_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49200
denormalizeIterable
train
function denormalizeIterable(items, entities, schema, bag) { const isMappable = typeof items.map === 'function'; const itemSchema = Array.isArray(schema) ? schema[0] : schema.schema; // Handle arrayOf iterables if (isMappable) { return items.map(o => denormalize(o, entities, itemSchema, bag)); } // Handle valuesOf iterables const denormalized = {}; Object.keys(items).forEach((key) => { denormalized[key] = denormalize(items[key], entities, itemSchema, bag); }); return denormalized; }
javascript
{ "resource": "" }
q49201
denormalizeObject
train
function denormalizeObject(obj, entities, schema, bag) { let denormalized = obj; const schemaDefinition = typeof schema.inferSchema === 'function' ? schema.inferSchema(obj) : (schema.schema || schema) ; Object.keys(schemaDefinition) // .filter(attribute => attribute.substring(0, 1) !== '_') .filter(attribute => typeof getIn(obj, [attribute]) !== 'undefined') .forEach((attribute) => { const item = getIn(obj, [attribute]); const itemSchema = getIn(schemaDefinition, [attribute]); denormalized = setIn(denormalized, [attribute], denormalize(item, entities, itemSchema, bag)); }); return denormalized; }
javascript
{ "resource": "" }
q49202
denormalizeEntity
train
function denormalizeEntity(entityOrId, entities, schema, bag) { const key = schema.key; const { entity, id } = resolveEntityOrId(entityOrId, entities, schema); if (!bag.hasOwnProperty(key)) { bag[key] = {}; } if (!bag[key].hasOwnProperty(id)) { // Ensure we don't mutate it non-immutable objects const obj = isImmutable(entity) ? entity : merge({}, entity); // Need to set this first so that if it is referenced within the call to // denormalizeObject, it will already exist. bag[key][id] = obj; bag[key][id] = denormalizeObject(obj, entities, schema, bag); } return bag[key][id]; }
javascript
{ "resource": "" }
q49203
train
function (elm, conf) { conf.sitekey = conf.key || config.key; conf.theme = conf.theme || config.theme; conf.stoken = conf.stoken || config.stoken; conf.size = conf.size || config.size; conf.type = conf.type || config.type; conf.hl = conf.lang || config.lang; conf.badge = conf.badge || config.badge; if (!conf.sitekey) { throwNoKeyException(); } return getRecaptcha().then(function (recaptcha) { var widgetId = recaptcha.render(elm, conf); instances[widgetId] = elm; return widgetId; }); }
javascript
{ "resource": "" }
q49204
train
function() { App.currentUser.signOut(); App.viewStack.clear(); App.router.redirect('/'); $('#fill_profile_invitation').hide(); }
javascript
{ "resource": "" }
q49205
train
function(nodemon) { nodemon.on('log', function(event) { console.log(event.colour); }); // opens browser on initial server start nodemon.on('config:update', function() { // Delay before server listens on port setTimeout(function() { require('open')('http://localhost:8080'); }, 1000); }); // refreshes browser when server reboots nodemon.on('restart', function() { // Delay before server listens on port setTimeout(function() { require('fs').writeFileSync('.rebooted', 'rebooted'); }, 3000); }); }
javascript
{ "resource": "" }
q49206
constuctIdListString
train
function constuctIdListString (items) { var idArr = [] forEach(items, item => { idArr.push(item.getId()) }) idArr.sort() return idArr.join(',') }
javascript
{ "resource": "" }
q49207
zoomed
train
function zoomed () { // Get the height and width height = el.clientHeight width = el.clientWidth // Set the map tile size tile.size([width, height]) // Get the current display bounds var bounds = display.llBounds() // Project the bounds based on the current projection var psw = projection(bounds[0]) var pne = projection(bounds[1]) // Based the new scale and translation vector off the current one var scale = projection.scale() * 2 * Math.PI var translate = projection.translate() var dx = pne[0] - psw[0] var dy = pne[1] - psw[1] scale = scale * (1 / Math.max(dx / width, dy / height)) projection .translate([width / 2, height / 2]) .scale(scale / 2 / Math.PI) // Reproject the bounds based on the new scale and translation vector psw = projection(bounds[0]) pne = projection(bounds[1]) var x = (psw[0] + pne[0]) / 2 var y = (psw[1] + pne[1]) / 2 translate = [width - x, height - y] // Update the Geo tiles tile .scale(scale) .translate(translate) // Get the new set of tiles and render renderTiles(tile()) }
javascript
{ "resource": "" }
q49208
matrix3d
train
function matrix3d (scale, translate) { var k = scale / 256 var r = scale % 1 ? Number : Math.round return 'matrix3d(' + [k, 0, 0, 0, 0, k, 0, 0, 0, 0, k, 0, r(translate[0] * scale), r(translate[1] * scale), 0, 1] + ')' }
javascript
{ "resource": "" }
q49209
prefixMatch
train
function prefixMatch (p) { var i = -1 var n = p.length var s = document.body.style while (++i < n) { if (p[i] + 'Transform' in s) return '-' + p[i].toLowerCase() + '-' } return '' }
javascript
{ "resource": "" }
q49210
generateInspectStyle
train
function generateInspectStyle(originalMapStyle, coloredLayers, opts) { opts = Object.assign({ backgroundColor: '#fff' }, opts); var backgroundLayer = { 'id': 'background', 'type': 'background', 'paint': { 'background-color': opts.backgroundColor } }; var sources = {}; Object.keys(originalMapStyle.sources).forEach(function (sourceId) { var source = originalMapStyle.sources[sourceId]; if (source.type === 'vector' || source.type === 'geojson') { sources[sourceId] = source; } }); return Object.assign(originalMapStyle, { layers: [backgroundLayer].concat(coloredLayers), soources: sources }); }
javascript
{ "resource": "" }
q49211
brightColor
train
function brightColor(layerId, alpha) { var luminosity = 'bright'; var hue = null; if (/water|ocean|lake|sea|river/.test(layerId)) { hue = 'blue'; } if (/state|country|place/.test(layerId)) { hue = 'pink'; } if (/road|highway|transport/.test(layerId)) { hue = 'orange'; } if (/contour|building/.test(layerId)) { hue = 'monochrome'; } if (/building/.test(layerId)) { luminosity = 'dark'; } if (/contour|landuse/.test(layerId)) { hue = 'yellow'; } if (/wood|forest|park|landcover/.test(layerId)) { hue = 'green'; } var rgb = randomColor({ luminosity: luminosity, hue: hue, seed: layerId, format: 'rgbArray' }); var rgba = rgb.concat([alpha || 1]); return 'rgba(' + rgba.join(', ') + ')'; }
javascript
{ "resource": "" }
q49212
setApi
train
function setApi() { self.api = {}; if(process && process.env && process.env.APPVEYOR_API_URL) { var fullUrl = process.env.APPVEYOR_API_URL; var urlParts = fullUrl.split("/")[2].split(":"); self.api = { host: urlParts[0], port: urlParts[1], endpoint: "/api/tests/batch" }; } else { throw Error("Not running in AppVeyor environment"); } }
javascript
{ "resource": "" }
q49213
postSpecsToAppVeyor
train
function postSpecsToAppVeyor() { log.info(inColor("Posting spec batch to AppVeyor API", "magenta")); var postData = JSON.stringify(self.unreportedSpecs); var options = { host: self.api.host, path: self.api.endpoint, port: self.api.port, method: "POST", headers: { "Content-Type": "application/json" } }; var http = require("http"); var req = http.request(options, function(res) { log.debug(inColor(" STATUS: " + res.statusCode, "yellow")); log.debug(inColor(" HEADERS: " + JSON.stringify(res.headers), "yellow")); res.setEncoding("utf8"); res.on("data", function (chunk) { log.debug(inColor(" BODY: " + chunk, "yellow")); }); res.on("end", function() { log.debug(inColor(" RESPONSE END", "yellow")); }); }); req.on("error", function(e) { log.debug(inColor("API request error: " + e.message, "red")); }); req.write(postData); req.end(); self.unreportedSpecs = []; }
javascript
{ "resource": "" }
q49214
getOutcome
train
function getOutcome(spec) { var outcome = "None"; if(isFailed(spec)) { outcome = "Failed"; } if(isDisabled(spec)) { outcome = "Ignored"; } if(isSkipped(spec)) { outcome = "Skipped"; } if(isPassed(spec)) { outcome = "Passed"; } return outcome; }
javascript
{ "resource": "" }
q49215
mapSpecToResult
train
function mapSpecToResult(spec) { var firstFailedExpectation = spec.failedExpectations[0] || {}; var result = { testName: spec.fullName, testFramework: "jasmine2", durationMilliseconds: elapsed(spec.__startTime, spec.__endTime), outcome: getOutcome(spec), ErrorMessage: firstFailedExpectation.message, ErrorStackTrace: firstFailedExpectation.stack }; return result; }
javascript
{ "resource": "" }
q49216
tclog
train
function tclog(message, attrs) { var str = "##teamcity[" + message; if (typeof(attrs) === "object") { if (!("timestamp" in attrs)) { attrs.timestamp = new Date(); } for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { if(delegates.modifySuiteName && message.indexOf("testSuite") === 0 && prop === "name") { attrs[prop] = delegates.modifySuiteName(attrs[prop]); } str += " " + prop + "='" + escapeTeamCityString(attrs[prop]) + "'"; } } } str += "]"; log(str); }
javascript
{ "resource": "" }
q49217
train
function (value, options) { // Check the parameters and reassign if needed if (typeof value === 'object') { options = value; value = true; } var selectHandler = this.remember('_selectHandler') || new SelectHandler(this); selectHandler.init(value === undefined ? true : value, options || {}); return this; }
javascript
{ "resource": "" }
q49218
handle
train
function handle(route, file) { route.status = 'starting'; route.emit('handle', file); for (let layer of route.stack) { route.emit('layer', layer, file); layer.handle(file); } route.status = 'finished'; route.emit('handle', file); return file; }
javascript
{ "resource": "" }
q49219
toRegexpSource
train
function toRegexpSource(val, keys, options) { if (Array.isArray(val)) { return arrayToRegexp(val, keys, options); } if (val instanceof RegExp) { return regexpToRegexp(val, keys, options); } return stringToRegexp(val, keys, options); }
javascript
{ "resource": "" }
q49220
stringToRegexp
train
function stringToRegexp(str, keys, options = {}) { let tokens = parse(str, options); let end = options.end !== false; let strict = options.strict; let delimiter = options.delimiter ? escapeString(options.delimiter) : '\\/'; let delimiters = options.delimiters || './'; let endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|'); let isEndDelimited = false; let route = ''; // Iterate over the tokens and create our regexp string. for (let i = 0; i < tokens.length; i++) { let token = tokens[i]; if (typeof token === 'string') { route += escapeString(token); isEndDelimited = i === tokens.length - 1 && delimiters.includes(token[token.length - 1]); continue; } let prefix = escapeString(token.prefix); let capture = token.repeat ? `(?:${token.pattern})(?:${prefix}(?:${token.pattern}))*` : token.pattern; if (keys) keys.push(token); if (token.optional) { if (token.partial) { route += prefix + `(${capture})?`; } else { route += `(?:${prefix}(${capture}))?`; } } else { route += `${prefix}(${capture})`; } } if (end) { if (!strict) route += `(?:${delimiter})?`; route += endsWith === '$' ? '$' : `(?=${endsWith})`; } else { if (!strict) route += `(?:${delimiter}(?=${endsWith}))?`; if (!isEndDelimited) route += `(?=${delimiter}|${endsWith})`; } return `^${route}`; }
javascript
{ "resource": "" }
q49221
arrayToRegexp
train
function arrayToRegexp(arr, keys, options) { let parts = []; arr.forEach(ele => parts.push(toRegexpSource(ele, keys, options))); return new RegExp(`(?:${parts.join('|')})`, flags(options)); }
javascript
{ "resource": "" }
q49222
regexpToRegexp
train
function regexpToRegexp(regex, keys, options) { if (!Array.isArray(keys)) return regex.source; let groups = regex.source.match(/\((?!\?)/g); if (!groups) return regex.source; let i = 0; let group = () => ({ name: i++, prefix: null, delimiter: null, optional: false, repeat: false, partial: false, pattern: null }); groups.forEach(() => keys.push(group())); return regex.source; }
javascript
{ "resource": "" }
q49223
getSyncMethod
train
function getSyncMethod(model, options = {}) { const forceAjaxSync = options.ajaxSync; const hasLocalStorage = getLocalStorage(model); return !forceAjaxSync && hasLocalStorage ? localSync : ajaxSync; }
javascript
{ "resource": "" }
q49224
_formatResponse
train
function _formatResponse (rawMapboxResponse) { if (!rawMapboxResponse.features.length) { return []; } return [{ boundingbox: _getBoundingBox(rawMapboxResponse.features[0]), center: _getCenter(rawMapboxResponse.features[0]), type: _getType(rawMapboxResponse.features[0]) }]; }
javascript
{ "resource": "" }
q49225
Layer
train
function Layer (source, style, options = {}) { Base.apply(this, arguments); _checkSource(source); _checkStyle(style); this._client = undefined; this._engine = undefined; this._internalModel = undefined; this._source = source; this._style = style; this._visible = _.isBoolean(options.visible) ? options.visible : true; this._featureClickColumns = options.featureClickColumns || []; this._featureOverColumns = options.featureOverColumns || []; this._minzoom = options.minzoom || 0; this._maxzoom = options.maxzoom || undefined; this._aggregation = options.aggregation || {}; _validateAggregationColumnsAndInteractivity(this._aggregation.columns, this._featureClickColumns, this._featureOverColumns); }
javascript
{ "resource": "" }
q49226
_getInteractivityFields
train
function _getInteractivityFields (columns) { var fields = columns.map(function (column, index) { return { name: column, title: true, position: index }; }); return { fields: fields }; }
javascript
{ "resource": "" }
q49227
_validateAggregationColumnsAndInteractivity
train
function _validateAggregationColumnsAndInteractivity (aggregationColumns, clickColumns, overColumns) { var aggColumns = (aggregationColumns && Object.keys(aggregationColumns)) || []; _validateColumnsConcordance(aggColumns, clickColumns, 'featureClick'); _validateColumnsConcordance(aggColumns, overColumns, 'featureOver'); }
javascript
{ "resource": "" }
q49228
parseCategoryData
train
function parseCategoryData (data, count, max, min, nulls, operation) { if (!data) { return null; } /** * @typedef {object} carto.dataview.CategoryData * @property {number} count - The total number of categories * @property {number} max - Maximum category value * @property {number} min - Minimum category value * @property {number} nulls - Number of null categories * @property {string} operation - Operation used * @property {carto.dataview.CategoryItem[]} categories * @api */ return { count: count, max: max, min: min, nulls: nulls, operation: operation, categories: _createCategories(data) }; }
javascript
{ "resource": "" }
q49229
Client
train
function Client (settings) { settings.serverUrl = (settings.serverUrl || DEFAULT_SERVER_URL).replace(/{username}/, settings.username || ''); _checkSettings(settings); this._layers = new Layers(); this._dataviews = []; this._engine = new Engine({ apiKey: settings.apiKey, username: settings.username, serverUrl: settings.serverUrl, client: 'js-' + VERSION }); this._bindEngine(this._engine); }
javascript
{ "resource": "" }
q49230
train
function (deps) { if (!deps.mapModel) throw new Error('mapModel is required'); if (!deps.tooltipModel) throw new Error('tooltipModel is required'); if (!deps.infowindowModel) throw new Error('infowindowModel is required'); this._mapModel = deps.mapModel; this._tooltipModel = deps.tooltipModel; this._infowindowModel = deps.infowindowModel; this._layersBeingFeaturedOvered = {}; }
javascript
{ "resource": "" }
q49231
Categories
train
function Categories (rule) { var categoryBuckets = rule.getBucketsWithCategoryFilter(); var defaultBuckets = rule.getBucketsWithDefaultFilter(); /** * @typedef {object} carto.layer.metadata.Category * @property {number|string} name - The name of the category * @property {string} value - The value of the category * @api */ this._categories = categoryBuckets.map(function (bucket) { return { name: bucket.filter.name, value: bucket.value }; }); this._defaultValue = defaultBuckets.length > 0 ? defaultBuckets[0].value : undefined; Base.call(this, 'categories', rule); }
javascript
{ "resource": "" }
q49232
Response
train
function Response (windshaftSettings, serverResponse) { this._windshaftSettings = windshaftSettings; this._layerGroupId = serverResponse.layergroupid; this._layers = serverResponse.metadata.layers; this._dataviews = serverResponse.metadata.dataviews; this._analyses = serverResponse.metadata.analyses; this._cdnUrl = serverResponse.cdn_url; }
javascript
{ "resource": "" }
q49233
_formatResponse
train
function _formatResponse (rawTomTomResponse) { if (!rawTomTomResponse.results.length) { return []; } const bestCandidate = rawTomTomResponse.results[0]; return [{ boundingbox: _getBoundingBox(bestCandidate), center: _getCenter(bestCandidate), type: _getType(bestCandidate) }]; }
javascript
{ "resource": "" }
q49234
_getType
train
function _getType (result) { let type = result.type; if (TYPES[type]) { if (type === 'Geography' && result.entityType) { type = type + ':' + result.entityType; } return TYPES[type]; } return 'default'; }
javascript
{ "resource": "" }
q49235
Base
train
function Base (source, layer, options) { options = options || {}; this._id = options.id || Base.$generateId(); }
javascript
{ "resource": "" }
q49236
parseHistogramData
train
function parseHistogramData (data, nulls, totalAmount) { if (!data) { return null; } var compactData = _.compact(data); var maxBin = _.max(compactData, function (bin) { return bin.freq || 0; }); var maxFreq = _.isFinite(maxBin.freq) && maxBin.freq !== 0 ? maxBin.freq : null; /** * @description * Object containing histogram data. * * @typedef {object} carto.dataview.HistogramData * @property {number} nulls - The number of items with null value * @property {number} totalAmount - The number of elements returned * @property {carto.dataview.BinItem[]} bins - Array containing the {@link carto.dataview.BinItem|data bins} for the histogram * @property {string} type - String with value: **histogram** * @api */ return { bins: _createBins(compactData, maxFreq), nulls: nulls || 0, totalAmount: totalAmount }; }
javascript
{ "resource": "" }
q49237
Base
train
function Base (type, rule) { this._type = type || ''; this._column = rule.getColumn(); this._mapping = rule.getMapping(); this._property = rule.getProperty(); }
javascript
{ "resource": "" }
q49238
serialize
train
function serialize (layersCollection, dataviewsCollection) { var analysisList = AnalysisService.getAnalysisList(layersCollection, dataviewsCollection); return _generateUniqueAnalysisList(analysisList); }
javascript
{ "resource": "" }
q49239
_generateUniqueAnalysisList
train
function _generateUniqueAnalysisList (analysisList) { var analysisIds = {}; return _.reduce(analysisList, function (list, analysis) { if (!analysisIds[analysis.get('id')] && !_isAnalysisPartOfOtherAnalyses(analysis, analysisList)) { analysisIds[analysis.get('id')] = true; // keep a set of already added analysis. list.push(analysis.toJSON()); } return list; }, []); }
javascript
{ "resource": "" }
q49240
_isAnalysisPartOfOtherAnalyses
train
function _isAnalysisPartOfOtherAnalyses (analysis, analysisList) { return _.any(analysisList, function (otherAnalysisModel) { if (!analysis.equals(otherAnalysisModel)) { return otherAnalysisModel.findAnalysisById(analysis.get('id')); } return false; }); }
javascript
{ "resource": "" }
q49241
train
function (defer) { if (this.t0 !== null) { Profiler.new_value(this.name, this._elapsed(), 't', defer); this.t0 = null; } }
javascript
{ "resource": "" }
q49242
train
function () { ++this.count; if (this.t0 === null) { this.start(); return; } var elapsed = this._elapsed(); if (elapsed > 1) { Profiler.new_value(this.name, this.count); this.count = 0; this.start(); } }
javascript
{ "resource": "" }
q49243
train
function (coord, zoom, ownerDocument) { var key = zoom + '/' + coord.x + '/' + coord.y; if (!this.cache[key]) { var img = this.cache[key] = new Image(256, 256); this.cache[key].src = this._getTileUrl(coord, zoom); this.cache[key].setAttribute('gTileKey', key); this.cache[key].onerror = function () { img.style.display = 'none'; }; } return this.cache[key]; }
javascript
{ "resource": "" }
q49244
SQL
train
function SQL (query) { _checkQuery(query); this._query = query; Base.apply(this, arguments); this._appliedFilters.on('change:filters', () => this._updateInternalModelQuery(this._getQueryToApply())); }
javascript
{ "resource": "" }
q49245
train
function (settings) { validatePresenceOfOptions(settings, ['urlTemplate', 'userName']); if (settings.templateName) { this.endpoints = { get: [WindshaftConfig.MAPS_API_BASE_URL, 'named', settings.templateName, 'jsonp'].join('/'), post: [WindshaftConfig.MAPS_API_BASE_URL, 'named', settings.templateName].join('/') }; } else { this.endpoints = { get: WindshaftConfig.MAPS_API_BASE_URL, post: WindshaftConfig.MAPS_API_BASE_URL }; } this.url = settings.urlTemplate.replace('{user}', settings.userName); this._requestTracker = new RequestTracker(MAP_INSTANTIATION_LIMIT); }
javascript
{ "resource": "" }
q49246
Buckets
train
function Buckets (rule) { var rangeBuckets = rule.getBucketsWithRangeFilter(); /** * @typedef {object} carto.layer.metadata.Bucket * @property {number} min - The minimum range value * @property {number} max - The maximum range value * @property {number|string} value - The value of the bucket * @api */ this._buckets = rangeBuckets.map(function (bucket) { return { min: bucket.filter.start, max: bucket.filter.end, value: bucket.value }; }); this._avg = rule.getFilterAvg(); this._min = rangeBuckets.length > 0 ? rangeBuckets[0].filter.start : undefined; this._max = rangeBuckets.length > 0 ? rangeBuckets[rangeBuckets.length - 1].filter.end : undefined; Base.call(this, 'buckets', rule); }
javascript
{ "resource": "" }
q49247
parseFormulaData
train
function parseFormulaData (nulls, operation, result) { /** * @description * Object containing formula data * * @typedef {object} carto.dataview.FormulaData * @property {number} nulls - Number of null values in the column * @property {string} operation - Operation used * @property {number} result - Result of the operation * @api */ return { nulls: nulls, operation: operation, result: result }; }
javascript
{ "resource": "" }
q49248
GoogleMapsMapType
train
function GoogleMapsMapType (layers, engine, map) { this._layers = layers; this._engine = engine; this._map = map; this._hoveredLayers = []; this.tileSize = new google.maps.Size(256, 256); this._internalView = new GMapsCartoDBLayerGroupView(this._engine._cartoLayerGroup, { nativeMap: map }); this._id = this._internalView._id; this._internalView.on('featureClick', this._onFeatureClick, this); this._internalView.on('featureOver', this._onFeatureOver, this); this._internalView.on('featureOut', this._onFeatureOut, this); this._internalView.on('featureError', this._onFeatureError, this); }
javascript
{ "resource": "" }
q49249
_checkAndTransformColumns
train
function _checkAndTransformColumns (columns) { var returnValue = null; if (columns) { _checkColumns(columns); returnValue = {}; Object.keys(columns).forEach(function (key) { returnValue[key] = _columnToSnakeCase(columns[key]); }); } return returnValue; }
javascript
{ "resource": "" }
q49250
_getListedError
train
function _getListedError (cartoError, errorList) { var errorListkeys = _.keys(errorList); var key; for (var i = 0; i < errorListkeys.length; i++) { key = errorListkeys[i]; if (!(errorList[key].messageRegex instanceof RegExp)) { throw new Error('MessageRegex on ' + key + ' is not a RegExp.'); } if (errorList[key].messageRegex.test(cartoError.message)) { return { friendlyMessage: _replaceRegex(cartoError, errorList[key]), errorCode: _buildErrorCode(cartoError, key) }; } } // When cartoError not found return generic values return { friendlyMessage: cartoError.message || '', errorCode: _buildErrorCode(cartoError, 'unknown-error') }; }
javascript
{ "resource": "" }
q49251
_buildErrorCode
train
function _buildErrorCode (cartoError, key) { var fragments = []; fragments.push(cartoError && cartoError.origin); fragments.push(cartoError && cartoError.type); fragments.push(key); fragments = _.compact(fragments); return fragments.join(':'); }
javascript
{ "resource": "" }
q49252
train
function (deps) { if (!deps.mapView) throw new Error('mapView is required'); if (!deps.mapModel) throw new Error('mapModel is required'); this._mapView = deps.mapView; this._mapModel = deps.mapModel; // Map to keep track of clickable layers that are being feature overed this._clickableLayersBeingFeatureOvered = {}; }
javascript
{ "resource": "" }
q49253
BoundingBoxGoogleMaps
train
function BoundingBoxGoogleMaps (map) { if (!_isGoogleMap(map)) { throw new Error('Bounding box requires a Google Maps map but got: ' + map); } // Adapt the Google Maps map to offer unique: // - getBounds() function // - 'boundsChanged' event var mapAdapter = new GoogleMapsBoundingBoxAdapter(map); // Use the adapter for the internal BoundingBoxFilter model this._internalModel = new BoundingBoxFilterModel(mapAdapter); this.listenTo(this._internalModel, 'boundsChanged', this._onBoundsChanged); }
javascript
{ "resource": "" }
q49254
parse
train
function parse(uriStr) { var m = ('' + uriStr).match(URI_RE_); if (!m) { return null; } return new URI( nullIfAbsent(m[1]), nullIfAbsent(m[2]), nullIfAbsent(m[3]), nullIfAbsent(m[4]), nullIfAbsent(m[5]), nullIfAbsent(m[6]), nullIfAbsent(m[7])); }
javascript
{ "resource": "" }
q49255
create
train
function create(scheme, credentials, domain, port, path, query, fragment) { var uri = new URI( encodeIfExists2(scheme, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_), encodeIfExists2( credentials, URI_DISALLOWED_IN_SCHEME_OR_CREDENTIALS_), encodeIfExists(domain), port > 0 ? port.toString() : null, encodeIfExists2(path, URI_DISALLOWED_IN_PATH_), null, encodeIfExists(fragment)); if (query) { if ('string' === typeof query) { uri.setRawQuery(query.replace(/[^?&=0-9A-Za-z_\-~.%]/g, encodeOne)); } else { uri.setAllParameters(query); } } return uri; }
javascript
{ "resource": "" }
q49256
encodeIfExists2
train
function encodeIfExists2(unescapedPart, extra) { if ('string' == typeof unescapedPart) { return encodeURI(unescapedPart).replace(extra, encodeOne); } return null; }
javascript
{ "resource": "" }
q49257
resolve
train
function resolve(baseUri, relativeUri) { // there are several kinds of relative urls: // 1. //foo - replaces everything from the domain on. foo is a domain name // 2. foo - replaces the last part of the path, the whole query and fragment // 3. /foo - replaces the the path, the query and fragment // 4. ?foo - replace the query and fragment // 5. #foo - replace the fragment only var absoluteUri = baseUri.clone(); // we satisfy these conditions by looking for the first part of relativeUri // that is not blank and applying defaults to the rest var overridden = relativeUri.hasScheme(); if (overridden) { absoluteUri.setRawScheme(relativeUri.getRawScheme()); } else { overridden = relativeUri.hasCredentials(); } if (overridden) { absoluteUri.setRawCredentials(relativeUri.getRawCredentials()); } else { overridden = relativeUri.hasDomain(); } if (overridden) { absoluteUri.setRawDomain(relativeUri.getRawDomain()); } else { overridden = relativeUri.hasPort(); } var rawPath = relativeUri.getRawPath(); var simplifiedPath = collapse_dots(rawPath); if (overridden) { absoluteUri.setPort(relativeUri.getPort()); simplifiedPath = simplifiedPath && simplifiedPath.replace(EXTRA_PARENT_PATHS_RE, ''); } else { overridden = !!rawPath; if (overridden) { // resolve path properly if (simplifiedPath.charCodeAt(0) !== 0x2f /* / */) { // path is relative var absRawPath = collapse_dots(absoluteUri.getRawPath() || '') .replace(EXTRA_PARENT_PATHS_RE, ''); var slash = absRawPath.lastIndexOf('/') + 1; simplifiedPath = collapse_dots( (slash ? absRawPath.substring(0, slash) : '') + collapse_dots(rawPath)) .replace(EXTRA_PARENT_PATHS_RE, ''); } } else { simplifiedPath = simplifiedPath && simplifiedPath.replace(EXTRA_PARENT_PATHS_RE, ''); if (simplifiedPath !== rawPath) { absoluteUri.setRawPath(simplifiedPath); } } } if (overridden) { absoluteUri.setRawPath(simplifiedPath); } else { overridden = relativeUri.hasQuery(); } if (overridden) { absoluteUri.setRawQuery(relativeUri.getRawQuery()); } else { overridden = relativeUri.hasFragment(); } if (overridden) { absoluteUri.setRawFragment(relativeUri.getRawFragment()); } return absoluteUri; }
javascript
{ "resource": "" }
q49258
URI
train
function URI( rawScheme, rawCredentials, rawDomain, port, rawPath, rawQuery, rawFragment) { this.scheme_ = rawScheme; this.credentials_ = rawCredentials; this.domain_ = rawDomain; this.port_ = port; this.path_ = rawPath; this.query_ = rawQuery; this.fragment_ = rawFragment; /** * @type {Array|null} */ this.paramCache_ = null; }
javascript
{ "resource": "" }
q49259
lookupEntity
train
function lookupEntity(name) { // TODO: entity lookup as specified by HTML5 actually depends on the // presence of the ";". if (ENTITIES.hasOwnProperty(name)) { return ENTITIES[name]; } var m = name.match(decimalEscapeRe); if (m) { return String.fromCharCode(parseInt(m[1], 10)); } else if (!!(m = name.match(hexEscapeRe))) { return String.fromCharCode(parseInt(m[1], 16)); } else if (entityLookupElement && safeEntityNameRe.test(name)) { entityLookupElement.innerHTML = '&' + name + ';'; var text = entityLookupElement.textContent; ENTITIES[name] = text; return text; } else { return '&' + name + ';'; } }
javascript
{ "resource": "" }
q49260
makeSaxParser
train
function makeSaxParser(handler) { // Accept quoted or unquoted keys (Closure compat) var hcopy = { cdata: handler.cdata || handler['cdata'], comment: handler.comment || handler['comment'], endDoc: handler.endDoc || handler['endDoc'], endTag: handler.endTag || handler['endTag'], pcdata: handler.pcdata || handler['pcdata'], rcdata: handler.rcdata || handler['rcdata'], startDoc: handler.startDoc || handler['startDoc'], startTag: handler.startTag || handler['startTag'] }; return function(htmlText, param) { return parse(htmlText, hcopy, param); }; }
javascript
{ "resource": "" }
q49261
parseTimeSeriesData
train
function parseTimeSeriesData (data, nulls, totalAmount, offset) { if (!data) { return null; } var compactData = _.compact(data); var maxBin = _.max(compactData, function (bin) { return bin.freq || 0; }); var maxFreq = _.isFinite(maxBin.freq) && maxBin.freq !== 0 ? maxBin.freq : null; /** * @description * Object containing time series data. * * @typedef {object} carto.dataview.TimeSeriesData * @property {number} nulls - The number of items with null value * @property {number} totalAmount - The number of elements returned * @property {number} offset - The time offset in hours. Needed to format UTC timestamps into the proper timezone format * @property {carto.dataview.TimeSeriesBinItem[]} bins - Array containing the {@link carto.dataview.TimeSeriesBinItem|data bins} for the time series * @api */ return { bins: _createBins(compactData, maxFreq), nulls: nulls || 0, offset: secondsToHours(offset), totalAmount: totalAmount }; }
javascript
{ "resource": "" }
q49262
Dataset
train
function Dataset (tableName) { _checkTableName(tableName); this._tableName = tableName; Base.apply(this, arguments); this._appliedFilters.on('change:filters', () => this._updateInternalModelQuery(this._getQueryToApply())); }
javascript
{ "resource": "" }
q49263
Histogram
train
function Histogram (source, column, options) { this._initialize(source, column, options); this._bins = this._options.bins; this._start = this._options.start; this._end = this._options.end; }
javascript
{ "resource": "" }
q49264
train
function (deps, options) { deps = deps || {}; options = options || {}; if (!deps.engine) throw new Error('engine is required'); if (!deps.mapModel) throw new Error('mapModel is required'); if (!deps.infowindowModel) throw new Error('infowindowModel is required'); if (!deps.tooltipModel) throw new Error('tooltipModel is required'); this._engine = deps.engine; this._mapModel = deps.mapModel; this._infowindowModel = deps.infowindowModel; this._tooltipModel = deps.tooltipModel; this._showEmptyFields = !!options.showEmptyFields; this._cartoDBLayerGroupView = null; this._cartoDBLayerModel = null; this.currentFeatureUniqueId = null; this._mapModel.on('change:popupsEnabled', this._onPopupsEnabledChanged, this); }
javascript
{ "resource": "" }
q49265
BoundingBoxLeaflet
train
function BoundingBoxLeaflet (map) { if (!_isLeafletMap(map)) { throw new Error('Bounding box requires a Leaflet map but got: ' + map); } // Adapt the Leaflet map to offer unique: // - getBounds() function // - 'boundsChanged' event var mapAdapter = new LeafletBoundingBoxAdapter(map); // Use the adapter for the internal BoundingBoxFilter model this._internalModel = new BoundingBoxFilterModel(mapAdapter); this.listenTo(this._internalModel, 'boundsChanged', this._onBoundsChanged); }
javascript
{ "resource": "" }
q49266
getMetadataFromRules
train
function getMetadataFromRules (rulesData) { var metadata = []; rulesData.forEach(function (ruleData) { var rule = new Rule(ruleData); if (_isBucketsMetadata(rule)) { metadata.push(new BucketsMetadata(rule)); } else if (_isCategoriesMetadata(rule)) { metadata.push(new CategoriesMetadata(rule)); } }); return metadata; }
javascript
{ "resource": "" }
q49267
pongHistogram_UpdateBars
train
function pongHistogram_UpdateBars( divId, dta, xMin, xMax ) { log( "pongHistogram", "UpdateBars "+divId); var pmd = moduleConfig[ divId ]; var cnt = ( pmd.blockCount ? pmd.blockCount : 10 ); // get y-axis scaling var yMax = pmd.yAxisMax; if ( !yMax || yMax == 'auto' ) { yMax = 0; for ( var i = 0; i < cnt; i++ ) { if ( parseFloat( dta[i][ pmd.dataY ] ) > yMax ) { yMax = parseFloat( dta[i][ pmd.dataY ] ); } } } var yH = $( '.HistogramBlockContainer' ).height(); log( "pongHistogram", 'yH='+yH); // scale bars in % height for ( var i = 0; i < cnt; i++ ) { //var bar = pongHistogram[ divId ][i]; var h = parseFloat( dta[i][ pmd.dataY ] ) / parseFloat( yMax ) * yH; h = ( h > 100 ? 100 : h ); log( "pongHistogram", ' bar '+i+' '+ JSON.stringify( dta[i]) + ' '+ pmd.dataY+' '+ pmd.xAxisMax + ' h='+h ); $( '#'+divId+'bar'+i ).height( h+'px' ); // set height of bar $( '#'+divId+'bar'+i ).attr( 'title', dta[i][ pmd.dataY ]+'#' ); if ( dta[i][ pmd.dataX ] ) { // update label $( '#'+divId+'xLabel'+i ).html( dta[i][ pmd.dataX ] ); } } log( "pongHistogram", 'UpdateBars end' ); return true; }
javascript
{ "resource": "" }
q49268
loadIncludes
train
function loadIncludes() { for ( var module in reqModules ) { if ( module && module != 'pong-tableXX' ) { // just to exclude modules, for debugging it's better to include them hardcoded in index.html // extra CSS files if ( moduleMap[ module ] ) { if ( moduleMap[ module ].css ) { for ( var i = 0; i < moduleMap[ module ].css.length; i++ ) { log( 'loadModules', module+' add extra CSS: '+modulesPath+module+'/'+moduleMap[ module ].css[i] ); jQuery('head').append('<link rel="stylesheet" rel="nofollow" href="'+modulesPath+module+'/'+moduleMap[ module ].css[i] +'" type="text/css" />'); } } // include files if ( moduleMap[ module ].include ) { for ( var i = 0; i < moduleMap[ module ].include.length; i++ ) { //for ( var includeJS in moduleMap[ module ].include ) { var includeJS = moduleMap[ module ].include[i]; log( 'loadModules', module+' load include: '+modulesPath+module+'/'+includeJS ); ajaxOngoing++; $.getScript( modulesPath+module+'/'+includeJS ) .done( function( script, textStatus, jqxhr ) { log( 'loadModules', this.url+' '+textStatus ); ajaxOngoing--; } ) .fail( function( jqxhr, settings, exception ) { log( 'loadModules', this.url+' '+exception ); ajaxOngoing--; } ); } } } } } ajaxOngoing--; }
javascript
{ "resource": "" }
q49269
getUrlGETparams
train
function getUrlGETparams() { var vars = {}, hash; var hashes = window.location.href.slice( window.location.href.indexOf('?') + 1 ).split('&'); for( var i = 0; i < hashes.length; i++ ) { hash = hashes[i].split('='); vars[ hash[0] ] = hash[1]; // switch on console logging if ( hash[0] == 'info') { logInfo = true } if ( hash[0] == 'info' && hash[1] && hash[1] != '') { logInfoStr = hash[1] } } //alert( JSON.stringify( vars ) ); return vars; }
javascript
{ "resource": "" }
q49270
publishEvent
train
function publishEvent( channelName, eventObj ) { var broker = getEventBroker( 'main' ) eventObj.channel = channelName broker.publish( eventObj ); }
javascript
{ "resource": "" }
q49271
feedbackEvtCallback
train
function feedbackEvtCallback( evt ) { log( "pong-feedback", "feedbackEvtCallback" ) if ( evt && evt.text ) { log( "pong-feedback", "feedbackEvtCallback "+evt.text ) if ( pongLastFeedbackTxt.indexOf( evt.text ) >= 0 ) { if ( evt.text.length > 0 ) { var feedbackTxt = $.i18n( evt.text ) var evtNo = pongLastFeedbackTxt.indexOf( feedbackTxt ) pongLastFeedbackCnt[evtNo] = pongLastFeedbackCnt[evtNo] + 1 pongLastFeedbackTim[evtNo] = new Date() moveToLastFeetback( evtNo ) } } else { if ( evt.text.length > 0 ) { var feedbackTxt = $.i18n( evt.text ) pongLastFeedbackTxt.shift() pongLastFeedbackTxt.push( feedbackTxt ) pongLastFeedbackCnt.shift() pongLastFeedbackCnt.push( 1 ) pongLastFeedbackTim.shift() pongLastFeedbackTim.push( new Date() ) } } } updateFeedback() }
javascript
{ "resource": "" }
q49272
train
function ( count, forms ) { var pluralRules, pluralFormIndex, index, explicitPluralPattern = new RegExp('\\d+=', 'i'), formCount, form; if ( !forms || forms.length === 0 ) { return ''; } // Handle for Explicit 0= & 1= values for ( index = 0; index < forms.length; index++ ) { form = forms[index]; if ( explicitPluralPattern.test( form ) ) { formCount = parseInt( form.substring( 0, form.indexOf( '=' ) ), 10 ); if ( formCount === count ) { return ( form.substr( form.indexOf( '=' ) + 1 ) ); } forms[index] = undefined; } } forms = $.map( forms, function ( form ) { if ( form !== undefined ) { return form; } } ); pluralRules = this.pluralRules[$.i18n().locale]; if ( !pluralRules ) { // default fallback. return ( count === 1 ) ? forms[0] : forms[1]; } pluralFormIndex = this.getPluralForm( count, pluralRules ); pluralFormIndex = Math.min( pluralFormIndex, forms.length - 1 ); return forms[pluralFormIndex]; }
javascript
{ "resource": "" }
q49273
train
function ( number, pluralRules ) { var i, pluralForms = [ 'zero', 'one', 'two', 'few', 'many', 'other' ], pluralFormIndex = 0; for ( i = 0; i < pluralForms.length; i++ ) { if ( pluralRules[pluralForms[i]] ) { if ( pluralRuleParser( pluralRules[pluralForms[i]], number ) ) { return pluralFormIndex; } pluralFormIndex++; } } return pluralFormIndex; }
javascript
{ "resource": "" }
q49274
train
function ( num, integer ) { var tmp, item, i, transformTable, numberString, convertedNumber; // Set the target Transform table: transformTable = this.digitTransformTable( $.i18n().locale ); numberString = '' + num; convertedNumber = ''; if ( !transformTable ) { return num; } // Check if the restore to Latin number flag is set: if ( integer ) { if ( parseFloat( num, 10 ) === num ) { return num; } tmp = []; for ( item in transformTable ) { tmp[transformTable[item]] = item; } transformTable = tmp; } for ( i = 0; i < numberString.length; i++ ) { if ( transformTable[numberString[i]] ) { convertedNumber += transformTable[numberString[i]]; } else { convertedNumber += numberString[i]; } } return integer ? parseFloat( convertedNumber, 10 ) : convertedNumber; }
javascript
{ "resource": "" }
q49275
initializeTheSearch
train
function initializeTheSearch( divId, type , params ) { if ( params && params.get && params.get.search ) { //alert( JSON.stringify( moduleConfig[ divId ] ) ) var cfg = moduleConfig[ divId ]; if ( cfg.update ) { for ( var i= 0; i < cfg.update.length; i++ ) { var p = {} p[ cfg.update[i].param ] = params.get.search //alert( cfg.update[i].id + ' ' +JSON.stringify(p) ) udateModuleData( cfg.update[i].id+'Content', p ) } } } }
javascript
{ "resource": "" }
q49276
addSearchHeaderRenderHtml
train
function addSearchHeaderRenderHtml( divId, type , params, config ) { log( "PoNG-Search", "add content " ); if ( ! config.page ) return; var html = []; var lang = ''; html.push( '<div class="pongSearch" id="'+divId+'">' ); html.push( '<form id="'+divId+'Form">' ); html.push( '<input type="hidden" name="layout" value="'+ config.page + '"/>' ); if ( getParam( 'lang' ) != '' ) { html.push( '<input type="hidden" name="lang" value="'+ getParam( 'lang' ) + '"/>' ); } var role = ''; if ( userRole != '' ) { html.push( '<input type="hidden" name="role" value="'+ getParam( 'role' ) + '"/>' ); } var title = ( config.title ? config.title : '' ); var name = ( config.name ? config.name : 'search' ); if ( config.label ) { html.push( '<label class="pongSearchLabel" for="'+divId+'Input">'+$.i18n( config.label )+'</label>' ) } html.push( '<input id="'+divId+'Input" class="pongSearchInput" title="'+title+'" name="'+name+'" accessKey="s"></input>' ) html.push( '</form>' ) html.push( '<script>' ) //html.push( ' $( function(){ alert("yepp") } );' ) html.push( ' $( "#'+divId+'Form" ).submit( function(event){ } );' ) html.push( '</script>' ) html.push( '</div>' ) $( "#"+divId ).html( html.join( "\n" ) ); }
javascript
{ "resource": "" }
q49277
pongSrcCodeDivRenderHTML
train
function pongSrcCodeDivRenderHTML( divId, resourceURL, params, cfg ) { log( "Pong-SrcCode", "load source code" ); if ( ! cfg.type ) { cfg.type = "plain"; } $.get( resourceURL, params ) .done( function ( srcData ) { jQuerySyntaxInsertCode( divId, srcData, cfg.type, cfg.options||{} ); } ).fail( function() { alert( "Failed to load source code." ) } ); }
javascript
{ "resource": "" }
q49278
pongListDivHTML
train
function pongListDivHTML( divId, resourceURL, params ) { log( "PoNG-List", "divId="+divId+" resourceURL="+resourceURL ); pongTableInit( divId, "PongList" ); if ( moduleConfig[ divId ] != null ) { renderPongListDivHTML( divId, resourceURL, params, moduleConfig[ divId ] ); } else { $.getJSON( resourceURL+"/pong-list", function( tbl ) { renderPongListDivHTML( divId, resourceURL, params, tbl ); } ); } }
javascript
{ "resource": "" }
q49279
train
function( locale, messages ) { if ( !this.messages[locale] ) { this.messages[locale] = messages; } else { this.messages[locale] = $.extend( this.messages[locale], messages ); } }
javascript
{ "resource": "" }
q49280
pongOnTheFlyAddActionBtn
train
function pongOnTheFlyAddActionBtn(id, modalName, resourceURL, params) { log( "PoNG-OnTheFly", "modalFormAddActionBtn " + id ); if ( !modalName ) { modalName = "OnTheFly"; } var buttonLbl = modalName; if ( params && params.showConfig ) { buttonLbl = 'Show the configruation of this view...'; } var html = ""; log( "PoNG-OnTheFly", "Std Config Dlg: " + modalName ); var icon = "ui-icon-pencil"; var paramsStr = 'null'; if ( params ) { paramsStr = JSON.stringify( params ) } var jscall = 'pongOnTheFlyOpenDlg( "' + id + '", "' + modalName + '", "' + resourceURL + '",' + paramsStr + ' );' var width = "600"; if ( params && params.width ) { width = params.width; } var height = "600"; if ( params && params.height ) { height = params.height; } html += '<div id="' + id + modalName + 'Dialog">' + resourceURL + " " + modalName + "</div>"; log( "PoNG-OnTheFly", " cfg: height: " + height + ", width: " + width ); html += '<script>' + '$(function() { ' + ' $( "#' + id + modalName + 'Dialog" ).dialog( ' + ' { autoOpen: false, modal: true, height: '+height+', width: '+width+',' + ' buttons: { "' + $.i18n( 'Save Configuration' ) + '": ' + ' function() { ' + ' pongOnTheFlySave( "'+id+'", "'+modalName+'", "'+resourceURL+'" );' + ' $( this ).dialog( "close" ); ' + ' } } ' + ' } ); ' + '} );</script>'; html += '<button id="' + id + modalName + 'Bt">' + $.i18n( buttonLbl ) + '</button>'; html += '<script> ' + ' $(function() { ' + ' $( "#' + id + modalName + 'Bt" ).button( ' +' { icons:{primary: "' + icon + '"}, text: false } ' +' ).click( function() { ' + jscall + ' } ); } ); ' +'</script>'; return html; }
javascript
{ "resource": "" }
q49281
pongOnTheFlyCreModalFromMeta
train
function pongOnTheFlyCreModalFromMeta(id, modalName, resourceURL) { log( "PoNG-OnTheFly", "Create modal view content " + resourceURL ); if ( !modalName ) { modalName = "OnTheFly"; } if ( resourceURL ) { log( "PoNG-OnTheFly", "Get JSON for " + id ); // var jsonCfg = pongOnTheFlyFindSubJSON( layoutOrig, "", sessionInfo[ // id+"OnTheFly" ].resID ); var editName = id + modalName + 'DialogConfig'; var tmplName = id + modalName + 'DialogAssist'; log( "PoNG-OnTheFly", "Add JSON to #" + id + modalName + "Dialog" ); $( '#' + id + modalName + 'Dialog' ).html( '<form>' +'<label for="' +editName+ '">View Configuration Editor:</label>' +'<textarea id="' +editName+ '" class="OnTheFly-ConfField"/>' +'<label for="' +tmplName + '">Config Copy-Paste Template</label>' +'<textarea id="' +tmplName+ '" class="OnTheFly-AssistField"/>' +'</form>' ); $( '#' + id + modalName + 'DialogConfig' ).val( $.i18n( 'Could not load configuration from' ) + ' "' + resourceURL + '"' ); $( '#' + id + modalName + 'DialogAssist' ).val( $.i18n( 'No help available.' ) ); } else { log( "PoNG-OnTheFly", "WARNING: Configuration issue!" ); } log( "PoNG-OnTheFly", "Done." ); }
javascript
{ "resource": "" }
q49282
train
function () { var i18n = this; // Set locale of String environment String.locale = i18n.locale; // Override String.localeString method String.prototype.toLocaleString = function () { var localeParts, localePartIndex, value, locale, fallbackIndex, tryingLocale, message; value = this.valueOf(); locale = i18n.locale; fallbackIndex = 0; while ( locale ) { // Iterate through locales starting at most-specific until // localization is found. As in fi-Latn-FI, fi-Latn and fi. localeParts = locale.split( '-' ); localePartIndex = localeParts.length; do { tryingLocale = localeParts.slice( 0, localePartIndex ).join( '-' ); message = i18n.messageStore.get( tryingLocale, value ); if ( message ) { return message; } localePartIndex--; } while ( localePartIndex ); if ( locale === 'en' ) { break; } locale = ( $.i18n.fallbacks[i18n.locale] && $.i18n.fallbacks[i18n.locale][fallbackIndex] ) || i18n.options.fallbackLocale; $.i18n.log( 'Trying fallback locale for ' + i18n.locale + ': ' + locale ); fallbackIndex++; } // key not found return ''; }; }
javascript
{ "resource": "" }
q49283
train
function ( key, parameters ) { var message = key.toLocaleString(); // FIXME: This changes the state of the I18N object, // should probably not change the 'this.parser' but just // pass it to the parser. this.parser.language = $.i18n.languages[$.i18n().locale] || $.i18n.languages['default']; if( message === '' || message === '*' ) { if ( ( mode == "php" ) && ( message != '*' ) ) { $.post( "svc/backend/i18n/", { missing: key, lang : $.i18n().locale , layout : pageInfo["layout"] } ); } message = key; } var result = this.parser.parse( message, parameters ); if ( result.substr(0,6) == 'UTF8: ') result = result.substr(6) return result; }
javascript
{ "resource": "" }
q49284
train
function ( message, parameters ) { return message.replace( /\$(\d+)/g, function ( str, match ) { var index = parseInt( match, 10 ) - 1; return parameters[index] !== undefined ? parameters[index] : '$' + match; } ); }
javascript
{ "resource": "" }
q49285
choice
train
function choice ( parserSyntax ) { return function () { var i, result; for ( i = 0; i < parserSyntax.length; i++ ) { result = parserSyntax[i](); if ( result !== null ) { return result; } } return null; }; }
javascript
{ "resource": "" }
q49286
sequence
train
function sequence ( parserSyntax ) { var i, res, originalPos = pos, result = []; for ( i = 0; i < parserSyntax.length; i++ ) { res = parserSyntax[i](); if ( res === null ) { pos = originalPos; return null; } result.push( res ); } return result; }
javascript
{ "resource": "" }
q49287
nOrMore
train
function nOrMore ( n, p ) { return function () { var originalPos = pos, result = [], parsed = p(); while ( parsed !== null ) { result.push( parsed ); parsed = p(); } if ( result.length < n ) { pos = originalPos; return null; } return result; }; }
javascript
{ "resource": "" }
q49288
pongTableCmpFields
train
function pongTableCmpFields( a, b ) { var cellValA = getSubData( a, pongTable_sc ); var cellValB = getSubData( b, pongTable_sc ); log( "Pong-Table", 'Sort: '+pongTable_sc+" "+cellValA+" "+cellValB ); if ( Number( cellValA ) && Number( cellValB ) ) { if ( ! isNaN( parseFloat( cellValA ) ) && ! isNaN( parseFloat( cellValB ) ) ) { cellValA = parseFloat( cellValA ); cellValB = parseFloat( cellValB ); log( "Pong-Table", "parseFloat" ); } else { if ( ! isNaN( parseInt( cellValA ) ) && ! isNaN( parseInt( cellValB ) ) ) { cellValA = parseInt( cellValA ); cellValB = parseInt( cellValB ); log( "Pong-Table", "parseInt" ); } } } if ( cellValA > cellValB ) { return ( pongTable_sort_up ? 1 : -1) } if ( cellValA < cellValB ) { return ( pongTable_sort_up ? -1 : 1) } return 0; }
javascript
{ "resource": "" }
q49289
pongListUpdateRow
train
function pongListUpdateRow( divId, divs, rowDta, r, cx, i, tblDiv ) { log( "PoNG-List", 'upd-div row='+r+'/'+cx ); for ( var c = 0; c < divs.length; c ++ ) { log( "PoNG-List", 'upd-div '+cx+'/'+c ); if ( divs[c].cellType == 'div' ) { log( "PoNG-List", 'upd-div-x '+divs[c].id ); if ( divs[c].divs ) { pongListUpdateRow( divId, divs[c].divs, rowDta, r, cx+c, i, tblDiv ); } } else { var cellId = '#'+divId+'R'+i+'X'+cx+'C'+c; log( "PoNG-List", 'upd-div-n '+cellId ); var dtaArr = poTbl[ tblDiv ].pongTableData; var rowIdVal = dtaArr[r][ poTbl[ tblDiv ].pongTableDef.rowId ]; tblUpdateCell( divId, divs[c], r, c, i, rowDta, cellId, rowIdVal, tblDiv ); } } }
javascript
{ "resource": "" }
q49290
encryptSecrects
train
function encryptSecrects(server, cryptoSecret, oldSever) { const updatedServer = { ...server }; /* eslint no-param-reassign:0 */ if (server.password) { const isPassDiff = (oldSever && server.password !== oldSever.password); if (!oldSever || isPassDiff) { updatedServer.password = crypto.encrypt(server.password, cryptoSecret); } } if (server.ssh && server.ssh.password) { const isPassDiff = (oldSever && server.ssh.password !== oldSever.ssh.password); if (!oldSever || isPassDiff) { updatedServer.ssh.password = crypto.encrypt(server.ssh.password, cryptoSecret); } } updatedServer.encrypted = true; return updatedServer; }
javascript
{ "resource": "" }
q49291
BundleFile
train
function BundleFile() { var location = getTempFileName('.browserify.js'); function write(content) { fs.writeFileSync(location, content); } function exists() { return fs.existsSync(location); } function remove() { if (exists()) { fs.unlinkSync(location); } } function touch() { if (!exists()) { write(''); } } // API this.touch = touch; this.update = write; this.remove = remove; this.location = location; }
javascript
{ "resource": "" }
q49292
extractSourceMap
train
function extractSourceMap(bundleContents) { var start = bundleContents.lastIndexOf('//# sourceMappingURL'); var sourceMapComment = start !== -1 ? bundleContents.substring(start) : ''; return sourceMapComment && convert.fromComment(sourceMapComment); }
javascript
{ "resource": "" }
q49293
addBundleFile
train
function addBundleFile(bundleFile, config) { var files = config.files, preprocessors = config.preprocessors; // list of patterns using our preprocessor var patterns = reduce(preprocessors, function(matched, val, key) { if (val.indexOf('browserify') !== -1) { matched.push(key); } return matched; }, []); // first file being preprocessed var file = find(files, function(f) { return some(patterns, function(p) { return minimatch(f.pattern, p); }); }); var idx = 0; if (file) { idx = files.indexOf(file); } else { log.debug('no matching preprocessed file was found, defaulting to prepend'); } log.debug('add bundle to config.files at position', idx); // insert bundle on the correct spot files.splice(idx, 0, { pattern: bundleFile.location, served: true, included: true, watched: true }); }
javascript
{ "resource": "" }
q49294
framework
train
function framework(emitter, config, logger) { log = logger.create('framework.browserify'); if (!bundleFile) { bundleFile = new BundleFile(); } bundleFile.touch(); log.debug('created browserify bundle: %s', bundleFile.location); b = createBundle(config); // TODO(Nikku): hook into karma karmas file update facilities // to remove files from the bundle once karma detects the deletion // hook into exit for cleanup emitter.on('exit', function(done) { log.debug('cleaning up'); if (b.close) { b.close(); } bundleFile.remove(); done(); }); // add bundle file to the list of files defined in the // configuration. be smart by doing so. addBundleFile(bundleFile, config); return b; }
javascript
{ "resource": "" }
q49295
bundlePreprocessor
train
function bundlePreprocessor(config) { var debug = config.browserify && config.browserify.debug; function updateSourceMap(file, content) { var map; if (debug) { map = extractSourceMap(content); file.sourceMap = map && map.sourcemap; } } return function(content, file, done) { if (b._builtOnce) { updateSourceMap(file, content); return done(content); } log.debug('building bundle'); // wait for the initial bundle to be created b.deferredBundle(function(err, content) { b._builtOnce = config.autoWatch; if (err) { return done(BUNDLE_ERROR_TPL); } content = content.toString('utf-8'); updateSourceMap(file, content); log.info('bundle built'); done(content); }); }; }
javascript
{ "resource": "" }
q49296
Dropdown
train
function Dropdown(element, completer, option) { this.$el = Dropdown.createElement(option); this.completer = completer; this.id = completer.id + 'dropdown'; this._data = []; // zipped data. this.$inputEl = $(element); this.option = option; // Override setPosition method. if (option.listPosition) { this.setPosition = option.listPosition; } if (option.height) { this.$el.height(option.height); } var self = this; $.each(['maxCount', 'placement', 'footer', 'header', 'noResultsMessage', 'className'], function (_i, name) { if (option[name] != null) { self[name] = option[name]; } }); this._bindEvents(element); dropdownViews[this.id] = this; }
javascript
{ "resource": "" }
q49297
train
function (e) { var $el = $(e.target); e.preventDefault(); if (!$el.hasClass('textcomplete-item')) { $el = $el.closest('.textcomplete-item'); } this._index = parseInt($el.data('index'), 10); this._activateIndexedItem(); }
javascript
{ "resource": "" }
q49298
train
function (func) { var memo = {}; return function (term, callback) { if (memo[term]) { callback(memo[term]); } else { func.call(this, term, function (data) { memo[term] = (memo[term] || []).concat(data); callback.apply(null, arguments); }); } }; }
javascript
{ "resource": "" }
q49299
train
function (value, strategy, e) { var pre = this.getTextFromHeadToCaret(); // use ownerDocument instead of window to support iframes var sel = this.el.ownerDocument.getSelection(); var range = sel.getRangeAt(0); var selection = range.cloneRange(); selection.selectNodeContents(range.startContainer); var content = selection.toString(); var post = content.substring(range.startOffset); var newSubstr = strategy.replace(value, e); var regExp; if (typeof newSubstr !== 'undefined') { if ($.isArray(newSubstr)) { post = newSubstr[1] + post; newSubstr = newSubstr[0]; } regExp = $.isFunction(strategy.match) ? strategy.match(pre) : strategy.match; pre = pre.replace(regExp, newSubstr) .replace(/ $/, "&nbsp"); // &nbsp necessary at least for CKeditor to not eat spaces range.selectNodeContents(range.startContainer); range.deleteContents(); // create temporary elements var preWrapper = this.el.ownerDocument.createElement("div"); preWrapper.innerHTML = pre; var postWrapper = this.el.ownerDocument.createElement("div"); postWrapper.innerHTML = post; // create the fragment thats inserted var fragment = this.el.ownerDocument.createDocumentFragment(); var childNode; var lastOfPre; while (childNode = preWrapper.firstChild) { lastOfPre = fragment.appendChild(childNode); } while (childNode = postWrapper.firstChild) { fragment.appendChild(childNode); } // insert the fragment & jump behind the last node in "pre" range.insertNode(fragment); range.setStartAfter(lastOfPre); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } }
javascript
{ "resource": "" }