Cribbed from Leaflet https://github.com/Leaflet/Leaflet/blob/master/spec/suites/layer/tile/TileLayerSpec.js#L302-L309
551754
function eachImg(layer, callback) {
      var imgtags = layer._container.children[0].children;
      for (var i in imgtags) {
        if (imgtags[i].tagName === 'IMG') {
          callback(imgtags[i]);
        }
      }
    }
1100117
function() {
        if (!this._tileOrigin) {
            var extent = this.getMaxExtent();
            this._tileOrigin = new OpenLayers.LonLat(extent.left, extent.bottom);
        }
        return this._tileOrigin;
    }
4090
public Envelope tileBboxLngLat(int tx, int ty, int zoomLevel) {
        Coordinate topLeft = metersToLngLat(tileTopLeft(tx, ty, zoomLevel));
        Coordinate lowerRight = metersToLngLat(tileTopLeft(tx + 1, ty + 1, zoomLevel));
        Envelope result = new Envelope(topLeft, lowerRight);
        return result;
    }
773420
private static double deltaLat(double deltaPixel, double lat, byte zoom, int tileSize) {
        long mapSize = MercatorProjection.getMapSize(zoom, tileSize);
        double pixelY = MercatorProjection.latitudeToPixelY(lat, mapSize);
        double lat2 = MercatorProjection.pixelYToLatitude(pixelY + deltaPixel, mapSize);

        return Math.abs(lat2 - lat);
    }
