_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q18300
setColumnDefaults
train
function setColumnDefaults(columns) { if (!columns) return; // Only one column should hold the tree view // Thus if multiple columns are provided with // isTreeColumn as true we take only the first one var treeColumnFound = false; for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) { var column = columns_1[_i]; if (!column.$$id) { column.$$id = id_1.id(); } // prop can be numeric; zero is valid not a missing prop // translate name => prop if (isNullOrUndefined(column.prop) && column.name) { column.prop = camel_case_1.camelCase(column.name); } if (!column.$$valueGetter) { column.$$valueGetter = column_prop_getters_1.getterForProp(column.prop); } // format props if no name passed if (!isNullOrUndefined(column.prop) && isNullOrUndefined(column.name)) { column.name = camel_case_1.deCamelCase(String(column.prop)); } if (isNullOrUndefined(column.prop) && isNullOrUndefined(column.name)) { column.name = ''; // Fixes IE and Edge displaying `null` } if (!column.hasOwnProperty('resizeable')) { column.resizeable = true; } if (!column.hasOwnProperty('sortable')) { column.sortable = true; } if (!column.hasOwnProperty('draggable')) { column.draggable = true; } if (!column.hasOwnProperty('canAutoResize')) { column.canAutoResize = true; } if (!column.hasOwnProperty('width')) { column.width = 150; } if (!column.hasOwnProperty('isTreeColumn')) { column.isTreeColumn = false; } else { if (column.isTreeColumn && !treeColumnFound) { // If the first column with isTreeColumn is true found // we mark that treeCoulmn is found treeColumnFound = true; } else { // After that isTreeColumn property for any other column // will be set as false column.isTreeColumn = false; } } } }
javascript
{ "resource": "" }
q18301
translateTemplates
train
function translateTemplates(templates) { var result = []; for (var _i = 0, templates_1 = templates; _i < templates_1.length; _i++) { var temp = templates_1[_i]; var col = {}; var props = Object.getOwnPropertyNames(temp); for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; col[prop] = temp[prop]; } if (temp.headerTemplate) { col.headerTemplate = temp.headerTemplate; } if (temp.cellTemplate) { col.cellTemplate = temp.cellTemplate; } if (temp.summaryFunc) { col.summaryFunc = temp.summaryFunc; } if (temp.summaryTemplate) { col.summaryTemplate = temp.summaryTemplate; } result.push(col); } return result; }
javascript
{ "resource": "" }
q18302
getterForProp
train
function getterForProp(prop) { if (prop == null) return emptyStringGetter; if (typeof prop === 'number') { return numericIndexGetter; } else { // deep or simple if (prop.indexOf('.') !== -1) { return deepValueGetter; } else { return shallowValueGetter; } } }
javascript
{ "resource": "" }
q18303
numericIndexGetter
train
function numericIndexGetter(row, index) { if (row == null) return ''; // mimic behavior of deepValueGetter if (!row || index == null) return row; var value = row[index]; if (value == null) return ''; return value; }
javascript
{ "resource": "" }
q18304
ChainableTemporaryCredentials
train
function ChainableTemporaryCredentials(options) { AWS.Credentials.call(this); options = options || {}; this.errorCode = 'ChainableTemporaryCredentialsProviderFailure'; this.expired = true; this.tokenCodeFn = null; var params = AWS.util.copy(options.params) || {}; if (params.RoleArn) { params.RoleSessionName = params.RoleSessionName || 'temporary-credentials'; } if (params.SerialNumber) { if (!options.tokenCodeFn || (typeof options.tokenCodeFn !== 'function')) { throw new AWS.util.error( new Error('tokenCodeFn must be a function when params.SerialNumber is given'), {code: this.errorCode} ); } else { this.tokenCodeFn = options.tokenCodeFn; } } this.service = new STS({ params: params, credentials: options.masterCredentials || AWS.config.credentials }); }
javascript
{ "resource": "" }
q18305
eventually
train
function eventually(callback, block, options) { if (!options) options = {}; if (!options.delay) options.delay = 0; if (!options.backoff) options.backoff = 500; if (!options.maxTime) options.maxTime = 5; var delay = options.delay; var started = this.AWS.util.date.getDate(); var self = this; var retry = function() { callback(); }; retry.fail = function(err) { var now = self.AWS.util.date.getDate(); if (now - started < options.maxTime * 1000) { setTimeout(function () { delay += options.backoff; block.call(self, retry); }, delay); } else { callback.fail(err || new Error('Eventually block timed out')); } }; block.call(this, retry); }
javascript
{ "resource": "" }
q18306
request
train
function request(svc, operation, params, next, extra) { var world = this; if (!svc) svc = this.service; if (typeof svc === 'string') svc = this[svc]; svc[operation](params, function(err, data) { world.response = this; world.error = err; world.data = data; try { if (typeof next.condition === 'function') { var condition = next.condition.call(world, world); if (!condition) { next.fail(new Error('Request success condition failed')); return; } } if (extra) { extra.call(world, world.response); next.call(world); } else if (extra !== false && err) { world.unexpectedError(world.response, next); } else { next.call(world); } } catch (err) { next.fail(err); } }); }
javascript
{ "resource": "" }
q18307
unexpectedError
train
function unexpectedError(resp, next) { var svc = resp.request.service.api.serviceName; var op = resp.request.operation; var code = resp.error.code; var msg = resp.error.message; var err = 'Received unexpected error from ' + svc + '.' + op + ', ' + code + ': ' + msg; next.fail(new Error(err)); }
javascript
{ "resource": "" }
q18308
train
function(bucket) { var fs = require('fs'); var path = require('path'); var filePath = path.resolve('integ.buckets.json'); var cache; if (fs.existsSync(filePath)) { try { cache = JSON.parse(fs.readFileSync(filePath)); cache.buckets.push(bucket); fs.writeFileSync(filePath, JSON.stringify(cache)); } catch (fileErr) { throw fileErr; } } else { cache = {}; cache.buckets = [bucket]; fs.writeFileSync(filePath, JSON.stringify(cache)); } }
javascript
{ "resource": "" }
q18309
train
function(size, name) { var fs = require('fs'); var path = require('path'); name = this.uniqueName(name); // Cannot set this as a world property because the world // is cleaned up before the AfterFeatures hook is fired. var fixturePath = path.resolve('./features/extra/fixtures/tmp'); if (!fs.existsSync(fixturePath)) fs.mkdirSync(fixturePath); var filename = path.join(fixturePath, name); var body; if (typeof size === 'string') { switch (size) { case 'empty': body = new Buffer(0); break; case 'small': body = new Buffer(1024 * 1024); break; case 'large': body = new Buffer(1024 * 1024 * 20); break; } } else if (typeof size === 'number') { body = new Buffer(size); } fs.writeFileSync(filename, body); return filename; }
javascript
{ "resource": "" }
q18310
train
function(size) { var match; var buffer; if (match = size.match(/(\d+)KB/)) { buffer = new Buffer(parseInt(match[1]) * 1024); } else if (match = size.match(/(\d+)MB/)) { buffer = new Buffer(parseInt(match[1]) * 1024 * 1024); } else { switch (size) { case 'empty': buffer = new Buffer(0); break; case 'small': buffer = new Buffer(1024 * 1024); break; case 'large': buffer = new Buffer(1024 * 1024 * 20); break; default: return new Buffer(1024 * 1024); } } buffer.fill('x'); return buffer; }
javascript
{ "resource": "" }
q18311
eventMessageChunker
train
function eventMessageChunker(buffer) { /** @type Buffer[] */ var messages = []; var offset = 0; while (offset < buffer.length) { var totalLength = buffer.readInt32BE(offset); // create new buffer for individual message (shares memory with original) var message = buffer.slice(offset, totalLength + offset); // increment offset to it starts at the next message offset += totalLength; messages.push(message); } return messages; }
javascript
{ "resource": "" }
q18312
SharedIniFileCredentials
train
function SharedIniFileCredentials(options) { AWS.Credentials.call(this); options = options || {}; this.filename = options.filename; this.profile = options.profile || process.env.AWS_PROFILE || AWS.util.defaultProfile; this.disableAssumeRole = Boolean(options.disableAssumeRole); this.preferStaticCredentials = Boolean(options.preferStaticCredentials); this.tokenCodeFn = options.tokenCodeFn || null; this.httpOptions = options.httpOptions || null; this.get(options.callback || AWS.util.fn.noop); }
javascript
{ "resource": "" }
q18313
escapeAttribute
train
function escapeAttribute(value) { return value.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
javascript
{ "resource": "" }
q18314
clearCache
train
function clearCache() { this._identityId = null; delete this.params.IdentityId; var poolId = this.params.IdentityPoolId; var loginId = this.params.LoginId || ''; delete this.storage[this.localStorageKey.id + poolId + loginId]; delete this.storage[this.localStorageKey.providers + poolId + loginId]; }
javascript
{ "resource": "" }
q18315
loadWaiterConfig
train
function loadWaiterConfig(state) { if (!this.service.api.waiters[state]) { throw new AWS.util.error(new Error(), { code: 'StateNotFoundError', message: 'State ' + state + ' not found.' }); } this.config = AWS.util.copy(this.service.api.waiters[state]); }
javascript
{ "resource": "" }
q18316
XmlNode
train
function XmlNode(name, children) { if (children === void 0) { children = []; } this.name = name; this.children = children; this.attributes = {}; }
javascript
{ "resource": "" }
q18317
eachPage
train
function eachPage(callback) { // Make all callbacks async-ish callback = AWS.util.fn.makeAsync(callback, 3); function wrappedCallback(response) { callback.call(response, response.error, response.data, function (result) { if (result === false) return; if (response.hasNextPage()) { response.nextPage().on('complete', wrappedCallback).send(); } else { callback.call(response, null, null, AWS.util.fn.noop); } }); } this.on('complete', wrappedCallback).send(); }
javascript
{ "resource": "" }
q18318
eachItem
train
function eachItem(callback) { var self = this; function wrappedCallback(err, data) { if (err) return callback(err, null); if (data === null) return callback(null, null); var config = self.service.paginationConfig(self.operation); var resultKey = config.resultKey; if (Array.isArray(resultKey)) resultKey = resultKey[0]; var items = jmespath.search(data, resultKey); var continueIteration = true; AWS.util.arrayEach(items, function(item) { continueIteration = callback(null, item); if (continueIteration === false) { return AWS.util.abort; } }); return continueIteration; } this.eachPage(wrappedCallback); }
javascript
{ "resource": "" }
q18319
Publisher
train
function Publisher(options) { // handle configuration options = options || {}; this.enabled = options.enabled || false; this.port = options.port || 31000; this.clientId = options.clientId || ''; if (this.clientId.length > 255) { // ClientId has a max length of 255 this.clientId = this.clientId.substr(0, 255); } this.messagesInFlight = 0; this.address = 'localhost'; }
javascript
{ "resource": "" }
q18320
removeVirtualHostedBucketFromPath
train
function removeVirtualHostedBucketFromPath(req) { var httpRequest = req.httpRequest; var bucket = httpRequest.virtualHostedBucket; if (bucket && httpRequest.path) { if (req.params && req.params.Key) { var encodedS3Key = '/' + AWS.util.uriEscapePath(req.params.Key); if (httpRequest.path.indexOf(encodedS3Key) === 0 && (httpRequest.path.length === encodedS3Key.length || httpRequest.path[encodedS3Key.length] === '?')) { //path only contains key or path contains only key and querystring return; } } httpRequest.path = httpRequest.path.replace(new RegExp('/' + bucket), ''); if (httpRequest.path[0] !== '/') { httpRequest.path = '/' + httpRequest.path; } } }
javascript
{ "resource": "" }
q18321
addContentType
train
function addContentType(req) { var httpRequest = req.httpRequest; if (httpRequest.method === 'GET' || httpRequest.method === 'HEAD') { // Content-Type is not set in GET/HEAD requests delete httpRequest.headers['Content-Type']; return; } if (!httpRequest.headers['Content-Type']) { // always have a Content-Type httpRequest.headers['Content-Type'] = 'application/octet-stream'; } var contentType = httpRequest.headers['Content-Type']; if (AWS.util.isBrowser()) { if (typeof httpRequest.body === 'string' && !contentType.match(/;\s*charset=/)) { var charset = '; charset=UTF-8'; httpRequest.headers['Content-Type'] += charset; } else { var replaceFn = function(_, prefix, charsetName) { return prefix + charsetName.toUpperCase(); }; httpRequest.headers['Content-Type'] = contentType.replace(/(;\s*charset=)(.+)$/, replaceFn); } } }
javascript
{ "resource": "" }
q18322
computeContentMd5
train
function computeContentMd5(req) { if (req.service.willComputeChecksums(req)) { var md5 = AWS.util.crypto.md5(req.httpRequest.body, 'base64'); req.httpRequest.headers['Content-MD5'] = md5; } }
javascript
{ "resource": "" }
q18323
dnsCompatibleBucketName
train
function dnsCompatibleBucketName(bucketName) { var b = bucketName; var domain = new RegExp(/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/); var ipAddress = new RegExp(/(\d+\.){3}\d+/); var dots = new RegExp(/\.\./); return (b.match(domain) && !b.match(ipAddress) && !b.match(dots)) ? true : false; }
javascript
{ "resource": "" }
q18324
updateReqBucketRegion
train
function updateReqBucketRegion(request, region) { var httpRequest = request.httpRequest; if (typeof region === 'string' && region.length) { httpRequest.region = region; } if (!httpRequest.endpoint.host.match(/s3(?!-accelerate).*\.amazonaws\.com$/)) { return; } var service = request.service; var s3Config = service.config; var s3BucketEndpoint = s3Config.s3BucketEndpoint; if (s3BucketEndpoint) { delete s3Config.s3BucketEndpoint; } var newConfig = AWS.util.copy(s3Config); delete newConfig.endpoint; newConfig.region = httpRequest.region; httpRequest.endpoint = (new AWS.S3(newConfig)).endpoint; service.populateURI(request); s3Config.s3BucketEndpoint = s3BucketEndpoint; httpRequest.headers.Host = httpRequest.endpoint.host; if (request._asm.currentState === 'validate') { request.removeListener('build', service.populateURI); request.addListener('build', service.removeVirtualHostedBucketFromPath); } }
javascript
{ "resource": "" }
q18325
extractError
train
function extractError(resp) { var codes = { 304: 'NotModified', 403: 'Forbidden', 400: 'BadRequest', 404: 'NotFound' }; var req = resp.request; var code = resp.httpResponse.statusCode; var body = resp.httpResponse.body || ''; var headers = resp.httpResponse.headers || {}; var region = headers['x-amz-bucket-region'] || null; var bucket = req.params.Bucket || null; var bucketRegionCache = req.service.bucketRegionCache; if (region && bucket && region !== bucketRegionCache[bucket]) { bucketRegionCache[bucket] = region; } var cachedRegion; if (codes[code] && body.length === 0) { if (bucket && !region) { cachedRegion = bucketRegionCache[bucket] || null; if (cachedRegion !== req.httpRequest.region) { region = cachedRegion; } } resp.error = AWS.util.error(new Error(), { code: codes[code], message: null, region: region }); } else { var data = new AWS.XML.Parser().parse(body.toString()); if (data.Region && !region) { region = data.Region; if (bucket && region !== bucketRegionCache[bucket]) { bucketRegionCache[bucket] = region; } } else if (bucket && !region && !data.Region) { cachedRegion = bucketRegionCache[bucket] || null; if (cachedRegion !== req.httpRequest.region) { region = cachedRegion; } } resp.error = AWS.util.error(new Error(), { code: data.Code || code, message: data.Message || null, region: region }); } req.service.extractRequestIds(resp); }
javascript
{ "resource": "" }
q18326
requestBucketRegion
train
function requestBucketRegion(resp, done) { var error = resp.error; var req = resp.request; var bucket = req.params.Bucket || null; if (!error || !bucket || error.region || req.operation === 'listObjects' || (AWS.util.isNode() && req.operation === 'headBucket') || (error.statusCode === 400 && req.operation !== 'headObject') || regionRedirectErrorCodes.indexOf(error.code) === -1) { return done(); } var reqOperation = AWS.util.isNode() ? 'headBucket' : 'listObjects'; var reqParams = {Bucket: bucket}; if (reqOperation === 'listObjects') reqParams.MaxKeys = 0; var regionReq = req.service[reqOperation](reqParams); regionReq._requestRegionForBucket = bucket; regionReq.send(function() { var region = req.service.bucketRegionCache[bucket] || null; error.region = region; done(); }); }
javascript
{ "resource": "" }
q18327
reqRegionForNetworkingError
train
function reqRegionForNetworkingError(resp, done) { if (!AWS.util.isBrowser()) { return done(); } var error = resp.error; var request = resp.request; var bucket = request.params.Bucket; if (!error || error.code !== 'NetworkingError' || !bucket || request.httpRequest.region === 'us-east-1') { return done(); } var service = request.service; var bucketRegionCache = service.bucketRegionCache; var cachedRegion = bucketRegionCache[bucket] || null; if (cachedRegion && cachedRegion !== request.httpRequest.region) { service.updateReqBucketRegion(request, cachedRegion); done(); } else if (!service.dnsCompatibleBucketName(bucket)) { service.updateReqBucketRegion(request, 'us-east-1'); if (bucketRegionCache[bucket] !== 'us-east-1') { bucketRegionCache[bucket] = 'us-east-1'; } done(); } else if (request.httpRequest.virtualHostedBucket) { var getRegionReq = service.listObjects({Bucket: bucket, MaxKeys: 0}); service.updateReqBucketRegion(getRegionReq, 'us-east-1'); getRegionReq._requestRegionForBucket = bucket; getRegionReq.send(function() { var region = service.bucketRegionCache[bucket] || null; if (region && region !== request.httpRequest.region) { service.updateReqBucketRegion(request, region); } done(); }); } else { // DNS-compatible path-style // (s3ForcePathStyle or bucket name with dot over https) // Cannot obtain region information for this case done(); } }
javascript
{ "resource": "" }
q18328
train
function(buckets) { var bucketRegionCache = this.bucketRegionCache; if (!buckets) { buckets = Object.keys(bucketRegionCache); } else if (typeof buckets === 'string') { buckets = [buckets]; } for (var i = 0; i < buckets.length; i++) { delete bucketRegionCache[buckets[i]]; } return bucketRegionCache; }
javascript
{ "resource": "" }
q18329
correctBucketRegionFromCache
train
function correctBucketRegionFromCache(req) { var bucket = req.params.Bucket || null; if (bucket) { var service = req.service; var requestRegion = req.httpRequest.region; var cachedRegion = service.bucketRegionCache[bucket]; if (cachedRegion && cachedRegion !== requestRegion) { service.updateReqBucketRegion(req, cachedRegion); } } }
javascript
{ "resource": "" }
q18330
extractRequestIds
train
function extractRequestIds(resp) { var extendedRequestId = resp.httpResponse.headers ? resp.httpResponse.headers['x-amz-id-2'] : null; var cfId = resp.httpResponse.headers ? resp.httpResponse.headers['x-amz-cf-id'] : null; resp.extendedRequestId = extendedRequestId; resp.cfId = cfId; if (resp.error) { resp.error.requestId = resp.requestId || null; resp.error.extendedRequestId = extendedRequestId; resp.error.cfId = cfId; } }
javascript
{ "resource": "" }
q18331
getSignedUrl
train
function getSignedUrl(operation, params, callback) { params = AWS.util.copy(params || {}); var expires = params.Expires || 900; delete params.Expires; // we can't validate this var request = this.makeRequest(operation, params); if (callback) { AWS.util.defer(function() { request.presign(expires, callback); }); } else { return request.presign(expires, callback); } }
javascript
{ "resource": "" }
q18332
createPresignedPost
train
function createPresignedPost(params, callback) { if (typeof params === 'function' && callback === undefined) { callback = params; params = null; } params = AWS.util.copy(params || {}); var boundParams = this.config.params || {}; var bucket = params.Bucket || boundParams.Bucket, self = this, config = this.config, endpoint = AWS.util.copy(this.endpoint); if (!config.s3BucketEndpoint) { endpoint.pathname = '/' + bucket; } function finalizePost() { return { url: AWS.util.urlFormat(endpoint), fields: self.preparePostFields( config.credentials, config.region, bucket, params.Fields, params.Conditions, params.Expires ) }; } if (callback) { config.getCredentials(function (err) { if (err) { callback(err); } callback(null, finalizePost()); }); } else { return finalizePost(); } }
javascript
{ "resource": "" }
q18333
convertInput
train
function convertInput(data, options) { options = options || {}; var type = typeOf(data); if (type === 'Object') { return formatMap(data, options); } else if (type === 'Array') { return formatList(data, options); } else if (type === 'Set') { return formatSet(data, options); } else if (type === 'String') { if (data.length === 0 && options.convertEmptyValues) { return convertInput(null); } return { S: data }; } else if (type === 'Number' || type === 'NumberValue') { return { N: data.toString() }; } else if (type === 'Binary') { if (data.length === 0 && options.convertEmptyValues) { return convertInput(null); } return { B: data }; } else if (type === 'Boolean') { return { BOOL: data }; } else if (type === 'null') { return { NULL: true }; } else if (type !== 'undefined' && type !== 'Function') { // this value has a custom constructor return formatMap(data, options); } }
javascript
{ "resource": "" }
q18334
marshallItem
train
function marshallItem(data, options) { return AWS.DynamoDB.Converter.input(data, options).M; }
javascript
{ "resource": "" }
q18335
convertOutput
train
function convertOutput(data, options) { options = options || {}; var list, map, i; for (var type in data) { var values = data[type]; if (type === 'M') { map = {}; for (var key in values) { map[key] = convertOutput(values[key], options); } return map; } else if (type === 'L') { list = []; for (i = 0; i < values.length; i++) { list.push(convertOutput(values[i], options)); } return list; } else if (type === 'SS') { list = []; for (i = 0; i < values.length; i++) { list.push(values[i] + ''); } return new DynamoDBSet(list); } else if (type === 'NS') { list = []; for (i = 0; i < values.length; i++) { list.push(convertNumber(values[i], options.wrapNumbers)); } return new DynamoDBSet(list); } else if (type === 'BS') { list = []; for (i = 0; i < values.length; i++) { list.push(new util.Buffer(values[i])); } return new DynamoDBSet(list); } else if (type === 'S') { return values + ''; } else if (type === 'N') { return convertNumber(values, options.wrapNumbers); } else if (type === 'B') { return new util.Buffer(values); } else if (type === 'BOOL') { return (values === 'true' || values === 'TRUE' || values === true); } else if (type === 'NULL') { return null; } } }
javascript
{ "resource": "" }
q18336
unmarshall
train
function unmarshall(data, options) { return AWS.DynamoDB.Converter.output({M: data}, options); }
javascript
{ "resource": "" }
q18337
populateHostPrefix
train
function populateHostPrefix(request) { var enabled = request.service.config.hostPrefixEnabled; if (!enabled) return request; var operationModel = request.service.api.operations[request.operation]; //don't marshal host prefix when operation has endpoint discovery traits if (hasEndpointDiscover(request)) return request; if (operationModel.endpoint && operationModel.endpoint.hostPrefix) { var hostPrefixNotation = operationModel.endpoint.hostPrefix; var hostPrefix = expandHostPrefix(hostPrefixNotation, request.params, operationModel.input); prependEndpointPrefix(request.httpRequest.endpoint, hostPrefix); validateHostname(request.httpRequest.endpoint.hostname); } return request; }
javascript
{ "resource": "" }
q18338
loadFromPath
train
function loadFromPath(path) { this.clear(); var options = JSON.parse(AWS.util.readFileSync(path)); var fileSystemCreds = new AWS.FileSystemCredentials(path); var chain = new AWS.CredentialProviderChain(); chain.providers.unshift(fileSystemCreds); chain.resolve(function (err, creds) { if (err) throw err; else options.credentials = creds; }); this.constructor(options); return this; }
javascript
{ "resource": "" }
q18339
extractCredentials
train
function extractCredentials(options) { if (options.accessKeyId && options.secretAccessKey) { options = AWS.util.copy(options); options.credentials = new AWS.Credentials(options); } return options; }
javascript
{ "resource": "" }
q18340
setPromisesDependency
train
function setPromisesDependency(dep) { PromisesDependency = dep; // if null was passed in, we should try to use native promises if (dep === null && typeof Promise === 'function') { PromisesDependency = Promise; } var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain]; if (AWS.S3 && AWS.S3.ManagedUpload) constructors.push(AWS.S3.ManagedUpload); AWS.util.addPromises(constructors, PromisesDependency); }
javascript
{ "resource": "" }
q18341
train
function() { $('div[id] > :header:first').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this headline')). appendTo(this); }); $('dt[id]').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this definition')). appendTo(this); }); }
javascript
{ "resource": "" }
q18342
train
function() { if (document.location.hash && $.browser.mozilla) window.setTimeout(function() { document.location.href += ''; }, 10); }
javascript
{ "resource": "" }
q18343
train
function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); if (src.substr(-9) == 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { togglers.click(); } }
javascript
{ "resource": "" }
q18344
train
function() { var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { if (this == '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); }
javascript
{ "resource": "" }
q18345
Service
train
function Service(config) { if (!this.loadServiceClass) { throw AWS.util.error(new Error(), 'Service must be constructed with `new\' operator'); } var ServiceClass = this.loadServiceClass(config || {}); if (ServiceClass) { var originalConfig = AWS.util.copy(config); var svc = new ServiceClass(config); Object.defineProperty(svc, '_originalConfig', { get: function() { return originalConfig; }, enumerable: false, configurable: true }); svc._clientId = ++clientCount; return svc; } this.initialize(config); }
javascript
{ "resource": "" }
q18346
makeRequest
train
function makeRequest(operation, params, callback) { if (typeof params === 'function') { callback = params; params = null; } params = params || {}; if (this.config.params) { // copy only toplevel bound params var rules = this.api.operations[operation]; if (rules) { params = AWS.util.copy(params); AWS.util.each(this.config.params, function(key, value) { if (rules.input.members[key]) { if (params[key] === undefined || params[key] === null) { params[key] = value; } } }); } } var request = new AWS.Request(this, operation, params); this.addAllRequestListeners(request); this.attachMonitoringEmitter(request); if (callback) request.send(callback); return request; }
javascript
{ "resource": "" }
q18347
makeUnauthenticatedRequest
train
function makeUnauthenticatedRequest(operation, params, callback) { if (typeof params === 'function') { callback = params; params = {}; } var request = this.makeRequest(operation, params).toUnauthenticated(); return callback ? request.send(callback) : request; }
javascript
{ "resource": "" }
q18348
waitFor
train
function waitFor(state, params, callback) { var waiter = new AWS.ResourceWaiter(this, state); return waiter.wait(params, callback); }
javascript
{ "resource": "" }
q18349
apiCallEvent
train
function apiCallEvent(request) { var api = request.service.api.operations[request.operation]; var monitoringEvent = { Type: 'ApiCall', Api: api ? api.name : request.operation, Version: 1, Service: request.service.api.serviceId || request.service.api.endpointPrefix, Region: request.httpRequest.region, MaxRetriesExceeded: 0, UserAgent: request.httpRequest.getUserAgent(), }; var response = request.response; if (response.httpResponse.statusCode) { monitoringEvent.FinalHttpStatusCode = response.httpResponse.statusCode; } if (response.error) { var error = response.error; var statusCode = response.httpResponse.statusCode; if (statusCode > 299) { if (error.code) monitoringEvent.FinalAwsException = error.code; if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message; } else { if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name; if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message; } } return monitoringEvent; }
javascript
{ "resource": "" }
q18350
apiAttemptEvent
train
function apiAttemptEvent(request) { var api = request.service.api.operations[request.operation]; var monitoringEvent = { Type: 'ApiCallAttempt', Api: api ? api.name : request.operation, Version: 1, Service: request.service.api.serviceId || request.service.api.endpointPrefix, Fqdn: request.httpRequest.endpoint.hostname, UserAgent: request.httpRequest.getUserAgent(), }; var response = request.response; if (response.httpResponse.statusCode) { monitoringEvent.HttpStatusCode = response.httpResponse.statusCode; } if ( !request._unAuthenticated && request.service.config.credentials && request.service.config.credentials.accessKeyId ) { monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId; } if (!response.httpResponse.headers) return monitoringEvent; if (request.httpRequest.headers['x-amz-security-token']) { monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token']; } if (response.httpResponse.headers['x-amzn-requestid']) { monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid']; } if (response.httpResponse.headers['x-amz-request-id']) { monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id']; } if (response.httpResponse.headers['x-amz-id-2']) { monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2']; } return monitoringEvent; }
javascript
{ "resource": "" }
q18351
attemptFailEvent
train
function attemptFailEvent(request) { var monitoringEvent = this.apiAttemptEvent(request); var response = request.response; var error = response.error; if (response.httpResponse.statusCode > 299 ) { if (error.code) monitoringEvent.AwsException = error.code; if (error.message) monitoringEvent.AwsExceptionMessage = error.message; } else { if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name; if (error.message) monitoringEvent.SdkExceptionMessage = error.message; } return monitoringEvent; }
javascript
{ "resource": "" }
q18352
attachMonitoringEmitter
train
function attachMonitoringEmitter(request) { var attemptTimestamp; //timestamp marking the beginning of a request attempt var attemptStartRealTime; //Start time of request attempt. Used to calculating attemptLatency var attemptLatency; //latency from request sent out to http response reaching SDK var callStartRealTime; //Start time of API call. Used to calculating API call latency var attemptCount = 0; //request.retryCount is not reliable here var region; //region cache region for each attempt since it can be updated in plase (e.g. s3) var callTimestamp; //timestamp when the request is created var self = this; var addToHead = true; request.on('validate', function () { callStartRealTime = AWS.util.realClock.now(); callTimestamp = Date.now(); }, addToHead); request.on('sign', function () { attemptStartRealTime = AWS.util.realClock.now(); attemptTimestamp = Date.now(); region = request.httpRequest.region; attemptCount++; }, addToHead); request.on('validateResponse', function() { attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime); }); request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() { var apiAttemptEvent = self.apiAttemptEvent(request); apiAttemptEvent.Timestamp = attemptTimestamp; apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0; apiAttemptEvent.Region = region; self.emit('apiCallAttempt', [apiAttemptEvent]); }); request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() { var apiAttemptEvent = self.attemptFailEvent(request); apiAttemptEvent.Timestamp = attemptTimestamp; //attemptLatency may not be available if fail before response attemptLatency = attemptLatency || Math.round(AWS.util.realClock.now() - attemptStartRealTime); apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0; apiAttemptEvent.Region = region; self.emit('apiCallAttempt', [apiAttemptEvent]); }); request.addNamedListener('API_CALL', 'complete', function API_CALL() { var apiCallEvent = self.apiCallEvent(request); apiCallEvent.AttemptCount = attemptCount; if (apiCallEvent.AttemptCount <= 0) return; apiCallEvent.Timestamp = callTimestamp; var latency = Math.round(AWS.util.realClock.now() - callStartRealTime); apiCallEvent.Latency = latency >= 0 ? latency : 0; var response = request.response; if ( typeof response.retryCount === 'number' && typeof response.maxRetries === 'number' && (response.retryCount >= response.maxRetries) ) { apiCallEvent.MaxRetriesExceeded = 1; } self.emit('apiCall', [apiCallEvent]); }); }
javascript
{ "resource": "" }
q18353
getSignerClass
train
function getSignerClass(request) { var version; // get operation authtype if present var operation = null; var authtype = ''; if (request) { var operations = request.service.api.operations || {}; operation = operations[request.operation] || null; authtype = operation ? operation.authtype : ''; } if (this.config.signatureVersion) { version = this.config.signatureVersion; } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') { version = 'v4'; } else { version = this.api.signatureVersion; } return AWS.Signers.RequestSigner.getVersion(version); }
javascript
{ "resource": "" }
q18354
defineMethods
train
function defineMethods(svc) { AWS.util.each(svc.prototype.api.operations, function iterator(method) { if (svc.prototype[method]) return; var operation = svc.prototype.api.operations[method]; if (operation.authtype === 'none') { svc.prototype[method] = function (params, callback) { return this.makeUnauthenticatedRequest(method, params, callback); }; } else { svc.prototype[method] = function (params, callback) { return this.makeRequest(method, params, callback); }; } }); }
javascript
{ "resource": "" }
q18355
nextPage
train
function nextPage(callback) { var config; var service = this.request.service; var operation = this.request.operation; try { config = service.paginationConfig(operation, true); } catch (e) { this.error = e; } if (!this.hasNextPage()) { if (callback) callback(this.error, null); else if (this.error) throw this.error; return null; } var params = AWS.util.copy(this.request.params); if (!this.nextPageTokens) { return callback ? callback(null, null) : null; } else { var inputTokens = config.inputToken; if (typeof inputTokens === 'string') inputTokens = [inputTokens]; for (var i = 0; i < inputTokens.length; i++) { params[inputTokens[i]] = this.nextPageTokens[i]; } return service.makeRequest(this.request.operation, params, callback); } }
javascript
{ "resource": "" }
q18356
toBuffer
train
function toBuffer(data, encoding) { return (typeof Buffer.from === 'function' && Buffer.from !== Uint8Array.from) ? Buffer.from(data, encoding) : new Buffer(data, encoding); }
javascript
{ "resource": "" }
q18357
train
function(query) { // create the required interface elements this.out = $('#search-results'); this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out); this.dots = $('<span></span>').appendTo(this.title); this.status = $('<p style="display: none"></p>').appendTo(this.out); this.output = $('<ul class="search"/>').appendTo(this.out); $('#search-progress').text(_('Preparing search...')); this.startPulse(); // index already loaded, the browser was quick! if (this.hasIndex()) this.query(query); else this.deferQuery(query); }
javascript
{ "resource": "" }
q18358
resolveMonitoringConfig
train
function resolveMonitoringConfig() { var config = { port: undefined, clientId: undefined, enabled: undefined, }; if (fromEnvironment(config) || fromConfigFile(config)) return toJSType(config); return toJSType(config); }
javascript
{ "resource": "" }
q18359
fromEnvironment
train
function fromEnvironment(config) { config.port = config.port || process.env.AWS_CSM_PORT; config.enabled = config.enabled || process.env.AWS_CSM_ENABLED; config.clientId = config.clientId || process.env.AWS_CSM_CLIENT_ID; return config.port && config.enabled && config.clientId || ['false', '0'].indexOf(config.enabled) >= 0; //no need to read shared config file if explicitely disabled }
javascript
{ "resource": "" }
q18360
fromConfigFile
train
function fromConfigFile(config) { var sharedFileConfig; try { var configFile = AWS.util.iniLoader.loadFrom({ isConfig: true, filename: process.env[AWS.util.sharedConfigFileEnv] }); var sharedFileConfig = configFile[ process.env.AWS_PROFILE || AWS.util.defaultProfile ]; } catch (err) { return false; } if (!sharedFileConfig) return config; config.port = config.port || sharedFileConfig.csm_port; config.enabled = config.enabled || sharedFileConfig.csm_enabled; config.clientId = config.clientId || sharedFileConfig.csm_client_id; return config.port && config.enabled && config.clientId; }
javascript
{ "resource": "" }
q18361
Signer
train
function Signer(keyPairId, privateKey) { if (keyPairId === void 0 || privateKey === void 0) { throw new Error('A key pair ID and private key are required'); } this.keyPairId = keyPairId; this.privateKey = privateKey; }
javascript
{ "resource": "" }
q18362
train
function (options, cb) { var signatureHash = 'policy' in options ? signWithCustomPolicy(options.policy, this.keyPairId, this.privateKey) : signWithCannedPolicy(options.url, options.expires, this.keyPairId, this.privateKey); var cookieHash = {}; for (var key in signatureHash) { if (Object.prototype.hasOwnProperty.call(signatureHash, key)) { cookieHash['CloudFront-' + key] = signatureHash[key]; } } return handleSuccess(cookieHash, cb); }
javascript
{ "resource": "" }
q18363
train
function (options, cb) { try { var resource = getResource(options.url); } catch (err) { return handleError(err, cb); } var parsedUrl = url.parse(options.url, true), signatureHash = Object.prototype.hasOwnProperty.call(options, 'policy') ? signWithCustomPolicy(options.policy, this.keyPairId, this.privateKey) : signWithCannedPolicy(resource, options.expires, this.keyPairId, this.privateKey); parsedUrl.search = null; for (var key in signatureHash) { if (Object.prototype.hasOwnProperty.call(signatureHash, key)) { parsedUrl.query[key] = signatureHash[key]; } } try { var signedUrl = determineScheme(options.url) === 'rtmp' ? getRtmpUrl(url.format(parsedUrl)) : url.format(parsedUrl); } catch (err) { return handleError(err, cb); } return handleSuccess(signedUrl, cb); }
javascript
{ "resource": "" }
q18364
train
function(list, iter, callback) { var item = list.shift(); iter(item, function(err) { if (err) return callback(err); else if (list.length) { eachSeries(list, iter, callback); } else { return callback(); } }); }
javascript
{ "resource": "" }
q18365
train
function(bucket, callback) { var s3 = new AWS.S3({maxRetries: 100}); var params = { Bucket: bucket }; s3.listObjects(params, function (err, data) { if (err) return callback(err); if (data.Contents.length > 0) { params.Delete = { Objects: [] }; data.Contents.forEach(function (item) { params.Delete.Objects.push({Key: item.Key}); }); s3.deleteObjects(params, callback); } else { callback(); } }); }
javascript
{ "resource": "" }
q18366
ProcessCredentials
train
function ProcessCredentials(options) { AWS.Credentials.call(this); options = options || {}; this.filename = options.filename; this.profile = options.profile || process.env.AWS_PROFILE || AWS.util.defaultProfile; this.get(options.callback || AWS.util.fn.noop); }
javascript
{ "resource": "" }
q18367
loadViaCredentialProcess
train
function loadViaCredentialProcess(profile, callback) { proc.exec(profile['credential_process'], function(err, stdOut, stdErr) { if (err) { callback(AWS.util.error( new Error('credential_process returned error'), { code: 'ProcessCredentialsProviderFailure'} ), null); } else { try { var credData = JSON.parse(stdOut); if (credData.Expiration) { var currentTime = AWS.util.date.getDate(); var expireTime = new Date(credData.Expiration); if (expireTime < currentTime) { throw Error('credential_process returned expired credentials'); } } if (credData.Version !== 1) { throw Error('credential_process does not return Version == 1'); } callback(null, credData); } catch (err) { callback(AWS.util.error( new Error(err.message), { code: 'ProcessCredentialsProviderFailure'} ), null); } } }); }
javascript
{ "resource": "" }
q18368
DocumentClient
train
function DocumentClient(options) { var self = this; self.options = options || {}; self.configure(self.options); }
javascript
{ "resource": "" }
q18369
allocBuffer
train
function allocBuffer(size) { if (typeof size !== 'number') { throw new Error('size passed to allocBuffer must be a number.'); } var buffer = typeof Buffer.alloc === 'function' ? Buffer.alloc(size) : new Buffer(size); buffer.fill(0); return buffer; }
javascript
{ "resource": "" }
q18370
addVersionJSONToChangelog
train
function addVersionJSONToChangelog(version, changes) { if (!changelog) readChangelog(); var entry = '\n\n## ' + version; changes.forEach(function(change) { entry += '\n* ' + change.type + ': ' + change.category + ': ' + change.description; }); var logParts = changelog.split(insertMarker); logParts[0] = logParts[0] .replace(versionMarkerReg, versionMarker.join(version)) + insertMarker; changelog = logParts.join(entry); }
javascript
{ "resource": "" }
q18371
ClientCreator
train
function ClientCreator() { this._metadata = require('../apis/metadata'); this._apisFolderPath = path.join(__dirname, '..', 'apis'); this._clientFolderPath = path.join(__dirname, '..', 'clients'); this._serviceCustomizationsFolderPath = path.join(__dirname, '..', 'lib', 'services'); this._packageJsonPath = path.join(__dirname, '..', 'package.json'); this._apiFileNames = null; }
javascript
{ "resource": "" }
q18372
marshallCustomIdentifiers
train
function marshallCustomIdentifiers(request, shape) { var identifiers = {}; marshallCustomIdentifiersHelper(identifiers, request.params, shape); return identifiers; }
javascript
{ "resource": "" }
q18373
optionalDiscoverEndpoint
train
function optionalDiscoverEndpoint(request) { var service = request.service; var api = service.api; var operationModel = api.operations ? api.operations[request.operation] : undefined; var inputShape = operationModel ? operationModel.input : undefined; var identifiers = marshallCustomIdentifiers(request, inputShape); var cacheKey = getCacheKey(request); if (Object.keys(identifiers).length > 0) { cacheKey = util.update(cacheKey, identifiers); if (operationModel) cacheKey.operation = operationModel.name; } var endpoints = AWS.endpointCache.get(cacheKey); if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') { //endpoint operation is being made but response not yet received //or endpoint operation just failed in 1 minute return; } else if (endpoints && endpoints.length > 0) { //found endpoint record from cache request.httpRequest.updateEndpoint(endpoints[0].Address); } else { //endpoint record not in cache or outdated. make discovery operation var endpointRequest = service.makeRequest(api.endpointOperation, { Operation: operationModel.name, Identifiers: identifiers, }); addApiVersionHeader(endpointRequest); endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK); //put in a placeholder for endpoints already requested, prevent //too much in-flight calls AWS.endpointCache.put(cacheKey, [{ Address: '', CachePeriodInMinutes: 1 }]); endpointRequest.send(function(err, data) { if (data && data.Endpoints) { AWS.endpointCache.put(cacheKey, data.Endpoints); } else if (err) { AWS.endpointCache.put(cacheKey, [{ Address: '', CachePeriodInMinutes: 1 //not to make more endpoint operation in next 1 minute }]); } }); } }
javascript
{ "resource": "" }
q18374
addApiVersionHeader
train
function addApiVersionHeader(endpointRequest) { var api = endpointRequest.service.api; var apiVersion = api.apiVersion; if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) { endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion; } }
javascript
{ "resource": "" }
q18375
invalidateCachedEndpoints
train
function invalidateCachedEndpoints(response) { var error = response.error; var httpResponse = response.httpResponse; if (error && (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421) ) { var request = response.request; var operations = request.service.api.operations || {}; var inputShape = operations[request.operation] ? operations[request.operation].input : undefined; var identifiers = marshallCustomIdentifiers(request, inputShape); var cacheKey = getCacheKey(request); if (Object.keys(identifiers).length > 0) { cacheKey = util.update(cacheKey, identifiers); if (operations[request.operation]) cacheKey.operation = operations[request.operation].name; } AWS.endpointCache.remove(cacheKey); } }
javascript
{ "resource": "" }
q18376
hasCustomEndpoint
train
function hasCustomEndpoint(client) { //if set endpoint is set for specific client, enable endpoint discovery will raise an error. if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) { throw util.error(new Error(), { code: 'ConfigurationException', message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.' }); }; var svcConfig = AWS.config[client.serviceIdentifier] || {}; return Boolean(AWS.config.endpoint || svcConfig.endpoint || (client._originalConfig && client._originalConfig.endpoint)); }
javascript
{ "resource": "" }
q18377
discoverEndpoint
train
function discoverEndpoint(request, done) { var service = request.service || {}; if (hasCustomEndpoint(service) || request.isPresigned()) return done(); if (!isEndpointDiscoveryApplicable(request)) return done(); request.httpRequest.appendToUserAgent('endpoint-discovery'); var operations = service.api.operations || {}; var operationModel = operations[request.operation]; var isEndpointDiscoveryRequired = operationModel ? operationModel.endpointDiscoveryRequired : 'NULL'; switch (isEndpointDiscoveryRequired) { case 'OPTIONAL': optionalDiscoverEndpoint(request); request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); done(); break; case 'REQUIRED': request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints); requiredDiscoverEndpoint(request, done); break; case 'NULL': default: done(); break; } }
javascript
{ "resource": "" }
q18378
ManagedUpload
train
function ManagedUpload(options) { var self = this; AWS.SequentialExecutor.call(self); self.body = null; self.sliceFn = null; self.callback = null; self.parts = {}; self.completeInfo = []; self.fillQueue = function() { self.callback(new Error('Unsupported body payload ' + typeof self.body)); }; self.configure(options); }
javascript
{ "resource": "" }
q18379
train
function(callback) { var self = this; self.failed = false; self.callback = callback || function(err) { if (err) throw err; }; var runFill = true; if (self.sliceFn) { self.fillQueue = self.fillBuffer; } else if (AWS.util.isNode()) { var Stream = AWS.util.stream.Stream; if (self.body instanceof Stream) { runFill = false; self.fillQueue = self.fillStream; self.partBuffers = []; self.body. on('error', function(err) { self.cleanup(err); }). on('readable', function() { self.fillQueue(); }). on('end', function() { self.isDoneChunking = true; self.numParts = self.totalPartNumbers; self.fillQueue.call(self); if (self.isDoneChunking && self.totalPartNumbers >= 1 && self.doneParts === self.numParts) { self.finishMultiPart(); } }); } } if (runFill) self.fillQueue.call(self); }
javascript
{ "resource": "" }
q18380
ParamValidator
train
function ParamValidator(validation) { if (validation === true || validation === undefined) { validation = {'min': true}; } this.validation = validation; }
javascript
{ "resource": "" }
q18381
Signer
train
function Signer(options) { options = options || {}; this.options = options; this.service = options.service; this.bindServiceObject(options); this._operations = {}; }
javascript
{ "resource": "" }
q18382
removeEventStreamOperations
train
function removeEventStreamOperations(model) { var modifiedModel = false; // loop over all operations var operations = model.operations; var operationNames = Object.keys(operations); for (var i = 0; i < operationNames.length; i++) { var operationName = operationNames[i]; var operation = operations[operationName]; // check input and output shapes var inputShapeName = operation.input && operation.input.shape; var outputShapeName = operation.output && operation.output.shape; var requiresEventStream = false; if (inputShapeName && hasEventStream(model.shapes[inputShapeName], model)) { requiresEventStream = true; } if (requiresEventStream) { modifiedModel = true; // remove the operation from the model console.log('Removing ' + operationName + ' because it depends on event streams on input.'); delete model.operations[operationName]; } } return modifiedModel; }
javascript
{ "resource": "" }
q18383
stringToBuffer
train
function stringToBuffer(data) { return (typeof Buffer.from === 'function' && Buffer.from !== Uint8Array.from) ? Buffer.from(data) : new Buffer(data); }
javascript
{ "resource": "" }
q18384
vGrow
train
function vGrow(yy, edge) { const c = matrix.findCellAt(sheetName, yy, cell.col); if (!c || !c.mark) { return false; } range[edge] = yy; c.mark = false; return true; }
javascript
{ "resource": "" }
q18385
hGrow
train
function hGrow(xx, edge) { const cells = []; for (y = range.top; y <= range.bottom; y++) { const c = matrix.findCellAt(sheetName, y, xx); if (c && c.mark) { cells.push(c); } else { return false; } } range[edge] = xx; for (let i = 0; i < cells.length; i++) { cells[i].mark = false; } return true; }
javascript
{ "resource": "" }
q18386
train
function(size) { var buffers; // read min(buffer, size || infinity) if (size) { buffers = []; while (size && this.buffers.length && !this.buffers[0].eod) { var first = this.buffers[0]; var buffer = first.read(size); size -= buffer.length; buffers.push(buffer); if (first.eod && first.full) { this.buffers.shift(); } } return Buffer.concat(buffers); } buffers = this.buffers.map(buf => buf.toBuffer()) .filter(Boolean); this.buffers = []; return Buffer.concat(buffers); }
javascript
{ "resource": "" }
q18387
train
function() { var topBlocks = this.workspace_.getTopBlocks(false); for (var i = 0, block; block = topBlocks[i]; i++) { block.removeSelect(); } }
javascript
{ "resource": "" }
q18388
train
function(menuOptions) { // Add the edit option at the end. menuOptions.push(Blockly.Procedures.makeEditOption(this)); // Find the delete option and update its callback to be specific to // functions. for (var i = 0, option; option = menuOptions[i]; i++) { if (option.text == Blockly.Msg.DELETE_BLOCK) { var input = this.getInput('custom_block'); // this is the root block, not the shadow block. if (input && input.connection && input.connection.targetBlock()) { var procCode = input.connection.targetBlock().getProcCode(); } else { return; } var rootBlock = this; option.callback = function() { var didDelete = Blockly.Procedures.deleteProcedureDefCallback( procCode, rootBlock); if (!didDelete) { // TODO:(#1151) alert('To delete a block definition, first remove all uses of the block'); } }; } } // Find and remove the duplicate option for (var i = 0, option; option = menuOptions[i]; i++) { if (option.text == Blockly.Msg.DUPLICATE) { menuOptions.splice(i, 1); break; } } }
javascript
{ "resource": "" }
q18389
train
function() { this.jsonInit({ "message0": Blockly.Msg.OPERATORS_MATHOP, "args0": [ { "type": "field_dropdown", "name": "OPERATOR", "options": [ [Blockly.Msg.OPERATORS_MATHOP_ABS, 'abs'], [Blockly.Msg.OPERATORS_MATHOP_FLOOR, 'floor'], [Blockly.Msg.OPERATORS_MATHOP_CEILING, 'ceiling'], [Blockly.Msg.OPERATORS_MATHOP_SQRT, 'sqrt'], [Blockly.Msg.OPERATORS_MATHOP_SIN, 'sin'], [Blockly.Msg.OPERATORS_MATHOP_COS, 'cos'], [Blockly.Msg.OPERATORS_MATHOP_TAN, 'tan'], [Blockly.Msg.OPERATORS_MATHOP_ASIN, 'asin'], [Blockly.Msg.OPERATORS_MATHOP_ACOS, 'acos'], [Blockly.Msg.OPERATORS_MATHOP_ATAN, 'atan'], [Blockly.Msg.OPERATORS_MATHOP_LN, 'ln'], [Blockly.Msg.OPERATORS_MATHOP_LOG, 'log'], [Blockly.Msg.OPERATORS_MATHOP_EEXP, 'e ^'], [Blockly.Msg.OPERATORS_MATHOP_10EXP, '10 ^'] ] }, { "type": "input_value", "name": "NUM" } ], "category": Blockly.Categories.operators, "extensions": ["colours_operators", "output_number"] }); }
javascript
{ "resource": "" }
q18390
randomColour
train
function randomColour() { var num = Math.floor(Math.random() * Math.pow(2, 24)); return '#' + ('00000' + num.toString(16)).substr(-6); }
javascript
{ "resource": "" }
q18391
train
function() { this.jsonInit({ "message0": Blockly.Msg.LOOKS_CHANGEEFFECTBY, "args0": [ { "type": "field_dropdown", "name": "EFFECT", "options": [ [Blockly.Msg.LOOKS_EFFECT_COLOR, 'COLOR'], [Blockly.Msg.LOOKS_EFFECT_FISHEYE, 'FISHEYE'], [Blockly.Msg.LOOKS_EFFECT_WHIRL, 'WHIRL'], [Blockly.Msg.LOOKS_EFFECT_PIXELATE, 'PIXELATE'], [Blockly.Msg.LOOKS_EFFECT_MOSAIC, 'MOSAIC'], [Blockly.Msg.LOOKS_EFFECT_BRIGHTNESS, 'BRIGHTNESS'], [Blockly.Msg.LOOKS_EFFECT_GHOST, 'GHOST'] ] }, { "type": "input_value", "name": "CHANGE" } ], "category": Blockly.Categories.looks, "extensions": ["colours_looks", "shape_statement"] }); }
javascript
{ "resource": "" }
q18392
train
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_dropdown", "name": "COSTUME", "options": [ ['costume1', 'COSTUME1'], ['costume2', 'COSTUME2'] ] } ], "colour": Blockly.Colours.looks.secondary, "colourSecondary": Blockly.Colours.looks.secondary, "colourTertiary": Blockly.Colours.looks.tertiary, "extensions": ["output_string"] }); }
javascript
{ "resource": "" }
q18393
train
function() { this.jsonInit({ "message0": Blockly.Msg.LOOKS_BACKDROPNUMBERNAME, "args0": [ { "type": "field_dropdown", "name": "NUMBER_NAME", "options": [ [Blockly.Msg.LOOKS_NUMBERNAME_NUMBER, 'number'], [Blockly.Msg.LOOKS_NUMBERNAME_NAME, 'name'] ] } ], "category": Blockly.Categories.looks, "checkboxInFlyout": true, "extensions": ["colours_looks", "output_number"] }); }
javascript
{ "resource": "" }
q18394
train
function() { this.jsonInit({ "id": "event_whenflagclicked", "message0": Blockly.Msg.EVENT_WHENFLAGCLICKED, "args0": [ { "type": "field_image", "src": Blockly.mainWorkspace.options.pathToMedia + "green-flag.svg", "width": 24, "height": 24, "alt": "flag" } ], "category": Blockly.Categories.event, "extensions": ["colours_event", "shape_hat"] }); }
javascript
{ "resource": "" }
q18395
train
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_variable", "name": "BROADCAST_OPTION", "variableTypes":[Blockly.BROADCAST_MESSAGE_VARIABLE_TYPE], "variable": Blockly.Msg.DEFAULT_BROADCAST_MESSAGE_NAME } ], "colour": Blockly.Colours.event.secondary, "colourSecondary": Blockly.Colours.event.secondary, "colourTertiary": Blockly.Colours.event.tertiary, "extensions": ["output_string"] }); }
javascript
{ "resource": "" }
q18396
train
function() { this.jsonInit({ "id": "event_whenkeypressed", "message0": Blockly.Msg.EVENT_WHENKEYPRESSED, "args0": [ { "type": "field_dropdown", "name": "KEY_OPTION", "options": [ [Blockly.Msg.EVENT_WHENKEYPRESSED_SPACE, 'space'], [Blockly.Msg.EVENT_WHENKEYPRESSED_UP, 'up arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_DOWN, 'down arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_RIGHT, 'right arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_LEFT, 'left arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_ANY, 'any'], ['a', 'a'], ['b', 'b'], ['c', 'c'], ['d', 'd'], ['e', 'e'], ['f', 'f'], ['g', 'g'], ['h', 'h'], ['i', 'i'], ['j', 'j'], ['k', 'k'], ['l', 'l'], ['m', 'm'], ['n', 'n'], ['o', 'o'], ['p', 'p'], ['q', 'q'], ['r', 'r'], ['s', 's'], ['t', 't'], ['u', 'u'], ['v', 'v'], ['w', 'w'], ['x', 'x'], ['y', 'y'], ['z', 'z'], ['0', '0'], ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'], ['7', '7'], ['8', '8'], ['9', '9'] ] } ], "category": Blockly.Categories.event, "extensions": ["colours_event", "shape_hat"] }); }
javascript
{ "resource": "" }
q18397
train
function() { this.jsonInit({ "message0": "%1", "args0": [ { "type": "field_dropdown", "name": "KEY_OPTION", "options": [ [Blockly.Msg.EVENT_WHENKEYPRESSED_SPACE, 'space'], [Blockly.Msg.EVENT_WHENKEYPRESSED_UP, 'up arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_DOWN, 'down arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_RIGHT, 'right arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_LEFT, 'left arrow'], [Blockly.Msg.EVENT_WHENKEYPRESSED_ANY, 'any'], ['a', 'a'], ['b', 'b'], ['c', 'c'], ['d', 'd'], ['e', 'e'], ['f', 'f'], ['g', 'g'], ['h', 'h'], ['i', 'i'], ['j', 'j'], ['k', 'k'], ['l', 'l'], ['m', 'm'], ['n', 'n'], ['o', 'o'], ['p', 'p'], ['q', 'q'], ['r', 'r'], ['s', 's'], ['t', 't'], ['u', 'u'], ['v', 'v'], ['w', 'w'], ['x', 'x'], ['y', 'y'], ['z', 'z'], ['0', '0'], ['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'], ['7', '7'], ['8', '8'], ['9', '9'] ] } ], "extensions": ["colours_sensing", "output_string"] }); }
javascript
{ "resource": "" }
q18398
train
function() { this.jsonInit({ "message0": Blockly.Msg.SENSING_SETDRAGMODE, "args0": [ { "type": "field_dropdown", "name": "DRAG_MODE", "options": [ [Blockly.Msg.SENSING_SETDRAGMODE_DRAGGABLE, 'draggable'], [Blockly.Msg.SENSING_SETDRAGMODE_NOTDRAGGABLE, 'not draggable'] ] } ], "category": Blockly.Categories.sensing, "extensions": ["colours_sensing", "shape_statement"] }); }
javascript
{ "resource": "" }
q18399
train
function() { this.jsonInit({ "message0": Blockly.Msg.SENSING_OF, "args0": [ { "type": "field_dropdown", "name": "PROPERTY", "options": [ [Blockly.Msg.SENSING_OF_XPOSITION, 'x position'], [Blockly.Msg.SENSING_OF_YPOSITION, 'y position'], [Blockly.Msg.SENSING_OF_DIRECTION, 'direction'], [Blockly.Msg.SENSING_OF_COSTUMENUMBER, 'costume #'], [Blockly.Msg.SENSING_OF_COSTUMENAME, 'costume name'], [Blockly.Msg.SENSING_OF_SIZE, 'size'], [Blockly.Msg.SENSING_OF_VOLUME, 'volume'], [Blockly.Msg.SENSING_OF_BACKDROPNUMBER, 'backdrop #'], [Blockly.Msg.SENSING_OF_BACKDROPNAME, 'backdrop name'] ] }, { "type": "input_value", "name": "OBJECT" } ], "output": true, "category": Blockly.Categories.sensing, "outputShape": Blockly.OUTPUT_SHAPE_ROUND, "extensions": ["colours_sensing"] }); }
javascript
{ "resource": "" }