_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q44900
findAttribute
train
function findAttribute(attrs, propName) { var index = Object.keys(attrs).filter(function (attr) { return attr.toLowerCase() === propName.toLowerCase(); })[0]; return attrs[index]; }
javascript
{ "resource": "" }
q44901
train
function() { var scopeProps = {}, config = {}; props.forEach(function(prop) { var propName = getPropName(prop); scopeProps[propName] = scope.$eval(findAttribute(attrs, propName)); config[propName] = getPropConfig(prop); }); scopeProps = applyFunctions(scopeProps, scope, config); scopeProps = angular.extend({}, scopeProps, injectableProps); renderComponent(reactComponent, scopeProps, scope, elem); }
javascript
{ "resource": "" }
q44902
netLogParser
train
function netLogParser(data) { data = (data || '{}').toString(); if (data.slice(data.length - 3) === ',\r\n') { data = data.slice(0, data.length - 3) + ']}'; } return JSON.parse(data); }
javascript
{ "resource": "" }
q44903
scriptToString
train
function scriptToString(data) { var script = []; data.forEach(function dataEach(step) { var key, value; if (typeof step === 'string') { script.push(step); } else if (typeof step === 'object') { key = [Object.keys(step)[0]]; value = step[key]; if (value !== undefined && value !== null && value !== '') { key = key.concat(value); } script.push(key.join(TAB)); } }); return script.join(NEWLINE); }
javascript
{ "resource": "" }
q44904
dryRun
train
function dryRun(config, path) { path = url.parse(path, true); return { url: url.format({ protocol: config.protocol, hostname: config.hostname, port: (config.port !== 80 && config.port !== 443 ? config.port : undefined), pathname: path.pathname, query: path.query }) }; }
javascript
{ "resource": "" }
q44905
normalizeServer
train
function normalizeServer(server) { // normalize hostname if (!reProtocol.test(server)) { server = 'http://' + server; } server = url.parse(server); return { protocol: server.protocol, hostname: server.hostname, auth: server.auth, pathname: server.pathname, port: parseInt(server.port, 10) || (server.protocol === 'https:' ? 443 : 80) }; }
javascript
{ "resource": "" }
q44906
localhost
train
function localhost(local, defaultPort) { // edge case when hostname:port is not informed via cli if (local === undefined || local === 'true') { local = [defaultPort]; } else { local = local.toString().split(':'); } return { hostname: reIp.test(local[0]) || isNaN(parseInt(local[0], 10)) && local[0] ? local[0] : os.hostname(), port: parseInt(local[1] || (!reIp.test(local[0]) && local[0]), 10) || defaultPort }; }
javascript
{ "resource": "" }
q44907
setQuery
train
function setQuery(map, options, query) { query = query || {}; options = options || {}; map.options.forEach(function eachOpts(opt) { Object.keys(opt).forEach(function eachOpt(key) { var param = opt[key], name = param.name, value = options[name] || options[key]; if (value !== undefined && param.api) { if (param.array) { value = [].concat(value).join(' '); } query[param.api] = param.bool ? param.invert ? (value ? 0 : 1) : (value ? 1 : 0) : value; } }); }); return query; }
javascript
{ "resource": "" }
q44908
setOptions
train
function setOptions(command, query) { var count, opts; command = commands[command]; if (!command) { return; } opts = {}; count = Object.keys(query).length; [options.common].concat(command.options).some(function someTypes(options) { if (!options) { return; } Object.keys(options).some(function someOptions(key) { var valid = options[key].valid; if (key in query) { if (options[key].bool) { opts[options[key].name] = !reBool.test(query[key]); } else if (!valid || (valid && valid.test(query[key]))) { opts[options[key].name] = decodeURIComponent(query[key]); } count -= 1; } return count === 0; }); return count === 0; }); return opts; }
javascript
{ "resource": "" }
q44909
baseDelay
train
function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined$1, args); }, wait); }
javascript
{ "resource": "" }
q44910
baseIntersection
train
function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined$1; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; }
javascript
{ "resource": "" }
q44911
castSlice
train
function castSlice(array, start, end) { var length = array.length; end = end === undefined$1 ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); }
javascript
{ "resource": "" }
q44912
createCurry
train
function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined$1, args, holders, undefined$1, undefined$1, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; }
javascript
{ "resource": "" }
q44913
createRecurry
train
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined$1, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); }
javascript
{ "resource": "" }
q44914
shuffleSelf
train
function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined$1 ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; }
javascript
{ "resource": "" }
q44915
last
train
function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined$1; }
javascript
{ "resource": "" }
q44916
take
train
function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined$1) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); }
javascript
{ "resource": "" }
q44917
template
train
function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined$1; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined$1, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
javascript
{ "resource": "" }
q44918
baseKeys
train
function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$7.call(object, key) && key != 'constructor') { result.push(key); } } return result; }
javascript
{ "resource": "" }
q44919
baseFilter
train
function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; }
javascript
{ "resource": "" }
q44920
baseIsEqual
train
function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); }
javascript
{ "resource": "" }
q44921
baseUniq
train
function baseUniq(array, iteratee, comparator) { var index = -1, includes = _arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = _arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE$1) { var set = iteratee ? null : _createSet(array); if (set) { return _setToArray(set); } isCommon = false; includes = _cacheHas; seen = new _SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; }
javascript
{ "resource": "" }
q44922
train
function (specificOptions, customParams, callback) { // Options - Default values const options = Object.assign({}, { urlPattern: ['/'], method: 'GET', successStatusCodes: [HTTP_CODE_200], failureStatusCodes: [], bodyProp: null, noparse: false, request: {} }, defaultOptions, specificOptions); // Create the url const url = buildUrl(options.urlPattern, customParams); // Build the actual request options const requestOptions = Object.assign({ method: options.method, url: url, headers: [], followAllRedirects: true, form: null, body: null }, options.request); // Do the request request(requestOptions, function (error, response, body) { if (error) { callback(error, response); return; } if ((Array.isArray(options.successStatusCodes) && !options.successStatusCodes.includes(response.statusCode)) || (Array.isArray(options.failureStatusCodes) && options.failureStatusCodes.includes(response.statusCode))) { callback(`Server returned unexpected status code: ${response.statusCode}`, response); return; } if (options.noparse) { // Wrap body in the response object if (typeof body === 'string') { body = { body: body }; } // Add location const location = response.headers.Location || response.headers.location; if (location) { body.location = location; } // Add status code body.statusCode = response.statusCode; callback(null, body); } else { tryParseJson(body, options.bodyProp, callback); } }); }
javascript
{ "resource": "" }
q44923
train
function (jobName, jobConfig, customParams, callback) { [jobName, jobConfig, customParams, callback] = doArgs(arguments, ['string', 'string', ['object', {}], 'function']); // Set the created job name! customParams.name = jobName; const self = this; doRequest({ method: 'POST', urlPattern: [JOB_CREATE], request: { body: jobConfig, headers: { 'Content-Type': 'application/xml' } }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.job_info(jobName, customParams, callback); }); }
javascript
{ "resource": "" }
q44924
train
function (viewName, viewConfig, customParams, callback) { [viewName, viewConfig, customParams, callback] = doArgs(arguments, ['string', 'object', ['object', {}], 'function']); viewConfig.json = JSON.stringify(viewConfig); const self = this; doRequest({ method: 'POST', urlPattern: [VIEW_CONFIG, viewName], request: { form: viewConfig // headers: {'content-type': 'application/x-www-form-urlencoded'}, }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.view_info(viewName, customParams, callback); }); }
javascript
{ "resource": "" }
q44925
train
function (viewName, customParams, callback) { [viewName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); doRequest({ urlPattern: [VIEW_INFO, viewName], bodyProp: 'jobs' }, customParams, callback); }
javascript
{ "resource": "" }
q44926
train
function (pluginName, customParams, callback) { [pluginName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); const body = `<jenkins><install plugin="${pluginName}" /></jenkins>`; doRequest({ method: 'POST', urlPattern: [INSTALL_PLUGIN], request: { body: body, headers: { 'Content-Type': 'text/xml' } }, noparse: true, bodyProp: 'plugins' }, customParams, callback); }
javascript
{ "resource": "" }
q44927
train
function (folderName, customParams, callback) { [folderName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']); const mode = 'com.cloudbees.hudson.plugins.folder.Folder'; customParams.name = folderName; customParams.mode = mode; customParams.Submit = 'OK'; doRequest({ method: 'POST', urlPattern: [NEWFOLDER] }, customParams, callback); }
javascript
{ "resource": "" }
q44928
appendParams
train
function appendParams(url, specificParams) { // Assign default and specific parameters var params = Object.assign({}, defaultParams, specificParams); // Stringify the querystring params var paramsString = qs.stringify(params); // Empty params if (paramsString === '') { return url; } // Does url contain parameters already? var delim = url.includes('?') ? '&' : '?'; return url + delim + paramsString; }
javascript
{ "resource": "" }
q44929
buildUrl
train
function buildUrl(urlPattern, customParams) { var url = formatUrl.apply(null, urlPattern); url = appendParams(url, customParams); return url; }
javascript
{ "resource": "" }
q44930
delete_build
train
function delete_build(jobName, buildNumber, customParams, callback) { var _doArgs21 = doArgs(arguments, ['string', 'string|number', ['object', {}], 'function']); var _doArgs22 = _slicedToArray(_doArgs21, 4); jobName = _doArgs22[0]; buildNumber = _doArgs22[1]; customParams = _doArgs22[2]; callback = _doArgs22[3]; doRequest({ method: 'POST', urlPattern: [BUILD_DELETE, jobName, buildNumber], noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); } else { data.body = 'Build ' + buildNumber + ' deleted.'; callback(null, data); } }); }
javascript
{ "resource": "" }
q44931
update_job
train
function update_job(jobName, jobConfig, customParams, callback) { var _doArgs29 = doArgs(arguments, ['string', 'string', ['object', {}], 'function']); var _doArgs30 = _slicedToArray(_doArgs29, 4); jobName = _doArgs30[0]; jobConfig = _doArgs30[1]; customParams = _doArgs30[2]; callback = _doArgs30[3]; doRequest({ method: 'POST', urlPattern: [JOB_CONFIG, jobName], request: { body: jobConfig, headers: { 'Content-Type': 'application/xml' } }, noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } // TODO rather return job_info ??? // const data = {name: jobName, location: response.headers['Location'] || response.headers['location']}; callback(null, { name: jobName }); }); }
javascript
{ "resource": "" }
q44932
enable_job
train
function enable_job(jobName, customParams, callback) { var _doArgs41 = doArgs(arguments, ['string', ['object', {}], 'function']); var _doArgs42 = _slicedToArray(_doArgs41, 3); jobName = _doArgs42[0]; customParams = _doArgs42[1]; callback = _doArgs42[2]; var self = this; doRequest({ method: 'POST', urlPattern: [JOB_ENABLE, jobName], noparse: true }, customParams, function (error, data) { if (error) { callback(error, data); return; } self.job_info(jobName, customParams, callback); }); }
javascript
{ "resource": "" }
q44933
tileToBBOX
train
function tileToBBOX(tile) { var e = tile2lon(tile[0] + 1, tile[2]); var w = tile2lon(tile[0], tile[2]); var s = tile2lat(tile[1] + 1, tile[2]); var n = tile2lat(tile[1], tile[2]); return [w, s, e, n]; }
javascript
{ "resource": "" }
q44934
tileToGeoJSON
train
function tileToGeoJSON(tile) { var bbox = tileToBBOX(tile); var poly = { type: 'Polygon', coordinates: [[ [bbox[0], bbox[1]], [bbox[0], bbox[3]], [bbox[2], bbox[3]], [bbox[2], bbox[1]], [bbox[0], bbox[1]] ]] }; return poly; }
javascript
{ "resource": "" }
q44935
pointToTile
train
function pointToTile(lon, lat, z) { var tile = pointToTileFraction(lon, lat, z); tile[0] = Math.floor(tile[0]); tile[1] = Math.floor(tile[1]); return tile; }
javascript
{ "resource": "" }
q44936
getChildren
train
function getChildren(tile) { return [ [tile[0] * 2, tile[1] * 2, tile[2] + 1], [tile[0] * 2 + 1, tile[1] * 2, tile[2 ] + 1], [tile[0] * 2 + 1, tile[1] * 2 + 1, tile[2] + 1], [tile[0] * 2, tile[1] * 2 + 1, tile[2] + 1] ]; }
javascript
{ "resource": "" }
q44937
hasSiblings
train
function hasSiblings(tile, tiles) { var siblings = getSiblings(tile); for (var i = 0; i < siblings.length; i++) { if (!hasTile(tiles, siblings[i])) return false; } return true; }
javascript
{ "resource": "" }
q44938
hasTile
train
function hasTile(tiles, tile) { for (var i = 0; i < tiles.length; i++) { if (tilesEqual(tiles[i], tile)) return true; } return false; }
javascript
{ "resource": "" }
q44939
tileToQuadkey
train
function tileToQuadkey(tile) { var index = ''; for (var z = tile[2]; z > 0; z--) { var b = 0; var mask = 1 << (z - 1); if ((tile[0] & mask) !== 0) b++; if ((tile[1] & mask) !== 0) b += 2; index += b.toString(); } return index; }
javascript
{ "resource": "" }
q44940
quadkeyToTile
train
function quadkeyToTile(quadkey) { var x = 0; var y = 0; var z = quadkey.length; for (var i = z; i > 0; i--) { var mask = 1 << (i - 1); var q = +quadkey[z - i]; if (q === 1) x |= mask; if (q === 2) y |= mask; if (q === 3) { x |= mask; y |= mask; } } return [x, y, z]; }
javascript
{ "resource": "" }
q44941
bboxToTile
train
function bboxToTile(bboxCoords) { var min = pointToTile(bboxCoords[0], bboxCoords[1], 32); var max = pointToTile(bboxCoords[2], bboxCoords[3], 32); var bbox = [min[0], min[1], max[0], max[1]]; var z = getBboxZoom(bbox); if (z === 0) return [0, 0, 0]; var x = bbox[0] >>> (32 - z); var y = bbox[1] >>> (32 - z); return [x, y, z]; }
javascript
{ "resource": "" }
q44942
pointToTileFraction
train
function pointToTileFraction(lon, lat, z) { var sin = Math.sin(lat * d2r), z2 = Math.pow(2, z), x = z2 * (lon / 360 + 0.5), y = z2 * (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); // Wrap Tile X x = x % z2 if (x < 0) x = x + z2 return [x, y, z]; }
javascript
{ "resource": "" }
q44943
addOptionals
train
function addOptionals(geojson, settings){ if(settings.crs && checkCRS(settings.crs)) { if(settings.isPostgres) geojson.geometry.crs = settings.crs; else geojson.crs = settings.crs; } if (settings.bbox) { geojson.bbox = settings.bbox; } if (settings.extraGlobal) { geojson.properties = {}; for (var key in settings.extraGlobal) { geojson.properties[key] = settings.extraGlobal[key]; } } }
javascript
{ "resource": "" }
q44944
checkCRS
train
function checkCRS(crs) { if (crs.type === 'name') { if (crs.properties && crs.properties.name) { return true; } else { throw new Error('Invalid CRS. Properties must contain "name" key'); } } else if (crs.type === 'link') { if (crs.properties && crs.properties.href && crs.properties.type) { return true; } else { throw new Error('Invalid CRS. Properties must contain "href" and "type" key'); } } else { throw new Error('Invald CRS. Type attribute must be "name" or "link"'); } }
javascript
{ "resource": "" }
q44945
setGeom
train
function setGeom(params) { params.geom = {}; for(var param in params) { if(params.hasOwnProperty(param) && geoms.indexOf(param) !== -1){ params.geom[param] = params[param]; delete params[param]; } } setGeomAttrList(params.geom); }
javascript
{ "resource": "" }
q44946
setGeomAttrList
train
function setGeomAttrList(params) { for(var param in params) { if(params.hasOwnProperty(param)) { if(typeof params[param] === 'string') { geomAttrs.push(params[param]); } else if (typeof params[param] === 'object') { // Array of coordinates for Point geomAttrs.push(params[param][0]); geomAttrs.push(params[param][1]); } } } if(geomAttrs.length === 0) { throw new Error('No geometry attributes specified'); } }
javascript
{ "resource": "" }
q44947
getFeature
train
function getFeature(args) { var item = args.item, params = args.params, propFunc = args.propFunc; var feature = { "type": "Feature" }; feature.geometry = buildGeom(item, params); feature.properties = propFunc.call(item); return feature; }
javascript
{ "resource": "" }
q44948
getPropFunction
train
function getPropFunction(params) { var func; if(!params.exclude && !params.include) { func = function(properties) { for(var attr in this) { if(this.hasOwnProperty(attr) && (geomAttrs.indexOf(attr) === -1)) { properties[attr] = this[attr]; } } }; } else if(params.include) { func = function(properties) { params.include.forEach(function(attr){ properties[attr] = this[attr]; }, this); }; } else if(params.exclude) { func = function(properties) { for(var attr in this) { if(this.hasOwnProperty(attr) && (geomAttrs.indexOf(attr) === -1) && (params.exclude.indexOf(attr) === -1)) { properties[attr] = this[attr]; } } }; } return function() { var properties = {}; func.call(this, properties); if(params.extra) { addExtra(properties, params.extra); } return properties; }; }
javascript
{ "resource": "" }
q44949
addExtra
train
function addExtra(properties, extra) { for(var key in extra){ if(extra.hasOwnProperty(key)) { properties[key] = extra[key]; } } return properties; }
javascript
{ "resource": "" }
q44950
fetchAllDependents
train
async function fetchAllDependents (name) { let pkg = await npm.getLatest(name) let deps = Object.keys(pkg.dependencies || {}) if (!deps.length) return [] let promises = [] for (let dep of deps) { promises.push(fetchAllDependents(dep)) } for (let subdeps of await Promise.all(promises)) { deps = deps.concat(subdeps) } return _.uniq(deps.sort()) }
javascript
{ "resource": "" }
q44951
createIconFiles
train
function createIconFiles(srcFile, dest) { const thisTaskName = swlog.logSubStart('create icon files'); return new Promise(resolve => { const exportArtboardsOptions = [ 'export', 'artboards', srcFile, `--formats=${options.iconFormats.join(',')}`, '--include-symbols=NO', '--save-for-web=YES', `--output=${dest}` ]; const outputStr = sketchtoolExec(exportArtboardsOptions.join(' ')); resolve(outputStr); }) .then(output => { options.iconFormats.forEach(format => { const regex = new RegExp(`\\.${format}`, 'g'); const count = (output.match(regex) || []).length; swlog.logTaskAction('Created', `${count} ${format.toUpperCase()} files`); }) swlog.logSubEnd(thisTaskName); if (options.iconFormats.indexOf('svg') !== -1) { return optimizeSVGs(dest); } }); }
javascript
{ "resource": "" }
q44952
sortByFileFormat
train
function sortByFileFormat(srcDir, format) { const initialFiles = `${srcDir}/*.${format}` const files = glob.sync(initialFiles); const dest = `${srcDir}/${format}`; let count = 0; createDirs([dest]); // Loop through and move each file const promises = files.map(f => { return new Promise((resolve, reject) => { const filename = sanitize(path.basename(f)); const reg = /[\w-]+-(16|24|32)\.[\w]+/; const match = filename.match(reg); let thisDest = dest; if (match) { const size = match[1]; thisDest = `${thisDest}/${size}`; createDirs([thisDest]); } fs.rename(f, `${thisDest}/${filename}`, err => { if (err) { reject(err); } count++; resolve(`${dest}/${filename}`); }); }); }); return Promise.all(promises).then(() => { swlog.logTaskAction('Moved', `${count}/${files.length} ${format.toUpperCase()} files`); }); }
javascript
{ "resource": "" }
q44953
createPagesMetadata
train
function createPagesMetadata(src, dest) { return new Promise((resolve, reject) => { const thisTaskName = swlog.logSubStart('create metadata file'); const outputStr = sketchtoolExec(`metadata ${src}`) const ignoredPages = ['Symbols', 'Icon Sheet', '------------'] let customObj = { categories: [] }; const dataObj = JSON.parse(outputStr); // Loop through pages, then arboards, to create a // simple mapping of names (ignoring certain pages) // and naming pages "categories" and artboards "icons" for (const pageId in dataObj.pagesAndArtboards) { if (dataObj.pagesAndArtboards.hasOwnProperty(pageId) && ! ignoredPages.includes(dataObj.pagesAndArtboards[pageId].name)) { const tempObj = { name: dataObj.pagesAndArtboards[pageId].name, icons: [] }; for (const ab in dataObj.pagesAndArtboards[pageId].artboards) { if (dataObj.pagesAndArtboards[pageId].artboards.hasOwnProperty(ab)) { tempObj.icons.push(dataObj.pagesAndArtboards[pageId].artboards[ab].name); } } tempObj.icons.sort(); customObj.categories.push(tempObj); } } fs.writeFileSync(`${dest}/metadata.json`, JSON.stringify(customObj, null, 4), 'utf-8'); swlog.logSubEnd(thisTaskName); resolve(); }); }
javascript
{ "resource": "" }
q44954
createDirs
train
function createDirs(arrPaths) { arrPaths.forEach(path => { if (!fs.existsSync(path)) { fs.mkdirSync(path); } }); }
javascript
{ "resource": "" }
q44955
optimizeSVGs
train
function optimizeSVGs(src) { const startOptimizeTaskName = swlog.logSubStart('optimize SVGs'); // Optimize with svgo: const svgoOptimize = new svgo({ js2svg: { useShortTags: false }, plugins: [ { removeViewBox: false }, { convertColors: { currentColor: '#000000' }}, { removeDimensions: true }, { moveGroupAttrsToElems: true }, { removeUselessStrokeAndFill: true }, { customSvgoRemoveGroupFill }, { customSvgoNonScalingStroke }, { customSvgoFillStroke } ] }); const svgFiles = glob.sync(`${src}/*.svg`); // Divide each optimization into a promise const svgPromises = svgFiles.map(async filepath => { try { const data = await readFile(filepath, 'utf8'); const dataOptimized = await svgoOptimize.optimize(data); await writeFile(filepath, dataOptimized.data, 'utf-8'); } catch(err) { swlog.error(err); } }); return Promise.all(svgPromises).then(() => { swlog.logSubEnd(startOptimizeTaskName); }).catch(swlog.error); }
javascript
{ "resource": "" }
q44956
getBumpTask
train
function getBumpTask(type) { return function () { return gulp.src(['./package.json', './bower.json']) .pipe(bump({ type: type })) .pipe(gulp.dest('./')); }; }
javascript
{ "resource": "" }
q44957
rereq
train
function rereq(options, done) { let req; req = https.request(options, (res) => { let chunk = ''; res.on('data', (data) => { chunk += data; }); res.on('end', () => { done(null, chunk.toString('utf8')); }); }); req.on('error', (e) => { done(e); }); req.end(); }
javascript
{ "resource": "" }
q44958
LightAssertionError
train
function LightAssertionError(options) { merge(this, options); if (!options.message) { Object.defineProperty(this, "message", { get: function() { if (!this._message) { this._message = this.generateMessage(); this.generatedMessage = true; } return this._message; } }); } }
javascript
{ "resource": "" }
q44959
train
function(expr) { if (expr) { return this; } var params = this.params; if ("obj" in params && !("actual" in params)) { params.actual = params.obj; } else if (!("obj" in params) && !("actual" in params)) { params.actual = this.obj; } params.stackStartFunction = params.stackStartFunction || this.assert; params.negate = this.negate; params.assertion = this; if (this.light) { throw new LightAssertionError(params); } else { throw new AssertionError(params); } }
javascript
{ "resource": "" }
q44960
has
train
function has(obj, key) { var type = getGlobalType(obj); var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'has'); return func(obj, key); }
javascript
{ "resource": "" }
q44961
get
train
function get(obj, key) { var type = getGlobalType(obj); var func = defaultTypeAdaptorStorage.requireAdaptor(type, 'get'); return func(obj, key); }
javascript
{ "resource": "" }
q44962
Compiler
train
function Compiler(options) { options = options || {}; Base.call(this, options); this.indentation = options.indent; }
javascript
{ "resource": "" }
q44963
mixin
train
function mixin(compiler) { compiler._comment = compiler.comment; compiler.map = new SourceMap(); compiler.position = { line: 1, column: 1 }; compiler.files = {}; for (var k in exports) compiler[k] = exports[k]; }
javascript
{ "resource": "" }
q44964
updatePosition
train
function updatePosition(str) { var lines = str.match(/\n/g); if (lines) lineno += lines.length; var i = str.lastIndexOf('\n'); column = ~i ? str.length - i : column + str.length; }
javascript
{ "resource": "" }
q44965
Position
train
function Position(start) { this.start = start; this.end = { line: lineno, column: column }; this.source = options.source; }
javascript
{ "resource": "" }
q44966
stylesheet
train
function stylesheet() { var rulesList = rules(); return { type: 'stylesheet', stylesheet: { source: options.source, rules: rulesList, parsingErrors: errorsList } }; }
javascript
{ "resource": "" }
q44967
rules
train
function rules() { var node; var rules = []; whitespace(); comments(rules); while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) { if (node !== false) { rules.push(node); comments(rules); } } return rules; }
javascript
{ "resource": "" }
q44968
match
train
function match(re) { var m = re.exec(css); if (!m) return; var str = m[0]; updatePosition(str); css = css.slice(str.length); return m; }
javascript
{ "resource": "" }
q44969
comments
train
function comments(rules) { var c; rules = rules || []; while (c = comment()) { if (c !== false) { rules.push(c); } } return rules; }
javascript
{ "resource": "" }
q44970
comment
train
function comment() { var pos = position(); if ('/' != css.charAt(0) || '*' != css.charAt(1)) return; var i = 2; while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i; i += 2; if ("" === css.charAt(i-1)) { return error('End of comment missing'); } var str = css.slice(2, i - 2); column += 2; updatePosition(str); css = css.slice(i); column += 2; return pos({ type: 'comment', comment: str }); }
javascript
{ "resource": "" }
q44971
selector
train
function selector() { var m = match(/^([^{]+)/); if (!m) return; /* @fix Remove all comments from selectors * http://ostermiller.org/findcomment.html */ return trim(m[0]) .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '') .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(m) { return m.replace(/,/g, '\u200C'); }) .split(/\s*(?![^(]*\)),\s*/) .map(function(s) { return s.replace(/\u200C/g, ','); }); }
javascript
{ "resource": "" }
q44972
declarations
train
function declarations() { var decls = []; if (!open()) return error("missing '{'"); comments(decls); // declarations var decl; while (decl = declaration()) { if (decl !== false) { decls.push(decl); comments(decls); } } if (!close()) return error("missing '}'"); return decls; }
javascript
{ "resource": "" }
q44973
keyframe
train
function keyframe() { var m; var vals = []; var pos = position(); while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) { vals.push(m[1]); match(/^,\s*/); } if (!vals.length) return; return pos({ type: 'keyframe', values: vals, declarations: declarations() }); }
javascript
{ "resource": "" }
q44974
atkeyframes
train
function atkeyframes() { var pos = position(); var m = match(/^@([-\w]+)?keyframes\s*/); if (!m) return; var vendor = m[1]; // identifier var m = match(/^([-\w]+)\s*/); if (!m) return error("@keyframes missing name"); var name = m[1]; if (!open()) return error("@keyframes missing '{'"); var frame; var frames = comments(); while (frame = keyframe()) { frames.push(frame); frames = frames.concat(comments()); } if (!close()) return error("@keyframes missing '}'"); return pos({ type: 'keyframes', name: name, vendor: vendor, keyframes: frames }); }
javascript
{ "resource": "" }
q44975
atsupports
train
function atsupports() { var pos = position(); var m = match(/^@supports *([^{]+)/); if (!m) return; var supports = trim(m[1]); if (!open()) return error("@supports missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@supports missing '}'"); return pos({ type: 'supports', supports: supports, rules: style }); }
javascript
{ "resource": "" }
q44976
atmedia
train
function atmedia() { var pos = position(); var m = match(/^@media *([^{]+)/); if (!m) return; var media = trim(m[1]); if (!open()) return error("@media missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@media missing '}'"); return pos({ type: 'media', media: media, rules: style }); }
javascript
{ "resource": "" }
q44977
atpage
train
function atpage() { var pos = position(); var m = match(/^@page */); if (!m) return; var sel = selector() || []; if (!open()) return error("@page missing '{'"); var decls = comments(); // declarations var decl; while (decl = declaration()) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) return error("@page missing '}'"); return pos({ type: 'page', selectors: sel, declarations: decls }); }
javascript
{ "resource": "" }
q44978
atdocument
train
function atdocument() { var pos = position(); var m = match(/^@([-\w]+)?document *([^{]+)/); if (!m) return; var vendor = trim(m[1]); var doc = trim(m[2]); if (!open()) return error("@document missing '{'"); var style = comments().concat(rules()); if (!close()) return error("@document missing '}'"); return pos({ type: 'document', document: doc, vendor: vendor, rules: style }); }
javascript
{ "resource": "" }
q44979
rule
train
function rule() { var pos = position(); var sel = selector(); if (!sel) return error('selector missing'); comments(); return pos({ type: 'rule', selectors: sel, declarations: declarations() }); }
javascript
{ "resource": "" }
q44980
addParent
train
function addParent(obj, parent) { var isNode = obj && typeof obj.type === 'string'; var childParent = isNode ? obj : parent; for (var k in obj) { var value = obj[k]; if (Array.isArray(value)) { value.forEach(function(v) { addParent(v, childParent); }); } else if (value && typeof value === 'object') { addParent(value, childParent); } } if (isNode) { Object.defineProperty(obj, 'parent', { configurable: true, writable: true, enumerable: false, value: parent || null }); } return obj; }
javascript
{ "resource": "" }
q44981
getElementTop
train
function getElementTop(el) { let top = 0; let element = el; do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); return top; }
javascript
{ "resource": "" }
q44982
getUnit
train
function getUnit(property, unit) { let propertyUnit = unit || DEFAULT_UNIT; if (ANGLE_PROPERTIES.indexOf(property) >= 0) { propertyUnit = unit || DEFAULT_ANGLE_UNIT; } return propertyUnit; }
javascript
{ "resource": "" }
q44983
parallax
train
function parallax(scrollPosition, start, duration, startValue, endValue, easing) { let min = startValue; let max = endValue; const invert = startValue > endValue; // Safety check, if "startValue" is in the wrong format if (typeof startValue !== 'number') { console.warn(`Plx, ERROR: startValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "endValue" is in the wrong format if (typeof endValue !== 'number') { console.warn(`Plx, ERROR: endValue is not a number (type: "${ typeof endValue }", value: "${ endValue }")`); // eslint-disable-line return null; } // Safety check, if "duration" is in the wrong format if (typeof duration !== 'number' || duration === 0) { console.warn(`Plx, ERROR: duration is zero or not a number (type: "${ typeof duration }", value: "${ duration }")`); // eslint-disable-line return null; } if (invert) { min = endValue; max = startValue; } let percentage = ((scrollPosition - start) / duration); if (percentage > 1) { percentage = 1; } else if (percentage < 0) { percentage = 0; } // Apply easing if (easing) { const easingPropType = typeof easing; if (easingPropType === 'object' && easing.length === 4) { percentage = BezierEasing( easing[0], easing[1], easing[2], easing[3] )(percentage); } else if (easingPropType === 'string' && EASINGS[easing]) { percentage = BezierEasing( EASINGS[easing][0], EASINGS[easing][1], EASINGS[easing][2], EASINGS[easing][3] )(percentage); } else if (easingPropType === 'function') { percentage = easing(percentage); } } let value = percentage * (max - min); if (invert) { value = max - value; } else { value += min; } return parseFloat(value.toFixed(3)); }
javascript
{ "resource": "" }
q44984
colorParallax
train
function colorParallax(scrollPosition, start, duration, startValue, endValue, easing) { let startObject = null; let endObject = null; if (startValue[0].toLowerCase() === 'r') { startObject = rgbToObject(startValue); } else { startObject = hexToObject(startValue); } if (endValue[0].toLowerCase() === 'r') { endObject = rgbToObject(endValue); } else { endObject = hexToObject(endValue); } if (startObject && endObject) { const r = parallax(scrollPosition, start, duration, startObject.r, endObject.r, easing); const g = parallax(scrollPosition, start, duration, startObject.g, endObject.g, easing); const b = parallax(scrollPosition, start, duration, startObject.b, endObject.b, easing); const a = parallax(scrollPosition, start, duration, startObject.a, endObject.a, easing); return `rgba(${ parseInt(r, 10) }, ${ parseInt(g, 10) }, ${ parseInt(b, 10) }, ${ a })`; } return null; }
javascript
{ "resource": "" }
q44985
applyProperty
train
function applyProperty(scrollPosition, propertyData, startPosition, duration, style, easing) { const { startValue, endValue, property, unit, } = propertyData; // If property is one of the color properties // Use it's parallax method const isColor = COLOR_PROPERTIES.indexOf(property) > -1; const parallaxMethod = isColor ? colorParallax : parallax; // Get new CSS value const value = parallaxMethod( scrollPosition, startPosition, duration, startValue, endValue, easing ); // Get transform function const transformMethod = TRANSFORM_MAP[property]; const filterMethod = FILTER_MAP[property]; const newStyle = style; if (transformMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Transforms, apply value to transform function newStyle.transform[property] = transformMethod(value, propertyUnit); } else if (filterMethod) { // Get CSS unit const propertyUnit = getUnit(property, unit); // Filters, apply value to filter function newStyle.filter[property] = filterMethod(value, propertyUnit); } else { // All other properties newStyle[property] = value; // Add unit if it is passed if (unit) { newStyle[property] += unit; } } return newStyle; }
javascript
{ "resource": "" }
q44986
getClasses
train
function getClasses(lastSegmentScrolledBy, isInSegment, parallaxData) { let cssClasses = null; if (lastSegmentScrolledBy === null) { cssClasses = 'Plx--above'; } else if (lastSegmentScrolledBy === parallaxData.length - 1 && !isInSegment) { cssClasses = 'Plx--below'; } else if (lastSegmentScrolledBy !== null && isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; cssClasses = `Plx--active Plx--in Plx--in-${ segmentName }`; } else if (lastSegmentScrolledBy !== null && !isInSegment) { const segmentName = parallaxData[lastSegmentScrolledBy].name || lastSegmentScrolledBy; const nextSegmentName = parallaxData[lastSegmentScrolledBy + 1].name || lastSegmentScrolledBy + 1; cssClasses = `Plx--active Plx--between Plx--between-${ segmentName }-and-${ nextSegmentName }`; } return cssClasses; }
javascript
{ "resource": "" }
q44987
omit
train
function omit(object, keysToOmit) { const result = {}; Object.keys(object).forEach(key => { if (keysToOmit.indexOf(key) === -1) { result[key] = object[key]; } }); return result; }
javascript
{ "resource": "" }
q44988
assignProperties
train
function assignProperties(dest, source) { for (var attr in source) { if (source.hasOwnProperty(attr)) { dest[attr] = source[attr]; } } }
javascript
{ "resource": "" }
q44989
resizeBuffers
train
function resizeBuffers (additionalSize) { const minimumNeededSize = index + additionalSize; if (minimumNeededSize > geomBuffer.vertices.length) { const newSize = 2 * minimumNeededSize; geomBuffer.vertices = resizeBuffer(geomBuffer.vertices, newSize); geomBuffer.normals = resizeBuffer(geomBuffer.normals, newSize); } }
javascript
{ "resource": "" }
q44990
addVertex
train
function addVertex (array, vertexIndex) { geomBuffer.vertices[index] = array[vertexIndex]; geomBuffer.normals[index++] = 0; geomBuffer.vertices[index] = array[vertexIndex + 1]; geomBuffer.normals[index++] = 0; }
javascript
{ "resource": "" }
q44991
yearWeek
train
function yearWeek (y, yd) { const dow = isoDow(y, 1, 1); const start = dow > 4 ? 9 - dow : 2 - dow; if ((Math.abs(yd - start) % 7) !== 0) { // y yd is not the start of any week return []; } if (yd < start) { // The week starts before the first week of the year => go back one year yd += Math.round((Date.UTC(y, 0, 1) - Date.UTC(y - 1, 0, 1)) / MS_PER_DAY); return yearWeek(y - 1, yd); } else if (Date.UTC(y, 0, 1) + (yd - 1 + 3) * MS_PER_DAY >= Date.UTC(y + 1, 0, 1)) { // The Wednesday (start of week + 3) lies in the next year => advance one year yd -= Math.round((Date.UTC(y + 1, 0, 1) - Date.UTC(y, 0, 1)) / MS_PER_DAY); return yearWeek(y + 1, yd); } return [y, 1 + Math.round((yd - start) / 7)]; }
javascript
{ "resource": "" }
q44992
XYZToSRGB
train
function XYZToSRGB ({ x, y, z, a }) { // Poynton, "Frequently Asked Questions About Color," page 10 // Wikipedia: http://en.wikipedia.org/wiki/SRGB // Wikipedia: http://en.wikipedia.org/wiki/CIE_1931_color_space // Convert XYZ to linear RGB const r = clamp(3.2406 * x - 1.5372 * y - 0.4986 * z, 0, 1); const g = clamp(-0.9689 * x + 1.8758 * y + 0.0415 * z, 0, 1); const b = clamp(0.0557 * x - 0.2040 * y + 1.0570 * z, 0, 1); return linearRGBToSRGB({ r, g, b, a }); }
javascript
{ "resource": "" }
q44993
checkConfig
train
function checkConfig (config) { if (config) { if (!util.isObject(config)) { throw new CartoValidationError('\'config\' property must be an object.', CartoValidationErrorTypes.INCORRECT_TYPE); } _checkServerURL(config.serverURL); } }
javascript
{ "resource": "" }
q44994
normalize
train
function normalize (x, y) { const s = Math.hypot(x, y); return [x / s, y / s]; }
javascript
{ "resource": "" }
q44995
generateSnippet
train
function generateSnippet (config) { const apiKey = config.b || 'default_public'; const username = config.c; const serverURL = config.d || 'https://{user}.carto.com'; const vizSpec = config.e || ''; const center = config.f || { lat: 0, lng: 0 }; const zoom = config.g || 10; const basemap = BASEMAPS[config.h] || 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json'; const source = config.i === sourceTypes.DATASET ? `new carto.source.Dataset("${config.a}")` : `new carto.source.SQL(\`${config.a}\`)`; return `<!DOCTYPE html> <html> <head> <title>Exported map | CARTO VL</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="UTF-8"> <script src="http://libs.cartocdn.com/carto-vl/v${carto.version}/carto-vl.js"></script> <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js"></script> <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css" rel="stylesheet" /> <style> html, body { margin: 0; } #map { position: absolute; width: 100%; height: 100%; } </style> </head> <body> <div id="map"></div> <script> const map = new mapboxgl.Map({ container: 'map', style: '${basemap}', center: [${center.lng}, ${center.lat}], zoom: ${zoom} }); carto.setDefaultConfig({ serverURL: '${serverURL}' }); carto.setDefaultAuth({ username: '${username}', apiKey: '${apiKey}' }); const source = ${source}; const viz = new carto.Viz(\` ${vizSpec} \`); const layer = new carto.Layer('layer', source, viz); layer.addTo(map, 'watername_ocean'); </script> </body> </html> `; }
javascript
{ "resource": "" }
q44996
startOfIsoWeek
train
function startOfIsoWeek (y, w) { const dow = isoDow(y, 1, 1); const startDay = dow > 4 ? 9 - dow : 2 - dow; const startDate = new Date(y, 0, startDay); return addDays(startDate, (w - 1) * 7); }
javascript
{ "resource": "" }
q44997
wRectangleTiles
train
function wRectangleTiles (z, wr) { const [wMinx, wMiny, wMaxx, wMaxy] = wr; const n = (1 << z); // for 0 <= z <= 30 equals Math.pow(2, z) const clamp = x => Math.min(Math.max(x, 0), n - 1); // compute tile coordinate ranges const tMinx = clamp(Math.floor(n * (wMinx + 1) * 0.5)); const tMaxx = clamp(Math.ceil(n * (wMaxx + 1) * 0.5) - 1); const tMiny = clamp(Math.floor(n * (1 - wMaxy) * 0.5)); const tMaxy = clamp(Math.ceil(n * (1 - wMiny) * 0.5) - 1); let tiles = []; for (let x = tMinx; x <= tMaxx; ++x) { for (let y = tMiny; y <= tMaxy; ++y) { tiles.push({ x: x, y: y, z: z }); } } return tiles; }
javascript
{ "resource": "" }
q44998
_reset
train
function _reset (viewportExpressions, renderLayer) { const metadata = renderLayer.viz.metadata; viewportExpressions.forEach(expr => expr._resetViewportAgg(metadata, renderLayer)); }
javascript
{ "resource": "" }
q44999
_runInActiveDataframes
train
function _runInActiveDataframes (viewportExpressions, renderLayer) { const dataframes = renderLayer.getActiveDataframes(); const inViewportFeaturesIDs = _runInDataframes(viewportExpressions, renderLayer, dataframes); _runImprovedForPartialFeatures(viewportExpressions, renderLayer, inViewportFeaturesIDs); }
javascript
{ "resource": "" }