117672
function getTileSpans(tileElements) {
      return [].map.call(tileElements, function(ele) {
        var ctrl = angular.element(ele).controller('mdGridTile');
        return {
          row: parseInt(
              $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-rowspan'), 10) || 1,
          col: parseInt(
              $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-colspan'), 10) || 1
        };
      });
    }
1112707
def _tiles_from_bbox(bbox, zoom_level):
        

        if isinstance(bbox, dict):
            point_min = Point.from_latitude_longitude(latitude=bbox['tl'], longitude=bbox['tr'])
            point_max = Point.from_latitude_longitude(latitude=bbox['bl'], longitude=bbox['br'])
        elif isinstance(bbox, list):
            point_min = Point.from_latitude_longitude(latitude=bbox[1], longitude=bbox[0])
            point_max = Point.from_latitude_longitude(latitude=bbox[3], longitude=bbox[2])
        else:
            raise RuntimeError("bbox must bei either a dict or a list")
        tile_min = Tile.for_point(point_min, zoom_level)
        tile_max = Tile.for_point(point_max, zoom_level)
        tiles = []
        for x in range(tile_min.tms_x, tile_max.tms_x + 1):
            for y in range(tile_min.tms_y, tile_max.tms_y + 1):
                tiles.append(Tile.from_tms(tms_x=x, tms_y=y, zoom=zoom_level))
        return tiles
868625
function doTidyUp(l) {
    var d = parseInt(Date.now()/1000);
    for (var m in markers) {
        if ((l && (l == markers[m].lay)) || typeof markers[m].ts != "undefined") {
            if ((l && (l == markers[m].lay)) || (markers[m].hasOwnProperty("ts") && (Number(markers[m].ts) < d) && (markers[m].lay !== "_drawing"))) {
                //console.log("STALE :",m);
                layers[markers[m].lay].removeLayer(markers[m]);
                if (typeof polygons[m] != "undefined") {
                    layers[markers[m].lay].removeLayer(polygons[m]);
                    delete polygons[m];
                }
                if (typeof polygons[m+"_"] != "undefined") {
                    layers[polygons[m+"_"].lay].removeLayer(polygons[m+"_"]);
                    delete polygons[m+"_"];
                }
                delete markers[m];
            }
        }
    }
    if (l) {
        if (layers[l]) { map.removeLayer(layers[l]); layercontrol.removeLayer(layers[l]); delete layers[l]; }
        if (overlays[l]) { map.removeLayer(overlays[l]); layercontrol.removeLayer(overlays[l]); delete overlays[l]; }
    }
}
87547
function getParent(tile) {
    // top left
    if (tile[0] % 2 === 0 && tile[1] % 2 === 0) {
        return [tile[0] / 2, tile[1] / 2, tile[2] - 1];
    }
    // bottom left
    if ((tile[0] % 2 === 0) && (!tile[1] % 2 === 0)) {
        return [tile[0] / 2, (tile[1] - 1) / 2, tile[2] - 1];
    }
    // top right
    if ((!tile[0] % 2 === 0) && (tile[1] % 2 === 0)) {
        return [(tile[0] - 1) / 2, (tile[1]) / 2, tile[2] - 1];
    }
    // bottom right
    return [(tile[0] - 1) / 2, (tile[1] - 1) / 2, tile[2] - 1];
}
646647
function() {
        var backBuffer;
        if(this.grid.length > 0) {
            backBuffer = document.createElement('div');
            backBuffer.id = this.div.id + '_bb';
            backBuffer.className = 'olBackBuffer';
            backBuffer.style.position = 'absolute';
            var map = this.map;
            backBuffer.style.zIndex = this.transitionEffect === 'resize' ?
                    this.getZIndex() - 1 :
                    // 'map-resize':
                    map.Z_INDEX_BASE.BaseLayer -
                            (map.getNumLayers() - map.getLayerIndex(this));
            for(var i=0, lenI=this.grid.length; i<lenI; i++) {
                for(var j=0, lenJ=this.grid[i].length; j<lenJ; j++) {
                    var tile = this.grid[i][j],
                        markup = this.grid[i][j].createBackBuffer();
                    if (markup) {
                        markup._i = i;
                        markup._j = j;
                        markup._w = tile.size.w;
                        markup._h = tile.size.h;
                        markup.id = tile.id + '_bb';
                        backBuffer.appendChild(markup);
                    }
                }
            }
        }
        return backBuffer;
    }
1320436
function tileToPixelCoords(x, y, v) {
         var ret = v || new me.Vector2d();
         return ret.set((x - y) * this.hTilewidth + this.originX, (x + y) * this.hTileheight);
       }
589830
function (map) {
        this._map = map;
        this._canvas = L.DomUtil.create('canvas', 'leaflet-layer');
        this.tiles = {};

        var size = this._map.getSize();
        this._canvas.width = size.x;
        this._canvas.height = size.y;

        var animated = this._map.options.zoomAnimation && L.Browser.any3d;
        L.DomUtil.addClass(this._canvas, 'leaflet-zoom-' + (animated ? 'animated' : 'hide'));


        map._panes.overlayPane.appendChild(this._canvas);

        map.on(this.getEvents(), this);

        var del = this._delegate || this;
        del.onLayerDidMount && del.onLayerDidMount(); // -- callback

        this.needRedraw();
    }
1135688
function (layer) {
            var bounds = layer instanceof me.TMXLayer ? me.pool.pull("me.Rect", 0, 0, 0, 0) : this.bounds;
            bounds.setShape(
                0, 0,
                this.cols * this.tilewidth,
                this.rows * this.tileheight
            );
            return bounds;
        }
107942
function (bounds) {
        bounds = this.adjustBounds(bounds);
        var res = this.getServerResolution();
        var x = Math.round((bounds.left - this.tileOrigin.lon) / (res * this.tileSize.w));
        var y = Math.round((bounds.bottom - this.tileOrigin.lat) / (res * this.tileSize.h));
        var z = this.getServerZoom();
        var path = this.serviceVersion + "/" + this.layername + "/" + z + "/" + x + "/" + y + "." + this.type; 
        var url = this.url;
        if (OpenLayers.Util.isArray(url)) {
            url = this.selectUrl(path, url);
        }
        return url + path;
    }
191840
function (center) {
		var map = this._map;
		if (!map) { return; }
		var zoom = map.getZoom();

		if (center === undefined) { center = map.getCenter(); }
		if (this._tileZoom === undefined) { return; }	// if out of minzoom/maxzoom

		var pixelBounds = this._getTiledPixelBounds(center),
		    tileRange = this._pxBoundsToTileRange(pixelBounds),
		    tileCenter = tileRange.getCenter(),
		    queue = [],
		    margin = this.options.keepBuffer,
		    noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
		                              tileRange.getTopRight().add([margin, -margin]));

		for (var key in this._tiles) {
			var c = this._tiles[key].coords;
			if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) {
				this._tiles[key].current = false;
			}
		}

		// _update just loads more tiles. If the tile zoom level differs too much
		// from the map's, let _setView reset levels and prune old tiles.
		if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }

		// create a queue of coordinates to load tiles from
		for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
			for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
				var coords = new L.Point(i, j);
				coords.z = this._tileZoom;

				if (!this._isValidTile(coords)) { continue; }

				var tile = this._tiles[this._tileCoordsToKey(coords)];
				if (tile) {
					tile.current = true;
				} else {
					queue.push(coords);
				}
			}
		}

		// sort tile queue to load tiles in order of their distance to center
		queue.sort(function (a, b) {
			return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
		});

		if (queue.length !== 0) {
			// if its the first batch of tiles to load
			if (!this._loading) {
				this._loading = true;
				// @event loading: Event
				// Fired when the grid layer starts loading tiles.
				this.fire('loading');
			}

			// create DOM fragment to append tiles in one batch
			var fragment = document.createDocumentFragment();

			for (i = 0; i < queue.length; i++) {
				this._addTile(queue[i], fragment);
			}

			this._level.el.appendChild(fragment);
		}
	}
