_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q25600
train
function (serviceAddress, coverageName, wcsVersion) { if (!serviceAddress || (serviceAddress.length === 0)) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WcsTileUrlBuilder", "constructor", "The WCS service address is missing.")); } if (!coverageName || (coverageName.length === 0)) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WcsTileUrlBuilder", "constructor", "The WCS coverage name is missing.")); } /** * The address of the WCS server. * @type {String} */ this.serviceAddress = serviceAddress; /** * The name of the coverage to retrieve. * @type {String} */ this.coverageName = coverageName; /** * The WCS version to specify when requesting resources. * @type {String} * @default 1.0.0 */ this.wcsVersion = (wcsVersion && wcsVersion.length > 0) ? wcsVersion : "1.0.0"; /** * The coordinate reference system to use when requesting coverages. * @type {String} * @default EPSG:4326 */ this.crs = "EPSG:4326"; }
javascript
{ "resource": "" }
q25601
train
function (position, attributes) { if (!position) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "Annotation", "constructor", "missingPosition")); } Renderable.call(this); /** * This annotation's geographic position. * @type {Position} */ this.position = position; /** * The annotation's attributes. * @type {AnnotationAttributes} * @default see [AnnotationAttributes]{@link AnnotationAttributes} */ this.attributes = attributes ? attributes : new AnnotationAttributes(null); /** * This annotation's altitude mode. May be one of * <ul> * <li>[WorldWind.ABSOLUTE]{@link WorldWind#ABSOLUTE}</li> * <li>[WorldWind.RELATIVE_TO_GROUND]{@link WorldWind#RELATIVE_TO_GROUND}</li> * <li>[WorldWind.CLAMP_TO_GROUND]{@link WorldWind#CLAMP_TO_GROUND}</li> * </ul> * @default WorldWind.ABSOLUTE */ this.altitudeMode = WorldWind.ABSOLUTE; // Internal use only. Intentionally not documented. this.layer = null; // Internal use only. Intentionally not documented. this.lastStateKey = null; // Internal use only. Intentionally not documented. this.calloutTransform = Matrix.fromIdentity(); // Internal use only. Intentionally not documented. this.calloutOffset = new WorldWind.Offset( WorldWind.OFFSET_FRACTION, 0.5, WorldWind.OFFSET_FRACTION, 0); // Internal use only. Intentionally not documented. this.label = ""; // Internal use only. Intentionally not documented. this.labelTexture = null; // Internal use only. Intentionally not documented. this.labelTransform = Matrix.fromIdentity(); // Internal use only. Intentionally not documented. this.placePoint = new Vec3(0, 0, 0); // Internal use only. Intentionally not documented. this.depthOffset = -2.05; // Internal use only. Intentionally not documented. this.calloutPoints = null; }
javascript
{ "resource": "" }
q25602
train
function (center, width, height, heading, attributes) { if (!center) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfaceRectangle", "constructor", "missingLocation")); } if (width < 0 || height < 0) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfaceRectangle", "constructor", "Size is negative.")); } SurfaceShape.call(this, attributes); // All these are documented with their property accessors below. this._center = center; this._width = width; this._height = height; this._heading = heading; }
javascript
{ "resource": "" }
q25603
train
function (m11, m12, m13, m21, m22, m23, m31, m32, m33) { this[0] = m11; this[1] = m12; this[2] = m13; this[3] = m21; this[4] = m22; this[5] = m23; this[6] = m31; this[7] = m32; this[8] = m33; }
javascript
{ "resource": "" }
q25604
train
function (message) { AbstractError.call(this, "UnsupportedOperationError", message); var stack; try { //noinspection ExceptionCaughtLocallyJS throw new Error(); } catch (e) { stack = e.stack; } this.stack = stack; }
javascript
{ "resource": "" }
q25605
train
function (sector, level, row, column) { Tile.call(this, sector, level, row, column); // args are checked in the superclass' constructor /** * The transformation matrix that maps tile local coordinates to model coordinates. * @type {Matrix} */ this.transformationMatrix = Matrix.fromIdentity(); /** * The tile's model coordinate points. * @type {Float32Array} */ this.points = null; /** * Indicates the state of this tile when the model coordinate points were last updated. This is used to * invalidate the points when this tile's state changes. * @type {String} */ this.pointsStateKey = null; /** * Indicates the state of this tile when the model coordinate VBO was last uploaded to GL. This is used to * invalidate the VBO when the tile's state changes. * @type {String} */ this.pointsVboStateKey = null; // Internal use. Intentionally not documented. this.neighborMap = {}; this.neighborMap[WorldWind.NORTH] = null; this.neighborMap[WorldWind.SOUTH] = null; this.neighborMap[WorldWind.EAST] = null; this.neighborMap[WorldWind.WEST] = null; // Internal use. Intentionally not documented. this._stateKey = null; // Internal use. Intentionally not documented. this._elevationTimestamp = null; // Internal use. Intentionally not documented. this.scratchArray = []; }
javascript
{ "resource": "" }
q25606
train
function (serverAddress, pathToData, displayName, configuration) { var cachePath = WWUtil.urlPath(serverAddress + "/" + pathToData); TiledImageLayer.call(this, (configuration && configuration.sector) || Sector.FULL_SPHERE, (configuration && configuration.levelZeroTileDelta) || new Location(45, 45), (configuration && configuration.numLevels) || 5, (configuration && configuration.imageFormat) || "image/jpeg", cachePath, (configuration && configuration.tileWidth) || 256, (configuration && configuration.tileHeight) || 256); this.displayName = displayName; this.pickEnabled = false; this.urlBuilder = new LevelRowColumnUrlBuilder(serverAddress, pathToData); }
javascript
{ "resource": "" }
q25607
train
function (coverageId, webCoverageService) { if (!coverageId) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WcsCoverage", "constructor", "missingId")); } if (!webCoverageService) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WcsCoverage", "constructor", "missingWebCoverageService")); } /** * The Web Coverage Service Coverages id or name as assigned by the providing service. * @type {String} */ this.coverageId = coverageId; /** * The WebCoverageService responsible for managing this Coverage and Web Coverage Service. * @type {WebCoverageService} */ this.service = webCoverageService; /** * The Sector representing the bounds of the coverage. * @type {Sector} */ this.sector = this.service.coverageDescriptions.getSector(this.coverageId); /** * The resolution of the coverage, in degrees. * @type {Number} */ this.resolution = this.service.coverageDescriptions.getResolution(this.coverageId); /** * A configuration object for use by TiledElevationCoverage. * @type {{}} */ this.elevationConfig = this.createElevationConfig(); }
javascript
{ "resource": "" }
q25608
train
function (serverAddress, pathToData, displayName, initialTime) { Layer.call(this, displayName || "Blue Marble time series"); /** * A value indicating the month to display. The nearest month to the specified time is displayed. * @type {Date} * @default January 2004 (new Date("2004-01")); */ this.time = initialTime || new Date("2004-01"); // Intentionally not documented. this.timeSequence = new PeriodicTimeSequence("2004-01-01/2004-12-01/P1M"); // Intentionally not documented. this.serverAddress = serverAddress; // Intentionally not documented. this.pathToData = pathToData; // Intentionally not documented. this.layers = {}; // holds the layers as they're created. // Intentionally not documented. this.layerNames = [ {month: "BlueMarble-200401", time: BMNGRestLayer.availableTimes[0]}, {month: "BlueMarble-200402", time: BMNGRestLayer.availableTimes[1]}, {month: "BlueMarble-200403", time: BMNGRestLayer.availableTimes[2]}, {month: "BlueMarble-200404", time: BMNGRestLayer.availableTimes[3]}, {month: "BlueMarble-200405", time: BMNGRestLayer.availableTimes[4]}, {month: "BlueMarble-200406", time: BMNGRestLayer.availableTimes[5]}, {month: "BlueMarble-200407", time: BMNGRestLayer.availableTimes[6]}, {month: "BlueMarble-200408", time: BMNGRestLayer.availableTimes[7]}, {month: "BlueMarble-200409", time: BMNGRestLayer.availableTimes[8]}, {month: "BlueMarble-200410", time: BMNGRestLayer.availableTimes[9]}, {month: "BlueMarble-200411", time: BMNGRestLayer.availableTimes[10]}, {month: "BlueMarble-200412", time: BMNGRestLayer.availableTimes[11]} ]; this.pickEnabled = false; }
javascript
{ "resource": "" }
q25609
train
function () { var result = {}; var queryString = window.location.href.split("?"); if (queryString && queryString.length > 1) { var args = queryString[1].split("&"); for (var a = 0; a < args.length; a++) { var arg = args[a].split("="); // Obtain geographic position to redirect WorldWindow camera view. if (arg[0] === "pos") { // arg format is "pos=lat,lon,alt" var position = arg[1].split(","), lat = parseFloat(position[0]), lon = parseFloat(position[1]), alt = parseFloat(position[2]); result.position = new WorldWind.Position(lat, lon, alt); } } } return result; }
javascript
{ "resource": "" }
q25610
train
function (drawContext) { if (!drawContext) { throw new ArgumentError(Logger.logMessage(Logger.LEVEL_SEVERE, "TextRenderer", "constructor", "missingDc")); } // Internal use only. Intentionally not documented. this.canvas2D = document.createElement("canvas"); // Internal use only. Intentionally not documented. this.ctx2D = this.canvas2D.getContext("2d"); // Internal use only. Intentionally not documented. this.dc = drawContext; /** * Indicates if the text will feature an outline around its characters. * @type {boolean} */ this.enableOutline = true; // Internal use only. Intentionally not documented. this.lineSpacing = 0.15; // fraction of font size /** * The color for the Text outline. * Its default has half transparency to avoid visual artifacts that appear while fully opaque. * @type {Color} */ this.outlineColor = new Color(0, 0, 0, 0.5); /** * Indicates the text outline width (or thickness) in pixels. * @type {number} */ this.outlineWidth = 4; /** * The text color. * @type {Color} */ this.textColor = new Color(1, 1, 1, 1); /** * The text size, face and other characteristics, as described in [Font]{@link Font}. * @type {Font} */ this.typeFace = new Font(14); }
javascript
{ "resource": "" }
q25611
train
function (worldWindow) { var thisGoToBox = this; this.wwd = worldWindow; $("#searchBox").find("button").on("click", function (e) { thisGoToBox.onSearchButton(e); }); this.geocoder = new WorldWind.NominatimGeocoder(); $("#searchText").on("keypress", function (e) { thisGoToBox.onSearchTextKeyPress($(this), e); }); }
javascript
{ "resource": "" }
q25612
train
function (xmlDom) { // Create a WmsCapabilities object from the XML DOM var wms = new WorldWind.WmsCapabilities(xmlDom); // Retrieve a WmsLayerCapabilities object by the desired layer name var wmsLayerCapabilities = wms.getNamedLayer(layerName); // Form a configuration object from the WmsLayerCapability object var wmsConfig = WorldWind.WmsLayer.formLayerConfiguration(wmsLayerCapabilities); // Modify the configuration objects title property to a more user friendly title wmsConfig.title = "Average Surface Temp"; // Create the WMS Layer from the configuration object var wmsLayer = new WorldWind.WmsLayer(wmsConfig); // Add the layers to WorldWind and update the layer manager wwd.addLayer(wmsLayer); layerManager.synchronizeLayerList(); }
javascript
{ "resource": "" }
q25613
train
function(options) { if(!options.ajax && !options.zip) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "RemoteDocument", "constructor", "Invalid option for retrieval specified. Use either ajax or zip option.") ); } this.options = options; }
javascript
{ "resource": "" }
q25614
train
function (center, majorRadius, minorRadius, heading, attributes) { if (!center) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfaceEllipse", "constructor", "missingLocation")); } if (majorRadius < 0 || minorRadius < 0) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfaceEllipse", "constructor", "Radius is negative.")); } SurfaceShape.call(this, attributes); // All these are documented with their property accessors below. this._center = center; this._majorRadius = majorRadius; this._minorRadius = minorRadius; this._heading = heading; this._intervals = SurfaceEllipse.DEFAULT_NUM_INTERVALS; }
javascript
{ "resource": "" }
q25615
train
function (layerElement, parentNode) { if (!layerElement) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WmsLayerCapabilities", "constructor", "Layer element is null or undefined.")); } /** * The parent object, as specified to the constructor of this object. * @type {{}} * @readonly */ this.parent = parentNode; /** * The layers that are children of this layer. * @type {WmsLayerCapabilities[]} * @readonly */ this.layers; /** * The name of this layer description. * @type {String} * @readonly */ this.name; /** * The title of this layer. * @type {String} * @readonly */ this.title; /** * The abstract of this layer. * @type {String} * @readonly */ this.abstract; /** * The list of keywords associated with this layer description. * @type {String[]} * @readonly */ this.keywordList; /** * The identifiers associated with this layer description. Each identifier has the following properties: * authority, content. * @type {Object[]} */ this.identifiers; /** * The metadata URLs associated with this layer description. Each object in the returned array has the * following properties: type, format, url. * @type {Object[]} * @readonly */ this.metadataUrls; /** * The data URLs associated with this layer description. Each object in the returned array has the * following properties: format, url. * @type {Object[]} * @readonly */ this.dataUrls; /** * The feature list URLs associated with this layer description. Each object in the returned array has the * following properties: format, url. * @type {Object[]} * @readonly */ this.featureListUrls; this.assembleLayer(layerElement); }
javascript
{ "resource": "" }
q25616
train
function (position, eyeDistanceScaling, attributes) { if (!position) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "Placemark", "constructor", "missingPosition")); } Renderable.call(this); /** * The placemark's attributes. If null and this placemark is not highlighted, this placemark is not * drawn. * @type {PlacemarkAttributes} * @default see [PlacemarkAttributes]{@link PlacemarkAttributes} */ this.attributes = attributes ? attributes : new PlacemarkAttributes(null); /** * The attributes used when this placemark's highlighted flag is true. If null and the * highlighted flag is true, this placemark's normal attributes are used. If they, too, are null, this * placemark is not drawn. * @type {PlacemarkAttributes} * @default null */ this.highlightAttributes = null; /** * Indicates whether this placemark uses its highlight attributes rather than its normal attributes. * @type {Boolean} * @default false */ this.highlighted = false; /** * This placemark's geographic position. * @type {Position} */ this.position = position; /** * Indicates whether this placemark's size is reduced at higher eye distances. If true, this placemark's * size is scaled inversely proportional to the eye distance if the eye distance is greater than the * value of the [eyeDistanceScalingThreshold]{@link Placemark#eyeDistanceScalingThreshold} property. * When the eye distance is below the threshold, this placemark is scaled only according to the * [imageScale]{@link PlacemarkAttributes#imageScale}. * @type {Boolean} */ this.eyeDistanceScaling = eyeDistanceScaling; /** * The eye distance above which to reduce the size of this placemark, in meters. If * [eyeDistanceScaling]{@link Placemark#eyeDistanceScaling} is true, this placemark's image, label and leader * line sizes are reduced as the eye distance increases beyond this threshold. * @type {Number} * @default 1e6 (meters) */ this.eyeDistanceScalingThreshold = 1e6; /** * The eye altitude above which this placemark's label is not displayed. * @type {number} */ this.eyeDistanceScalingLabelThreshold = 1.5 * this.eyeDistanceScalingThreshold; /** * This placemark's textual label. If null, no label is drawn. * @type {String} * @default null */ this.label = null; /** * This placemark's altitude mode. May be one of * <ul> * <li>[WorldWind.ABSOLUTE]{@link WorldWind#ABSOLUTE}</li> * <li>[WorldWind.RELATIVE_TO_GROUND]{@link WorldWind#RELATIVE_TO_GROUND}</li> * <li>[WorldWind.CLAMP_TO_GROUND]{@link WorldWind#CLAMP_TO_GROUND}</li> * </ul> * @default WorldWind.ABSOLUTE */ this.altitudeMode = WorldWind.ABSOLUTE; /** * Indicates whether this placemark has visual priority over other shapes in the scene. * @type {Boolean} * @default false */ this.alwaysOnTop = false; /** * Indicates whether this placemark's leader line, if any, is pickable. * @type {Boolean} * @default false */ this.enableLeaderLinePicking = false; /** * Indicates whether this placemark's image should be re-retrieved even if it has already been retrieved. * Set this property to true when the image has changed but has the same image path. * The property is set to false when the image is re-retrieved. * @type {Boolean} */ this.updateImage = true; /** * Indicates the group ID of the declutter group to include this placemark. If non-zero, this placemark * is decluttered relative to all other shapes within its group. * @type {Number} * @default 2 */ this.declutterGroup = 2; /** * This placemark's target label visibility, a value between 0 and 1. During ordered rendering this * placemark modifies its [current visibility]{@link Placemark#currentVisibility} towards its target * visibility at the rate specified by the draw context's [fade time]{@link DrawContext#fadeTime} property. * The target visibility and current visibility are used to control the fading in and out of this * placemark's label. * @type {Number} * @default 1 */ this.targetVisibility = 1; /** * This placemark's current label visibility, a value between 0 and 1. This property scales the placemark's * effective label opacity. It is incremented or decremented each frame according to the draw context's * [fade time]{@link DrawContext#fadeTime} property in order to achieve this placemark's * [target visibility]{@link Placemark#targetVisibility}. This current visibility and target visibility are * used to control the fading in and out of this placemark's label. * @type {Number} * @default 1 * @readonly */ this.currentVisibility = 1; /** * The amount of rotation to apply to the image, measured in degrees clockwise and relative to this * placemark's [imageRotationReference]{@link Placemark#imageRotationReference}. * @type {Number} * @default 0 */ this.imageRotation = 0; /** * The amount of tilt to apply to the image, measured in degrees away from the eye point and relative * to this placemark's [imageTiltReference]{@link Placemark#imageTiltReference}. While any positive or * negative number may be specified, values outside the range [0. 90] cause some or all of the image to * be clipped. * @type {Number} * @default 0 */ this.imageTilt = 0; /** * Indicates whether to apply this placemark's image rotation relative to the screen or the globe. * If WorldWind.RELATIVE_TO_SCREEN, this placemark's image is rotated in the plane of the screen and * its orientation relative to the globe changes as the view changes. * If WorldWind.RELATIVE_TO_GLOBE, this placemark's image is rotated in a plane tangent to the globe * at this placemark's position and retains its orientation relative to the globe. * @type {String} * @default WorldWind.RELATIVE_TO_SCREEN */ this.imageRotationReference = WorldWind.RELATIVE_TO_SCREEN; /** * Indicates whether to apply this placemark's image tilt relative to the screen or the globe. * If WorldWind.RELATIVE_TO_SCREEN, this placemark's image is tilted inwards (for positive tilts) * relative to the plane of the screen, and its orientation relative to the globe changes as the view * changes. If WorldWind.RELATIVE_TO_GLOBE, this placemark's image is tilted towards the globe's surface, * and retains its orientation relative to the surface. * @type {string} * @default WorldWind.RELATIVE_TO_SCREEN */ this.imageTiltReference = WorldWind.RELATIVE_TO_SCREEN; // Internal use only. Intentionally not documented. this.activeAttributes = null; // Internal use only. Intentionally not documented. this.activeTexture = null; // Internal use only. Intentionally not documented. this.labelTexture = null; // Internal use only. Intentionally not documented. this.placePoint = new Vec3(0, 0, 0); // Cartesian point corresponding to this placemark's geographic position // Internal use only. Intentionally not documented. this.groundPoint = new Vec3(0, 0, 0); // Cartesian point corresponding to ground position below this placemark // Internal use only. Intentionally not documented. this.imageTransform = Matrix.fromIdentity(); // Internal use only. Intentionally not documented. this.labelTransform = Matrix.fromIdentity(); // Internal use only. Intentionally not documented. this.texCoordMatrix = Matrix.fromIdentity(); // Internal use only. Intentionally not documented. this.imageBounds = null; // Internal use only. Intentionally not documented. this.layer = null; // Internal use only. Intentionally not documented. this.depthOffset = -0.003; }
javascript
{ "resource": "" }
q25617
train
function (sector, attributes) { if (!sector) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfaceSector", "constructor", "missingSector")); } SurfaceShape.call(this, attributes); /** * This shape's sector. * @type {Sector} */ this._sector = sector; // The default path type for a surface sector is linear so that it represents a bounding box by default. this._pathType = WorldWind.LINEAR; }
javascript
{ "resource": "" }
q25618
train
function (config, timeString) { if (!config) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WmsLayer", "constructor", "No configuration specified.")); } var cachePath = config.service + config.layerNames + config.styleNames; if (timeString) { cachePath = cachePath + timeString; } TiledImageLayer.call(this, config.sector, config.levelZeroDelta, config.numLevels, config.format, cachePath, config.size, config.size); this.displayName = config.title; this.pickEnabled = false; this.urlBuilder = new WmsUrlBuilder(config.service, config.layerNames, config.styleNames, config.version, timeString); if (config.coordinateSystem) { this.urlBuilder.crs = config.coordinateSystem; } /** * The time string passed to this layer's constructor. * @type {String} * @readonly */ this.timeString = timeString; }
javascript
{ "resource": "" }
q25619
train
function () { /** * The box's center point. * @type {Vec3} * @default (0, 0, 0) */ this.center = new Vec3(0, 0, 0); /** * The center point of the box's bottom. (The origin of the R axis.) * @type {Vec3} * @default (-0.5, 0, 0) */ this.bottomCenter = new Vec3(-0.5, 0, 0); /** * The center point of the box's top. (The end of the R axis.) * @type {Vec3} * @default (0.5, 0, 0) */ this.topCenter = new Vec3(0.5, 0, 0); /** * The box's R axis, its longest axis. * @type {Vec3} * @default (1, 0, 0) */ this.r = new Vec3(1, 0, 0); /** * The box's S axis, its mid-length axis. * @type {Vec3} * @default (0, 1, 0) */ this.s = new Vec3(0, 1, 0); /** * The box's T axis, its shortest axis. * @type {Vec3} * @default (0, 0, 1) */ this.t = new Vec3(0, 0, 1); /** * The box's radius. (The half-length of its diagonal.) * @type {number} * @default sqrt(3) */ this.radius = Math.sqrt(3); // Internal use only. Intentionally not documented. this.tmp1 = new Vec3(0, 0, 0); this.tmp2 = new Vec3(0, 0, 0); this.tmp3 = new Vec3(0, 0, 0); // Internal use only. Intentionally not documented. this.scratchElevations = new Float64Array(9); this.scratchPoints = new Float64Array(3 * this.scratchElevations.length); }
javascript
{ "resource": "" }
q25620
train
function (config) { if (!config) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "TiledElevationCoverage", "constructor", "missingConfig")); } if (!config.coverageSector) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "TiledElevationCoverage", "constructor", "missingSector")); } if (!config.resolution) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "TiledElevationCoverage", "constructor", "missingResolution")); } if (!config.retrievalImageFormat) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "TiledElevationCoverage", "constructor", "missingImageFormat")); } ElevationCoverage.call(this, config.resolution); var firstLevelDelta = 45, tileWidth = 256, lastLevel = LevelSet.numLevelsForResolution(firstLevelDelta / tileWidth, config.resolution), numLevels = Math.ceil(lastLevel); // match or exceed the specified resolution /** * The sector this coverage spans. * @type {Sector} * @readonly */ this.coverageSector = config.coverageSector; /** * The mime type to use when retrieving elevations. * @type {String} * @readonly */ this.retrievalImageFormat = config.retrievalImageFormat; /** * This coverage's minimum elevation in meters. * @type {Number} * @default 0 */ this.minElevation = config.minElevation || 0; /** * This coverage's maximum elevation in meters. * @type {Number} */ this.maxElevation = config.maxElevation || 0; /** * Indicates whether the data associated with this coverage is point data. A value of false * indicates that the data is area data (pixel is area). * @type {Boolean} * @default true */ this.pixelIsPoint = false; /** * The {@link LevelSet} dividing this coverage's geographic domain into a multi-resolution, hierarchical * collection of tiles. * @type {LevelSet} * @readonly */ this.levels = new LevelSet(this.coverageSector, new Location(firstLevelDelta, firstLevelDelta), numLevels, tileWidth, tileWidth); /** * Internal use only * The list of assembled tiles. * @type {Array} * @ignore */ this.currentTiles = []; /** * Internal use only * A scratch sector for use in computations. * @type {Sector} * @ignore */ this.currentSector = new Sector(0, 0, 0, 0); /** * Internal use only * A cache of elevation tiles. * @type {MemoryCache} * @ignore */ this.tileCache = new MemoryCache(1000000, 800000); /** * Internal use only * A cache of elevations. * @type {MemoryCache} * @ignore */ this.imageCache = new MemoryCache(10000000, 8000000); /** * Controls how many concurrent tile requests are allowed for this coverage. * @type {Number} * @default WorldWind.configuration.coverageRetrievalQueueSize */ this.retrievalQueueSize = WorldWind.configuration.coverageRetrievalQueueSize; /** * Internal use only * The list of elevation retrievals in progress. * @type {Array} * @ignore */ this.currentRetrievals = []; /** * Internal use only * The list of resources pending acquisition. * @type {Array} * @ignore */ this.absentResourceList = new AbsentResourceList(3, 5e3); /** * Internal use only * The factory to create URLs for data requests. This property is typically set in the constructor of child * classes. See {@link WcsUrlBuilder} for a concrete example. * @type {UrlBuilder} * @ignore */ this.urlBuilder = config.urlBuilder || null; }
javascript
{ "resource": "" }
q25621
train
function (sector, tileMatrix, row, column, imagePath) { this.sector = sector; this.tileMatrix = tileMatrix; this.row = row; this.column = column; this.imagePath = imagePath; this.texelSize = (sector.deltaLatitude() * Angle.DEGREES_TO_RADIANS) / tileMatrix.tileHeight; this.tileKey = tileMatrix.levelNumber.toString() + "." + row.toString() + "." + column.toString(); this.gpuCacheKey = imagePath; }
javascript
{ "resource": "" }
q25622
train
function (sector, level, row, column, cacheKey) { if (!cacheKey || (cacheKey.length < 1)) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "FramebufferTile", "constructor", "The specified cache name is null, undefined or zero length.")); } TextureTile.call(this, sector, level, row, column); // args are checked in the superclass' constructor // Assign the cacheKey as the gpuCacheKey (inherited from TextureTile). this.gpuCacheKey = cacheKey; // Internal. Intentionally not documented. this.textureTransform = Matrix.fromIdentity().setToUnitYFlip(); // Internal. Intentionally not documented. this.mustClear = true; }
javascript
{ "resource": "" }
q25623
doCalc
train
function doCalc() { var distance = lengthMeasurer.getLength(pathPositions, false, WorldWind.GREAT_CIRCLE); var terrainDistance = lengthMeasurer.getLength(pathPositions, true, WorldWind.GREAT_CIRCLE); var geographicDistance = lengthMeasurer.getGeographicDistance(pathPositions, WorldWind.GREAT_CIRCLE); var area = areaMeasurer.getArea(pathPositions, false); var terrainArea = areaMeasurer.getArea(pathPositions, true); // Display the results. geoDistSpan.textContent = (geographicDistance / 1e3).toFixed(3); distSpan.textContent = (distance / 1e3).toFixed(3); terrainDistSpan.textContent = (terrainDistance / 1e3).toFixed(3); projectedAreaSpan.textContent = (area / 1e6).toFixed(3); terrainAreaSpan.textContent = (terrainArea / 1e6).toFixed(3); }
javascript
{ "resource": "" }
q25624
train
function(callback) { this.factory.running = false; this._clearInterval(callback); this.callback(this.callbacks.stop); this.callback(callback); }
javascript
{ "resource": "" }
q25625
train
function(callback) { var t = this; t._interval(callback); t.timer = setInterval(function() { t._interval(callback); }, this.interval); }
javascript
{ "resource": "" }
q25626
train
function(digit) { var obj = this.createList(digit, { classes: { active: this.factory.classes.active, before: this.factory.classes.before, flip: this.factory.classes.flip } }); this.appendDigitToClock(obj); }
javascript
{ "resource": "" }
q25627
train
function(name) { var lang; if(FlipClock.Lang[name.ucfirst()]) { lang = FlipClock.Lang[name.ucfirst()]; } else if(FlipClock.Lang[name]) { lang = FlipClock.Lang[name]; } else { lang = FlipClock.Lang[this.defaultLanguage]; } return this.lang = lang; }
javascript
{ "resource": "" }
q25628
train
function(callback) { var t = this; if(!t.running && (!t.countdown || t.countdown && t.time.time > 0)) { t.face.start(t.time); t.timer.start(function() { t.flip(); if(typeof callback === "function") { callback(); } }); } else { t.log('Trying to start timer when countdown already at 0'); } }
javascript
{ "resource": "" }
q25629
train
function(_default, options) { if(typeof _default !== "object") { _default = {}; } if(typeof options !== "object") { options = {}; } this.setOptions($.extend(true, {}, _default, options)); }
javascript
{ "resource": "" }
q25630
train
function(method) { if(typeof method === "function") { var args = []; for(var x = 1; x <= arguments.length; x++) { if(arguments[x]) { args.push(arguments[x]); } } method.apply(this, args); } }
javascript
{ "resource": "" }
q25631
train
function(str) { var data = []; str = str.toString(); for(var x = 0;x < str.length; x++) { if(str[x].match(/^\d*$/g)) { data.push(str[x]); } } return data; }
javascript
{ "resource": "" }
q25632
train
function(i) { var timeStr = this.toString(); var length = timeStr.length; if(timeStr[length - i]) { return timeStr[length - i]; } return false; }
javascript
{ "resource": "" }
q25633
train
function(obj) { var data = []; $.each(obj, function(i, value) { value = value.toString(); if(value.length == 1) { value = '0'+value; } for(var x = 0; x < value.length; x++) { data.push(value.charAt(x)); } }); if(data.length > this.minimumDigits) { this.minimumDigits = data.length; } if(this.minimumDigits > data.length) { for(var x = data.length; x < this.minimumDigits; x++) { data.unshift('0'); } } return data; }
javascript
{ "resource": "" }
q25634
train
function(includeSeconds) { var digits = [ this.getDays(), this.getHours(true), this.getMinutes(true) ]; if(includeSeconds) { digits.push(this.getSeconds(true)); } return this.digitize(digits); }
javascript
{ "resource": "" }
q25635
train
function(date) { if(!date) { date = new Date(); } if (this.time instanceof Date) { if (this.factory.countdown) { return Math.max(this.time.getTime()/1000 - date.getTime()/1000,0); } else { return date.getTime()/1000 - this.time.getTime()/1000 ; } } else { return this.time; } }
javascript
{ "resource": "" }
q25636
train
function(totalDigits, digits) { var total = 0; var newArray = []; $.each(digits, function(i, digit) { if(i < totalDigits) { total += parseInt(digits[i], 10); } else { newArray.push(digits[i]); } }); if(total === 0) { return newArray; } return digits; }
javascript
{ "resource": "" }
q25637
train
function(x) { if(this.time instanceof Date) { this.time.setSeconds(this.time.getSeconds() + x); } else { this.time += x; } }
javascript
{ "resource": "" }
q25638
createRedisClient
train
function createRedisClient(clientConfig, callback) { let c = require('config'); let client = null; let conId = null; let redisOpts = { //showFriendlyErrorStack: true, db: clientConfig.dbIndex, password: clientConfig.password, connectionName: clientConfig.connectionName || c.get('redis.connectionName'), retryStrategy: function (times) { return times > 10 ? 3000 : 1000; } }; // add tls support (simple and complex) // 1) boolean flag - simple tls without cert validation and similiar // 2) object - all params allowed for tls socket possible (see https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options) if (typeof clientConfig.tls === 'boolean' && clientConfig.tls) { redisOpts.tls = {}; } else if (typeof clientConfig.tls === 'object') { redisOpts.tls = clientConfig.tls; } if (clientConfig.sentinels) { Object.assign(redisOpts, { sentinels: clientConfig.sentinels, name: clientConfig.sentinel_name || 'mymaster', }); conId = `S:${redisOpts.sentinels[0].host}:${redisOpts.sentinels[0].port}:${redisOpts.name}-${redisOpts.db}`; } else { Object.assign(redisOpts, { port: clientConfig.port, host: clientConfig.host, path: clientConfig.path, family: 4 }); if (clientConfig.path) { // unix-socket: // no need for strong crypto here, just short string hopefully unique between different socket paths // only needed if someone uses this app with multiple different local redis sockets... // ATTN: use no hardcoded algorithm as some systems may not support it. just search for a sha-something let hashAlg = crypto.getHashes().find((h) => (h.startsWith('sha'))); let cid =crypto.createHash(hashAlg).update(clientConfig.path).digest('hex').substring(24); conId = `U:${cid}:${redisOpts.db}`; } else { conId = `R:${redisOpts.host}:${redisOpts.port}:${redisOpts.db}`; } } client = new Redis(redisOpts); client.label = clientConfig.label; client.options.connectionId = clientConfig.connectionId = conId; return client; }
javascript
{ "resource": "" }
q25639
parseRedisSentinel
train
function parseRedisSentinel(key, sentinelsString) { if (!sentinelsString) return []; // convert array entries from string to object if needed if (Array.isArray(sentinelsString)) { sentinelsString.forEach(function(entry, index) { if (typeof entry === 'string') { let tmp = entry.trim().split(':'); sentinelsString[index] = {host: tmp[0].toLowerCase(), port: parseInt(tmp[1])}; } }); return sentinelsString.sort((i1, i2) => ((i1.host.toLowerCase()) > i2.host.toLowerCase() || i1.port - i2.port)); } if (typeof sentinelsString !== 'string') { throw new Error('Invalid type for key ' + key + ': must be either comma separated string with sentinels or list of them'); } try { let sentinels = []; if (sentinelsString.startsWith('[')) { let obj = JSON.parse(sentinelsString); obj.forEach(function(sentinel) { if (typeof sentinel === 'object') sentinels.push(sentinel); else { let tmp = sentinel.trim().split(':'); sentinels.push({host: tmp[0].toLowerCase(), port: parseInt(tmp[1])}); } }); } else { // simple string, comma separated list of host:port let obj = sentinelsString.split(','); obj.forEach(function(sentinel) { if (sentinel && sentinel.trim()) { let tmp = sentinel.trim().split(':'); sentinels.push({host: tmp[0].toLowerCase(), port: parseInt(tmp[1])}); } }); } return sentinels.sort((i1, i2) => ((i1.host.toLowerCase()) > i2.host.toLowerCase() || i1.port - i2.port)); } catch (e) { throw new Error('Invalid type for key ' + key + ': Cannot parse redis sentinels string - ' + e.message ); } }
javascript
{ "resource": "" }
q25640
enableJsonValidationCheck
train
function enableJsonValidationCheck(value, isJsonCheckBox) { try { JSON.parse(value); // if this is valid json and is array or object assume we want validation active if (value.match(/^\s*[{\[]/)) { $(isJsonCheckBox).click(); } } catch (ex) { // do nothing } }
javascript
{ "resource": "" }
q25641
addInputValidator
train
function addInputValidator(inputId, format, currentState) { var input; if (typeof inputId === 'string') { input = $('#' + inputId) } else if (typeof inputId === 'object') { input = inputId; } if (!input){ console.log('Invalid html id given to validate format: ', inputId); return; } switch (format) { case 'json': input.on('keyup', validateInputAsJson); break; default: console.log('Invalid format given to validate input: ', format); return; } // set initial state if requested if (typeof currentState === 'boolean') { setValidationClasses(input.get(0), currentState); } else { input.trigger( "keyup" ); } }
javascript
{ "resource": "" }
q25642
validateInputAsJson
train
function validateInputAsJson() { if (this.value) { try { JSON.parse(this.value); setValidationClasses(this, true); } catch(e) { setValidationClasses(this, false); } } else { setValidationClasses(this, false) } }
javascript
{ "resource": "" }
q25643
setValidationClasses
train
function setValidationClasses(element, success) { var add = (success ? 'validate-positive' : 'validate-negative'); var remove = (success ? 'validate-negative' : 'validate-positive'); if (element.className.indexOf(add) < 0) { $(element).removeClass(remove).addClass(add); } }
javascript
{ "resource": "" }
q25644
renderEjs
train
function renderEjs(filename, data, element, callback) { $.get(filename) .done(function(htmlTmpl) { element.html(ejs.render(htmlTmpl, data)); }) .fail(function(error) { console.log('failed to get html template ' + filename + ': ' + JSON.stringify(error)); alert('failed to fetch html template ' + filename); }) .always(function () { if (typeof callback === 'function') callback(); resizeApp(); }); }
javascript
{ "resource": "" }
q25645
getConnection
train
function getConnection (req, res, next, connectionId) { let con = req.app.locals.redisConnections.find(function(connection) { return (connection.options.connectionId === connectionId); }); if (con) { res.locals.connection = con; res.locals.connectionId = connectionId; } else { console.error('Connection with id ' + connectionId + ' not found.'); return printError(res, next, null, req.originalUrl); } next(); }
javascript
{ "resource": "" }
q25646
postExec
train
function postExec (req, res) { let cmd = req.body.cmd; let connection = res.locals.connection; let parts = myutil.split(cmd); parts[0] = parts[0].toLowerCase(); let commandName = parts[0].toLowerCase(); // must be in our white list to be allowed in read only mode if (req.app.locals.redisReadOnly) { if (!isReadOnlyCommand(commandName, connection)) { return res.send('ERROR: Command not read-only'); } } let args = parts.slice(1); args.push(function (err, results) { if (err) { return res.send(err.message); } return res.send(JSON.stringify(results)); }); // check if command is valid is done by ioredis if called with // 'connection.call(command, ...)' and our callback called to handle it // but throws Error if called via 'connection[commandName].apply(connection, ...)' connection.call(commandName, ...args); }
javascript
{ "resource": "" }
q25647
train
function(options, callback) { return AuthenticationRequest.builder() .withPath('/api/token') .withBodyParameters({ grant_type: 'client_credentials' }) .withBodyParameters(options) .withHeaders({ Authorization: 'Basic ' + new Buffer( this.getClientId() + ':' + this.getClientSecret() ).toString('base64') }) .build() .execute(HttpManager.post, callback); }
javascript
{ "resource": "" }
q25648
train
function(code, callback) { return AuthenticationRequest.builder() .withPath('/api/token') .withBodyParameters({ grant_type: 'authorization_code', redirect_uri: this.getRedirectURI(), code: code, client_id: this.getClientId(), client_secret: this.getClientSecret() }) .build() .execute(HttpManager.post, callback); }
javascript
{ "resource": "" }
q25649
train
function(trackId, options, callback) { // In case someone is using a version where options parameter did not exist. var actualCallback, actualOptions; if (typeof options === 'function' && !callback) { actualCallback = options; actualOptions = {}; } else { actualCallback = callback; actualOptions = options; } return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/tracks/' + trackId) .withQueryParameters(actualOptions) .build() .execute(HttpManager.get, actualCallback); }
javascript
{ "resource": "" }
q25650
train
function(trackIds, options, callback) { // In case someone is using a version where options parameter did not exist. var actualCallback, actualOptions; if (typeof options === 'function' && !callback) { actualCallback = options; actualOptions = {}; } else { actualCallback = callback; actualOptions = options; } return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/tracks') .withQueryParameters( { ids: trackIds.join(',') }, actualOptions ) .build() .execute(HttpManager.get, actualCallback); }
javascript
{ "resource": "" }
q25651
train
function(query, types, options, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/search/') .withQueryParameters( { type: types.join(','), q: query }, options ) .build() .execute(HttpManager.get, callback); }
javascript
{ "resource": "" }
q25652
train
function(userId, options, callback) { var path; if (typeof userId === 'string') { path = '/v1/users/' + encodeURIComponent(userId) + '/playlists'; } else if (typeof userId === 'object') { callback = options; options = userId; path = '/v1/me/playlists'; } /* undefined */ else { path = '/v1/me/playlists'; } return WebApiRequest.builder(this.getAccessToken()) .withPath(path) .withQueryParameters(options) .build() .execute(HttpManager.get, callback); }
javascript
{ "resource": "" }
q25653
train
function(userId, playlistName, options, callback) { // In case someone is using a version where options parameter did not exist. var actualCallback; if (typeof options === 'function' && !callback) { actualCallback = options; } else { actualCallback = callback; } var actualOptions = { name: playlistName }; if (typeof options === 'object') { Object.keys(options).forEach(function(key) { actualOptions[key] = options[key]; }); } return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/users/' + encodeURIComponent(userId) + '/playlists') .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters(actualOptions) .build() .execute(HttpManager.post, actualCallback); }
javascript
{ "resource": "" }
q25654
train
function(playlistId, options, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/playlists/' + playlistId + '/followers') .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters(options) .build() .execute(HttpManager.put, callback); }
javascript
{ "resource": "" }
q25655
train
function(playlistId, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/playlists/' + playlistId + '/followers') .withHeaders({ 'Content-Type': 'application/json' }) .build() .execute(HttpManager.del, callback); }
javascript
{ "resource": "" }
q25656
train
function(playlistId, tracks, options, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/playlists/' + playlistId + '/tracks') .withHeaders({ 'Content-Type': 'application/json' }) .withQueryParameters(options) .withBodyParameters({ uris: tracks }) .build() .execute(HttpManager.post, callback); }
javascript
{ "resource": "" }
q25657
train
function( playlistId, positions, snapshotId, callback ) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/playlists/' + playlistId + '/tracks') .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters({ positions: positions, snapshot_id: snapshotId }) .build() .execute(HttpManager.del, callback); }
javascript
{ "resource": "" }
q25658
train
function( playlistId, rangeStart, insertBefore, options, callback ) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/playlists/' + playlistId + '/tracks') .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters( { range_start: rangeStart, insert_before: insertBefore }, options ) .build() .execute(HttpManager.put, callback); }
javascript
{ "resource": "" }
q25659
train
function(options, callback) { var _opts = {}; var optionsOfTypeArray = ['seed_artists', 'seed_genres', 'seed_tracks']; for (var option in options) { if (options.hasOwnProperty(option)) { if ( optionsOfTypeArray.indexOf(option) !== -1 && Object.prototype.toString.call(options[option]) === '[object Array]' ) { _opts[option] = options[option].join(','); } else { _opts[option] = options[option]; } } } return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/recommendations') .withQueryParameters(_opts) .build() .execute(HttpManager.get, callback); }
javascript
{ "resource": "" }
q25660
train
function(scopes, state, showDialog) { return AuthenticationRequest.builder() .withPath('/authorize') .withQueryParameters({ client_id: this.getClientId(), response_type: 'code', redirect_uri: this.getRedirectURI(), scope: scopes.join('%20'), state: state, show_dialog: showDialog && !!showDialog }) .build() .getURL(); }
javascript
{ "resource": "" }
q25661
train
function(trackIds, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/tracks') .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters({ ids: trackIds }) .build() .execute(HttpManager.del, callback); }
javascript
{ "resource": "" }
q25662
train
function(albumIds, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/albums') .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters(albumIds) .build() .execute(HttpManager.del, callback); }
javascript
{ "resource": "" }
q25663
train
function(options, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/player') .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters({ device_ids: options.deviceIds, play: !!options.play }) .build() .execute(HttpManager.put, callback); }
javascript
{ "resource": "" }
q25664
train
function(options, callback) { /*jshint camelcase: false */ var _options = options || {}; var queryParams = _options.device_id ? { device_id: _options.device_id } : null; var postData = {}; ['context_uri', 'uris', 'offset'].forEach(function(field) { if (field in _options) { postData[field] = _options[field]; } }); return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/player/play') .withQueryParameters(queryParams) .withHeaders({ 'Content-Type': 'application/json' }) .withBodyParameters(postData) .build() .execute(HttpManager.put, callback); }
javascript
{ "resource": "" }
q25665
train
function(options, callback) { return ( WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/player/pause') /*jshint camelcase: false */ .withQueryParameters( options && options.device_id ? { device_id: options.device_id } : null ) .withHeaders({ 'Content-Type': 'application/json' }) .build() .execute(HttpManager.put, callback) ); }
javascript
{ "resource": "" }
q25666
train
function(callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/player/previous') .withHeaders({ 'Content-Type': 'application/json' }) .build() .execute(HttpManager.post, callback); }
javascript
{ "resource": "" }
q25667
train
function(options, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/player/repeat') .withQueryParameters({ state: options.state || 'off' }) .build() .execute(HttpManager.put, callback); }
javascript
{ "resource": "" }
q25668
train
function(userIds, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/following') .withQueryParameters({ ids: userIds.join(','), type: 'user' }) .build() .execute(HttpManager.del, callback); }
javascript
{ "resource": "" }
q25669
train
function(options, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath('/v1/me/following') .withHeaders({ 'Content-Type': 'application/json' }) .withQueryParameters( { type: 'artist' }, options ) .build() .execute(HttpManager.get, callback); }
javascript
{ "resource": "" }
q25670
train
function(userId, playlistId, followerIds, callback) { return WebApiRequest.builder(this.getAccessToken()) .withPath( '/v1/users/' + encodeURIComponent(userId) + '/playlists/' + playlistId + '/followers/contains' ) .withQueryParameters({ ids: followerIds.join(',') }) .build() .execute(HttpManager.get, callback); }
javascript
{ "resource": "" }
q25671
isValidState
train
function isValidState(state, isBee) { const validStates = isBee ? BEE_STATES : BULL_STATES; return _.includes(validStates, state); }
javascript
{ "resource": "" }
q25672
_json
train
async function _json(req, res) { const { queueName, queueHost, state } = req.params; const {Queues} = req.app.locals; const queue = await Queues.get(queueName, queueHost); if (!queue) return res.status(404).json({ message: 'Queue not found' }); if (!isValidState(state, queue.IS_BEE)) return res.status(400).json({ message: `Invalid state requested: ${state}` }); let jobs; if (queue.IS_BEE) { jobs = await queue.getJobs(state, { size: 1000 }); jobs = jobs.map((j) => _.pick(j, 'id', 'progress', 'data', 'options', 'status')); } else { jobs = await queue[`get${_.capitalize(state)}`](0, 1000); jobs = jobs.map((j) => j.toJSON()); } const filename = `${queueName}-${state}-dump.json`; res.setHeader('Content-disposition', `attachment; filename=${filename}`); res.setHeader('Content-type', 'application/json'); res.write(JSON.stringify(jobs, null, 2), () => res.end()); }
javascript
{ "resource": "" }
q25673
_html
train
async function _html(req, res) { const { queueName, queueHost, state } = req.params; const {Queues} = req.app.locals; const queue = await Queues.get(queueName, queueHost); const basePath = req.baseUrl; if (!queue) return res.status(404).render('dashboard/templates/queueNotFound', {basePath, queueName, queueHost}); if (!isValidState(state, queue.IS_BEE)) return res.status(400).json({ message: `Invalid state requested: ${state}` }); let jobCounts; if (queue.IS_BEE) { jobCounts = await queue.checkHealth(); delete jobCounts.newestJob; } else { jobCounts = await queue.getJobCounts(); } const page = parseInt(req.query.page, 10) || 1; const pageSize = parseInt(req.query.pageSize, 10) || 100; const startId = (page - 1) * pageSize; const endId = startId + pageSize - 1; let jobs; if (queue.IS_BEE) { const page = {}; if (['failed', 'succeeded'].includes(state)) { page.size = pageSize; } else { page.start = startId; page.end = endId; } jobs = await queue.getJobs(state, page); // Filter out Bee jobs that have already been removed by the time the promise resolves jobs = jobs.filter((job) => job); } else { jobs = await queue[`get${_.capitalize(state)}`](startId, endId); } let pages = _.range(page - 6, page + 7) .filter((page) => page >= 1); while (pages.length < 12) { pages.push(_.last(pages) + 1); } pages = pages.filter((page) => page <= _.ceil(jobCounts[state] / pageSize)); return res.render('dashboard/templates/queueJobsByState', { basePath, queueName, queueHost, state, jobs, jobsInStateCount: jobCounts[state], disablePagination: queue.IS_BEE && (state === 'succeeded' || state === 'failed'), currentPage: page, pages, pageSize, lastPage: _.last(pages) }); }
javascript
{ "resource": "" }
q25674
toPersianNumber
train
function toPersianNumber(number) { // List of standard persian numbers from 0 to 9 const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']; return number .toString() .replace(/\d/g, x => persianDigits[x]); }
javascript
{ "resource": "" }
q25675
_subclassObject
train
function _subclassObject(tree, base, extension, extName) { // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName); for (var attrName in extension) { if (typeof extension[attrName] === "function") { if (typeof tree[attrName] === "function") { // override existing method tree[attrName] = _makeVirtualFunction( attrName, tree, base, extension, extName ); } else if (attrName.charAt(0) === "_") { // Create private methods in tree.ext.EXTENSION namespace tree.ext[extName][attrName] = _makeVirtualFunction( attrName, tree, base, extension, extName ); } else { $.error( "Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName ); } } else { // Create member variables in tree.ext.EXTENSION namespace if (attrName !== "options") { tree.ext[extName][attrName] = extension[attrName]; } } } }
javascript
{ "resource": "" }
q25676
train
function(node, mode) { var i, n; mode = mode || "child"; if (node === false) { for (i = this.children.length - 1; i >= 0; i--) { n = this.children[i]; if (n.statusNodeType === "paging") { this.removeChild(n); } } this.partload = false; return; } node = $.extend( { title: this.tree.options.strings.moreData, statusNodeType: "paging", icon: false, }, node ); this.partload = true; return this.addNode(node, mode); }
javascript
{ "resource": "" }
q25677
train
function(patch) { // patch [key, null] means 'remove' if (patch === null) { this.remove(); return _getResolvedPromise(this); } // TODO: make sure that root node is not collapsed or modified // copy (most) attributes to node.ATTR or node.data.ATTR var name, promise, v, IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global for (name in patch) { v = patch[name]; if (!IGNORE_MAP[name] && !$.isFunction(v)) { if (NODE_ATTR_MAP[name]) { this[name] = v; } else { this.data[name] = v; } } } // Remove and/or create children if (patch.hasOwnProperty("children")) { this.removeChildren(); if (patch.children) { // only if not null and not empty list // TODO: addChildren instead? this._setChildren(patch.children); } // TODO: how can we APPEND or INSERT child nodes? } if (this.isVisible()) { this.renderTitle(); this.renderStatus(); } // Expand collapse (final step, since this may be async) if (patch.hasOwnProperty("expanded")) { promise = this.setExpanded(patch.expanded); } else { promise = _getResolvedPromise(this); } return promise; }
javascript
{ "resource": "" }
q25678
train
function(deep) { var cl = this.children, i, l, n; if (!cl) { return 0; } n = cl.length; if (deep !== false) { for (i = 0, l = n; i < l; i++) { n += cl[i].countChildren(); } } return n; }
javascript
{ "resource": "" }
q25679
train
function() { if (this.lazy) { if (this.children == null) { // null or undefined: Not yet loaded return undefined; } else if (this.children.length === 0) { // Loaded, but response was empty return false; } else if ( this.children.length === 1 && this.children[0].isStatusNode() ) { // Currently loading or load error return undefined; } return true; } return !!(this.children && this.children.length); }
javascript
{ "resource": "" }
q25680
train
function(opts) { var i, that = this, deferreds = [], dfd = new $.Deferred(), parents = this.getParentList(false, false), len = parents.length, effects = !(opts && opts.noAnimation === true), scroll = !(opts && opts.scrollIntoView === false); // Expand bottom-up, so only the top node is animated for (i = len - 1; i >= 0; i--) { // that.debug("pushexpand" + parents[i]); deferreds.push(parents[i].setExpanded(true, opts)); } $.when.apply($, deferreds).done(function() { // All expands have finished // that.debug("expand DONE", scroll); if (scroll) { that.scrollIntoView(effects).done(function() { // that.debug("scroll DONE"); dfd.resolve(); }); } else { dfd.resolve(); } }); return dfd.promise(); }
javascript
{ "resource": "" }
q25681
_goto
train
function _goto(n) { if (n) { // setFocus/setActive will scroll later (if autoScroll is specified) try { n.makeVisible({ scrollIntoView: false }); } catch (e) {} // #272 // Node may still be hidden by a filter if (!$(n.span).is(":visible")) { n.debug("Navigate: skipping hidden node"); n.navigate(where, activate); return; } return activate === false ? n.setFocus() : n.setActive(); } }
javascript
{ "resource": "" }
q25682
train
function(cmp, deep) { var i, l, cl = this.children; if (!cl) { return; } cmp = cmp || function(a, b) { var x = a.title.toLowerCase(), y = b.title.toLowerCase(); return x === y ? 0 : x > y ? 1 : -1; }; cl.sort(cmp); if (deep) { for (i = 0, l = cl.length; i < l; i++) { if (cl[i].children) { cl[i].sortChildren(cmp, "$norender$"); } } } if (deep !== "$norender$") { this.render(); } this.triggerModifyChild("sort"); }
javascript
{ "resource": "" }
q25683
train
function(value, flag) { var className, hasClass, rnotwhite = /\S+/g, classNames = value.match(rnotwhite) || [], i = 0, wasAdded = false, statusElem = this[this.tree.statusClassPropName], curClasses = " " + (this.extraClasses || "") + " "; // this.info("toggleClass('" + value + "', " + flag + ")", curClasses); // Modify DOM element directly if it already exists if (statusElem) { $(statusElem).toggleClass(value, flag); } // Modify node.extraClasses to make this change persistent // Toggle if flag was not passed while ((className = classNames[i++])) { hasClass = curClasses.indexOf(" " + className + " ") >= 0; flag = flag === undefined ? !hasClass : !!flag; if (flag) { if (!hasClass) { curClasses += className + " "; wasAdded = true; } } else { while (curClasses.indexOf(" " + className + " ") > -1) { curClasses = curClasses.replace( " " + className + " ", " " ); } } } this.extraClasses = $.trim(curClasses); // this.info("-> toggleClass('" + value + "', " + flag + "): '" + this.extraClasses + "'"); return wasAdded; }
javascript
{ "resource": "" }
q25684
train
function(operation, childNode, extra) { var data, modifyChild = this.tree.options.modifyChild; if (modifyChild) { if (childNode && childNode.parent !== this) { $.error( "childNode " + childNode + " is not a child of " + this ); } data = { node: this, tree: this.tree, operation: operation, childNode: childNode || null, }; if (extra) { $.extend(data, extra); } modifyChild({ type: "modifyChild" }, data); } }
javascript
{ "resource": "" }
q25685
train
function(flag) { flag = flag !== false; // Confusing use of '!' /*jshint -W018 */ if (!!this._enableUpdate === !!flag) { return flag; } /*jshint +W018 */ this._enableUpdate = flag; if (flag) { this.debug("enableUpdate(true): redraw "); //, this._dirtyRoots); this.render(); } else { // this._dirtyRoots = null; this.debug("enableUpdate(false)..."); } return !flag; // return previous value }
javascript
{ "resource": "" }
q25686
train
function(match, startNode, visibleOnly) { match = typeof match === "string" ? _makeNodeTitleStartMatcher(match) : match; startNode = startNode || this.getFirstChild(); var stopNode = null, parentChildren = startNode.parent.children, matchingNode = null, walkVisible = function(parent, idx, fn) { var i, grandParent, parentChildren = parent.children, siblingCount = parentChildren.length, node = parentChildren[idx]; // visit node itself if (node && fn(node) === false) { return false; } // visit descendants if (node && node.children && node.expanded) { if (walkVisible(node, 0, fn) === false) { return false; } } // visit subsequent siblings for (i = idx + 1; i < siblingCount; i++) { if (walkVisible(parent, i, fn) === false) { return false; } } // visit parent's subsequent siblings grandParent = parent.parent; if (grandParent) { return walkVisible( grandParent, grandParent.children.indexOf(parent) + 1, fn ); } else { // wrap-around: restart with first node return walkVisible(parent, 0, fn); } }; walkVisible( startNode.parent, parentChildren.indexOf(startNode), function(node) { // Stop iteration if we see the start node a second time if (node === stopNode) { return false; } stopNode = stopNode || node; // Ignore nodes hidden by a filter if (!$(node.span).is(":visible")) { node.debug("quicksearch: skipping hidden node"); return; } // Test if we found a match, but search for a second match if this // was the currently active node if (match(node)) { // node.debug("quicksearch match " + node.title, startNode); matchingNode = node; if (matchingNode !== startNode) { return false; } } } ); return matchingNode; }
javascript
{ "resource": "" }
q25687
train
function(key, searchRoot) { // Search the DOM by element ID (assuming this is faster than traversing all nodes). var el, match; // TODO: use tree.keyMap if available // TODO: check opts.generateIds === true if (!searchRoot) { el = document.getElementById(this.options.idPrefix + key); if (el) { return el.ftnode ? el.ftnode : null; } } // Not found in the DOM, but still may be in an unrendered part of tree searchRoot = searchRoot || this.rootNode; match = null; searchRoot.visit(function(node) { if (node.key === key) { match = node; return false; // Stop iteration } }, true); return match; }
javascript
{ "resource": "" }
q25688
train
function(ctx, callOpts) { // TODO: return promise? var ac, i, l, node = ctx.node; if (node.parent) { ac = node.parent.children; for (i = 0, l = ac.length; i < l; i++) { if (ac[i] !== node && ac[i].expanded) { this._callHook( "nodeSetExpanded", ac[i], false, callOpts ); } } } }
javascript
{ "resource": "" }
q25689
train
function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if (node.li) { $(node.li).remove(); node.li = null; } this.nodeRemoveChildMarkup(ctx); }
javascript
{ "resource": "" }
q25690
train
function(ctx, flag) { // ctx.node.debug("nodeSetFocus(" + flag + ")"); var ctx2, tree = ctx.tree, node = ctx.node, opts = tree.options, // et = ctx.originalEvent && ctx.originalEvent.type, isInput = ctx.originalEvent ? $(ctx.originalEvent.target).is(":input") : false; flag = flag !== false; // (node || tree).debug("nodeSetFocus(" + flag + "), event: " + et + ", isInput: "+ isInput); // Blur previous node if any if (tree.focusNode) { if (tree.focusNode === node && flag) { // node.debug("nodeSetFocus(" + flag + "): nothing to do"); return; } ctx2 = $.extend({}, ctx, { node: tree.focusNode }); tree.focusNode = null; this._triggerNodeEvent("blur", ctx2); this._callHook("nodeRenderStatus", ctx2); } // Set focus to container and node if (flag) { if (!this.hasFocus()) { node.debug("nodeSetFocus: forcing container focus"); this._callHook("treeSetFocus", ctx, true, { calledByNode: true, }); } node.makeVisible({ scrollIntoView: false }); tree.focusNode = node; if (opts.titlesTabbable) { if (!isInput) { // #621 $(node.span) .find(".fancytree-title") .focus(); } } else { // We cannot set KB focus to a node, so use the tree container // #563, #570: IE scrolls on every call to .focus(), if the container // is partially outside the viewport. So do it only, when absolutely // neccessary: if ( $(document.activeElement).closest( ".fancytree-container" ).length === 0 ) { $(tree.$container).focus(); } } if (opts.aria) { // Set active descendant to node's span ID (create one, if needed) $(tree.$container).attr( "aria-activedescendant", $(node.tr || node.li) .uniqueId() .attr("id") ); // "ftal_" + opts.idPrefix + node.key); } // $(node.span).find(".fancytree-title").focus(); this._triggerNodeEvent("focus", ctx); // if( opts.autoActivate ){ // tree.nodeSetActive(ctx, true); // } if (opts.autoScroll) { node.scrollIntoView(); } this._callHook("nodeRenderStatus", ctx); } }
javascript
{ "resource": "" }
q25691
train
function(ctx) { var tree = ctx.tree; tree.activeNode = null; tree.focusNode = null; tree.$div.find(">ul.fancytree-container").empty(); // TODO: call destructors and remove reference loops tree.rootNode.children = null; }
javascript
{ "resource": "" }
q25692
train
function(el) { var widget; if (el instanceof Fancytree) { return el; // el already was a Fancytree } if (el === undefined) { el = 0; // get first tree } if (typeof el === "number") { el = $(".fancytree-container").eq(el); // el was an integer: return nth instance } else if (typeof el === "string") { el = $(el).eq(0); // el was a selector: use first match } else if (el instanceof $) { el = el.eq(0); // el was a jQuery object: use the first DOM element } else if (el.originalEvent !== undefined) { el = $(el.target); // el was an Event } el = el.closest(":ui-fancytree"); widget = el.data("ui-fancytree") || el.data("fancytree"); // the latter is required by jQuery <= 1.8 return widget ? widget.tree : null; }
javascript
{ "resource": "" }
q25693
train
function( optionName, node, nodeObject, treeOptions, defaultValue ) { var ctx, res, tree = node.tree, treeOpt = treeOptions[optionName], nodeOpt = nodeObject[optionName]; if ($.isFunction(treeOpt)) { ctx = { node: node, tree: tree, widget: tree.widget, options: tree.widget.options, typeInfo: tree.types[node.type] || {}, }; res = treeOpt.call(tree, { type: optionName }, ctx); if (res == null) { res = nodeOpt; } } else { res = nodeOpt != null ? nodeOpt : treeOpt; } if (res == null) { res = defaultValue; // no option set at all: return default } return res; }
javascript
{ "resource": "" }
q25694
train
function(span, baseClass, icon) { var $span = $(span); if (typeof icon === "string") { $span.attr("class", baseClass + " " + icon); } else { // support object syntax: { text: ligature, addClasse: classname } if (icon.text) { $span.text("" + icon.text); } else if (icon.html) { span.innerHTML = icon.html; } $span.attr( "class", baseClass + " " + (icon.addClass || "") ); } }
javascript
{ "resource": "" }
q25695
train
function(event) { // Poor-man's hotkeys. See here for a complete implementation: // https://github.com/jeresig/jquery.hotkeys var which = event.which, et = event.type, s = []; if (event.altKey) { s.push("alt"); } if (event.ctrlKey) { s.push("ctrl"); } if (event.metaKey) { s.push("meta"); } if (event.shiftKey) { s.push("shift"); } if (et === "click" || et === "dblclick") { s.push(MOUSE_BUTTONS[event.button] + et); } else { if (!IGNORE_KEYCODES[which]) { s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() ); } } return s.join("+"); }
javascript
{ "resource": "" }
q25696
train
function(instance, methodName, handler, context) { var prevSuper, _super = instance[methodName] || $.noop; instance[methodName] = function() { var self = context || this; try { prevSuper = self._super; self._super = _super; return handler.apply(self, arguments); } finally { self._super = prevSuper; } }; }
javascript
{ "resource": "" }
q25697
train
function(definition) { _assert( definition.name != null, "extensions must have a `name` property." ); _assert( definition.version != null, "extensions must have a `version` property." ); $.ui.fancytree._extensions[definition.name] = definition; }
javascript
{ "resource": "" }
q25698
train
function() { var level = 0; var levels = [0,0,0,0,0,0,0]; var hLevelText = ''; var prependText = ''; var prevLevel = 0; var n = 0; self.children('*:header:visible').each(function(index, heading) { log('Processing heading %o', heading); level = parseInt(heading.tagName.substring(1)); if (config.min_level <= level && level <= config.max_level) { n++; levels[level]++; for (var l = 1; l <= level; l++) { hLevelText += levels[l] > 0 ? levels[l] + config.number_separator : ''; } levels[level + 1] = 0; hLevelText = hLevelText.substring(0, hLevelText.length - 1); prependText = hLevelText; if (config.generate_toc || config.add_anchors) { if (config.generate_toc) { var link = '<a href="#h' + hLevelText + '">' +jQuery('<span/>').text(jQuery(this).text()).html() + '</a>'; var elem = "\n"+'<li>' + hLevelText + (config.number_suffix ? config.number_suffix : '') + ' ' + link; if (level < prevLevel) { log(hLevelText + ', unnesting because:' + level + '<' + prevLevel); var unnest = ''; while (level < prevLevel) { unnest += '</ul>'; prevLevel--; } toc += unnest + elem + '</li>'; } else if (level > prevLevel) { log(hLevelText + ', nesting because:' + level + '>' + prevLevel); toc += '<ul>' + elem; } else { log(hLevelText + ', same level (' + level + ')'); toc += elem; } } prependText = '<span id="h' + hLevelText + '"></span>' + hLevelText; } if (config.number_suffix) { prependText += config.number_suffix; } jQuery(this).prepend(prependText + ' '); prependText = hLevelText = ''; prevLevel = level; } }); if (config.generate_toc) { if (config.toc_title) { toc = '<h4>' + config.toc_title + '</h4>' + toc; } if (n == 0) { toc += config.toc_none ? '<p>' + config.toc_none + '</p>' : ''; } jQuery(config.toc_elem ? config.toc_elem : 'body').append(toc); } processed = true; }
javascript
{ "resource": "" }
q25699
train
function() { if (!config.debug) { return; } try { console.log.apply(console, arguments); } catch(e) { try { opera.postError.apply(opera, arguments); } catch(e){} } }
javascript
{ "resource": "" }