614085
function CartoDBSubLayer(layer, position) {
  SubLayerBase.call(this, layer, position);
  this._bindInteraction();

  var layer = this._parent.getLayer(this._position);
  // TODO: Test this
  if (Backbone.Model && layer) {
    this.infowindow = new Backbone.Model(layer.infowindow);
    this.infowindow.bind('change', function() {
      layer.infowindow = this.infowindow.toJSON();
      this._parent.setLayer(this._position, layer);
    }, this);
  }
}
471555
function generateLayers () {
			grunt.log.write("Generating layers...");

			var config = lang.extend({}, requireConfig, {
				isPrepareStage: true,
				optimize: "none",
				optimizeCss: "none",
				appDir: buildDir,
				dir: tempDir,
				baseUrl: "./",
				logLevel: 2, // WARN
				removeCombined: false,
				skipDirOptimize: true,
				keepBuildDir: false,
				skipSemiColonInsertion: true,
				pragmas: {
					prepare: true,
					build: true
				},
				// Pragmas for rjs plugins:
				pragmasOnSave: {
					prepareSave: true
				},
				// main (root) modules:
				modules: modules.map(function (module) { return { name: module }; }),
				onBuildWrite: function (moduleName, modulePath, contents) {
					// put moduleName into some layer basing on its path
					layers.some(function (layer) {
						var relPath = path.relative(path.resolve(config.dir), modulePath);
						var layerDir = layer.dir;
						if (!Array.isArray(layerDir)) {
							layerDir = [layerDir];
						}
						layerDir.forEach(function(dir) {
							if (relPath.indexOf(dir) === 0) {
								if (options.ignoreModules) {
									if (options.ignoreModules.some(function (m) {
										return m === moduleName;
									})) {
										return;
									}
								}
								layer.modules[moduleName] = true;
							}
						});
					});
					if (moduleName.indexOf('xhtmpl!') === 0) {
						modulesToDelete.push(path.join(outputDir, modulePath.slice('xhtmpl!'.length)));

						// Manually save pre-compiled template back into buildDir as
						// we're currently saving into tempDir (that's why we can't rely on returning content)

						// NOTE: manually remove leading semicolon
						// TODO: the code should be removed after migrating on 2.1.9 (with skipSemiColonInsertion support)
						if (contents.charAt(contents.length-1) === ";") {
							contents = contents.slice(0, contents.length-1);
						}
						file.saveFile(path.join(buildDir, modulePath.slice('xhtmpl!'.length)), contents);
					}
					//return contents;
					return "// this is a stub for finding layer's dependencies: moduleName=" + moduleName;
				}
			});

			requirejs.optimize(
				config,
				lang.safeCallback(function () {
					// create layer modules using 'layers' structure created in onBuildWrite:
					// every 'layer module' is an empty RJS module with imports (via define([..])) of all modules inside this layer
					layers.forEach(function (layer) {
						var modules = Object.keys(layer.modules).sort(),
							content = "define([\n\t\"" + modules.join("\",\n\t\"") + "\"\n], function () {});";
						file.saveFile(path.join(buildDir, layer.name) + ".js", content);
					});

					grunt.log.writeln('OK'.green);

					// Go to next step
					optimizeModules();
				}),
				lang.errorCallback
			);
		}
482625
function createMap(divId) {
  const source = new OSM();
  const layer = new TileLayer({
    source: source
  });
  const map = new Map({
    layers: [layer],
    target: divId,
    view: new View({
      center: [0, 0],
      zoom: 2
    })
  });
  const zoomslider = new ZoomSlider();
  map.addControl(zoomslider);
  return map;
}