Write a file for each tile
766316
def write_grid_local(tiles, params):
  
  # TODO: this isn't being used right now, will need to be
  # ported to gfile if we want to keep it
  for ti,tj,tile in enumerate_tiles(tiles):
    filename = "{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}".format(ti=ti, tj=tj, **params) #directory=directory, name=name, n_layer=n_layer, n_tile=n_tile, 
    # write out the tile as a npz
    print("saving", filename + ".npz")
    np.savez_compressed(filename + ".npz", **tile)
    # write out the tile as a csv
    print("saving", filename + ".csv")
    df = pd.DataFrame(tile)
    df.to_csv(filename + ".csv", index=False)
832738
def _write(self, session, openFile, maskMap):
        
        # Magic numbers
        FIRST_VALUE_INDEX = 12

        # Write the header
        openFile.write('DATASET\r\n')

        if self.type == self.SCALAR_TYPE:
            openFile.write('OBJTYPE {0}\r\n'.format(self.objectType))
            openFile.write('BEGSCL\r\n')

        elif self.type == self.VECTOR_TYPE:
            openFile.write('VECTYPE {0}\r\n'.format(self.vectorType))
            openFile.write('BEGVEC\r\n')

        openFile.write('OBJID {0}\r\n'.format(self.objectID))
        openFile.write('ND {0}\r\n'.format(self.numberData))
        openFile.write('NC {0}\r\n'.format(self.numberCells))
        openFile.write('NAME {0}\r\n'.format(self.name))

        # Retrieve the mask map to use as the status rasters
        statusString = ''
        if isinstance(maskMap, RasterMapFile):
            # Convert Mask Map to GRASS ASCII Raster
            statusGrassRasterString = maskMap.getAsGrassAsciiGrid(session)

            if statusGrassRasterString is not None:
                # Split by lines
                statusValues = statusGrassRasterString.split()
            else:
                statusValues = maskMap.rasterText.split()

            # Assemble into a string in the WMS Dataset format
            for i in range(FIRST_VALUE_INDEX, len(statusValues)):
                statusString += statusValues[i] + '\r\n'

        # Write time steps
        for timeStepRaster in self.rasters:
            # Write time step header
            openFile.write('TS {0} {1}\r\n'.format(timeStepRaster.iStatus, timeStepRaster.timestamp))

            # Write status raster (mask map) if applicable
            if timeStepRaster.iStatus == 1:
                openFile.write(statusString)

            # Write value raster
            valueString = timeStepRaster.getAsWmsDatasetString(session)

            if valueString is not None:
                openFile.write(valueString)

            else:
                openFile.write(timeStepRaster.rasterText)

        # Write ending tag for the dataset
        openFile.write('ENDDS\r\n')
865053
function createTile(coords, done) {
    let key = this._tileCoordsToKey(coords);
    
    let tileContainer = L.DomUtil.create("div");
    tileContainer.dataset.pending = this._imagesPerTile;
    
    for ( let i = 0; i < this._imagesPerTile; i++ ) {
      let key2 = key + "/" + i;
      if ( key2 in this._freshTiles ) {
        tileContainer.appendChild(this._freshTiles[ key2 ].pop());
        if ( !this._freshTiles[ key2 ].length ) {
          delete this._freshTiles[ key2 ];
        }
        tileContainer.dataset.pending--;
        // 				console.log('Got ', key2, ' from _freshTiles');
      } else {
        this._tileCallbacks[ key2 ] = this._tileCallbacks[ key2 ] || [];
        this._tileCallbacks[ key2 ].push(
          (function(c /* , k2*/) {
            return function(imgNode) {
              let parent = imgNode.parentNode;
              if ( parent ) {
                parent.removeChild(imgNode);
                parent.removeChild = L.Util.falseFn;
                // 							imgNode.parentNode.replaceChild(L.DomUtil.create('img'), imgNode);
              }
              c.appendChild(imgNode);
              c.dataset.pending--;
              if ( !parseInt(c.dataset.pending) ) {
                done();
              }
              // 						console.log('Sent ', k2, ' to _tileCallbacks, still ', c.dataset.pending, ' images to go');
            };
          })(tileContainer /* , key2*/)
        );
      }
    }
    
    if ( !parseInt(tileContainer.dataset.pending) ) {
      L.Util.requestAnimFrame(done);
    }
    return tileContainer;
  }
325144
def get_columns_rows(filenames):
    """"""
    tiles = []
    for filename in filenames:
        row, column = os.path.splitext(filename)[0][-5:].split('_')
        tiles.append((int(row), int(column)))
    rows = [pos[0] for pos in tiles]; columns = [pos[1] for pos in tiles]
    num_rows = max(rows); num_columns = max(columns)
    return (num_columns, num_rows)
1305186
function write_sty_bin(wb, opts) {
	var ba = buf_array();
	write_record(ba, "BrtBeginStyleSheet");
	write_FMTS_bin(ba, wb.SSF);
	write_FONTS_bin(ba, wb);
	write_FILLS_bin(ba, wb);
	write_BORDERS_bin(ba, wb);
	write_CELLSTYLEXFS_bin(ba, wb);
	write_CELLXFS_bin(ba, opts.cellXfs);
	write_STYLES_bin(ba, wb);
	write_DXFS_bin(ba, wb);
	write_TABLESTYLES_bin(ba, wb);
	write_COLORPALETTE_bin(ba, wb);
	/* FRTSTYLESHEET*/
	write_record(ba, "BrtEndStyleSheet");
	return ba.end();
}
1044863
private static TileDirectory buildTileDirectory(File directory) {

		TileDirectory tileDirectory = new TileDirectory();
		tileDirectory.directory = directory;

		// Search for zoom level directories
		for (File zoomDirectory : directory.listFiles()) {
			if (zoomDirectory.isDirectory()) {
				try {
					Integer zoomLevel = Integer
							.valueOf(zoomDirectory.getName());
					ZoomDirectory zoom = tileDirectory.new ZoomDirectory();
					zoom.directory = new File(tileDirectory.directory,
							zoomDirectory.getName());
					zoom.zoom = zoomLevel;
					tileDirectory.zooms.put(zoomLevel, zoom);
					tileDirectory.minZoom = Math.min(tileDirectory.minZoom,
							zoomLevel);
					tileDirectory.maxZoom = Math.max(tileDirectory.maxZoom,
							zoomLevel);

					// Search for x level directories
					for (File xDirectory : zoomDirectory.listFiles()) {
						if (xDirectory.isDirectory()) {
							try {
								Integer xValue = Integer.valueOf(xDirectory
										.getName());
								XDirectory x = tileDirectory.new XDirectory();
								x.directory = new File(zoom.directory,
										xDirectory.getName());
								x.x = xValue;
								zoom.xValues.put(xValue, x);
								zoom.minX = Math.min(zoom.minX, xValue);
								zoom.maxX = Math.max(zoom.maxX, xValue);

								// Search for y level directories
								for (File yImage : xDirectory.listFiles()) {
									if (yImage.isFile()) {
										try {
											String yImageName = yImage
													.getName();
											int extensionLocation = yImageName
													.lastIndexOf(".");
											if (extensionLocation >= 0) {
												yImageName = yImageName
														.substring(0,
																extensionLocation);
											}
											YFile y = tileDirectory.new YFile();
											y.y = Integer.valueOf(yImageName);
											y.file = new File(x.directory,
													yImage.getName());

											x.yValues.put(y.y, y);
											x.minY = Math.min(x.minY, y.y);
											x.maxY = Math.max(x.maxY, y.y);
										} catch (NumberFormatException e) {
											LOGGER.log(
													Level.INFO,
													"Skipping file: "
															+ yImage.getAbsolutePath());
										}

									} else {
										LOGGER.log(
												Level.INFO,
												"Skipping directory: "
														+ yImage.getAbsolutePath());
									}
								}

								zoom.minY = Math.min(zoom.minY, x.minY);
								zoom.maxY = Math.max(zoom.maxY, x.maxY);

							} catch (NumberFormatException e) {
								LOGGER.log(Level.INFO, "Skipping directory: "
										+ xDirectory.getAbsolutePath());
							}
						} else {
							LOGGER.log(Level.INFO, "Skipping file: "
									+ xDirectory.getAbsolutePath());
						}
					}
				} catch (NumberFormatException e) {
					LOGGER.log(Level.INFO, "Skipping directory: "
							+ zoomDirectory.getAbsolutePath());
				}
			} else {
				LOGGER.log(Level.INFO,
						"Skipping file: " + zoomDirectory.getAbsolutePath());
			}
		}

		return tileDirectory;
	}
43794
def render_tile(cells, ti, tj, render, params, metadata, layout, summary):
  
  image_size = params["cell_size"] * params["n_tile"]
  tile = Image.new("RGB", (image_size, image_size), (255,255,255))
  keys = cells.keys()
  for i,key in enumerate(keys):
    print("cell", i+1, "/", len(keys), end='\r')
    cell_image = render(cells[key], params, metadata, layout, summary)
    # stitch this rendering into the tile image
    ci = key[0] % params["n_tile"]
    cj = key[1] % params["n_tile"]
    xmin = ci*params["cell_size"]
    ymin = cj*params["cell_size"]
    xmax = (ci+1)*params["cell_size"]
    ymax = (cj+1)*params["cell_size"]

    if params.get("scale_density", False):
      density = len(cells[key]["gi"])
      # scale = density/summary["max_density"]
      scale = math.log(density)/(math.log(summary["max_density"]) or 1)
      owidth = xmax - xmin
      width = int(round(owidth * scale))
      if(width < 1):
        width = 1
      offsetL = int(round((owidth - width)/2))
      offsetR = owidth - width - offsetL # handle odd numbers
      # print("\n")
      # print("width", width, offsetL, offsetR)
      box = [xmin + offsetL, ymin + offsetL, xmax - offsetR, ymax - offsetR]
      resample = params.get("scale_type", Image.NEAREST)
      cell_image = cell_image.resize(size=(width,width), resample=resample)
      # print(cell_image)
    else:
      box = [xmin, ymin, xmax, ymax]

    # print("box", box)
    tile.paste(cell_image, box)
  print("\n")
  return tile
760093
def tb_h_file_creation(target, source, env):
    """"""

    files = [str(x) for x in source]

    try:
        desc = TBDescriptor(files)
    except pyparsing.ParseException as e:
        raise BuildError("Could not parse tilebus file", parsing_exception=e)

    block = desc.get_block(config_only=True)
    block.render_template(block.CommandHeaderTemplate, out_path=str(target[0]))
    block.render_template(block.ConfigHeaderTemplate, out_path=str(target[1]))
632613
def main():

    

    arguments = docopt(__doc__, version='tileinfo 0.1')

    src_name = arguments['SOURCE']
    src_format = arguments['--srcformat']
    indent = arguments['--indent']
    if isinstance(indent, str) and indent.lower() == 'none':
        indent = None
    elif isinstance(indent, str):
        indent = int(indent)
    else:
        indent = 4

    with sys.stdin if src_name in ('-', None) else open(src_name, 'rb') as f:

        # Guess input format if not given
        if src_format is None:
            if '.json' == f.name[-5:]:
                src_format = 'json'
            else:
                src_format = 'tile'

        if src_format == 'tile':
            header, data = Tile(f.read()).unpack()
        else:
            header = json.loads(f.read())
            data = header.pop('data')

        # Generate the info report
        report = info(data, header['cols'])

        # Merge report with other tile attributes
        out = {k: v for k, v in header.items() if k != 'data'}
        out['data'] = {}
        for field, vals in report.items():
            out['data'][field + '_min'] = vals['min']
            out['data'][field + '_max'] = vals['max']

        print(json.dumps(out, indent=indent, sort_keys=True))
437298
def write_file(writer, filename):
  """"""
  for line in txt_line_iterator(filename):
    writer.write(line)
    writer.write("\n")
373140
def get_tiles(self):
        """"""
        for x, y in griditer(self.root_tile.x, self.root_tile.y, ncol=self.tiles_per_row):
            yield TileCoordinate(self.root_tile.zoom, x, y)
192707
def write_files(template, destination='./dxf'):
    
    os.makedirs(destination)
    for key, value in template.items():
        with open(os.path.join(destination, key), 'w') as f:
            f.write(replace_whitespace(value, insert=False))
979603
private void writeConfToFile(File dir, Map<PropertyKey, String> properties) throws IOException {
    // Generates the full set of properties to write
    Map<PropertyKey, String> map = new HashMap<>(mProperties);
    for (Map.Entry<PropertyKey, String> entry : properties.entrySet()) {
      map.put(entry.getKey(), entry.getValue());
    }

    StringBuilder sb = new StringBuilder();
    for (Entry<PropertyKey, String> entry : map.entrySet()) {
      sb.append(String.format("%s=%s%n", entry.getKey(), entry.getValue()));
    }

    dir.mkdirs();
    try (FileOutputStream fos
        = new FileOutputStream(new File(dir, "alluxio-site.properties"))) {
      fos.write(sb.toString().getBytes(Charsets.UTF_8));
    }
  }
260537
def draw_tiling(coord_generator, filename):
    """"""
    im = Image.new('L', size=(CANVAS_WIDTH, CANVAS_HEIGHT))
    for shape in coord_generator(CANVAS_WIDTH, CANVAS_HEIGHT):
        ImageDraw.Draw(im).polygon(shape, outline='white')
    im.save(filename)
1247036
function createTile(coords, done) {
    let key = this._tileCoordsToKey(coords);
    // console.log('Need:', key);
    
    if ( key in this._freshTiles ) {
      let tile = this._freshTiles[ key ].pop();
      if ( !this._freshTiles[ key ].length ) {
        delete this._freshTiles[ key ];
      }
      L.Util.requestAnimFrame(done);
      // 			console.log('Got ', key, ' from _freshTiles');
      return tile;
    }
    let tileContainer = L.DomUtil.create("div");
    this._tileCallbacks[ key ] = this._tileCallbacks[ key ] || [];
    this._tileCallbacks[ key ].push(
      (function(c /* , k*/) {
        return function(imgNode) {
          let parent = imgNode.parentNode;
          if ( parent ) {
            parent.removeChild(imgNode);
            parent.removeChild = L.Util.falseFn;
            // 						imgNode.parentNode.replaceChild(L.DomUtil.create('img'), imgNode);
          }
          c.appendChild(imgNode);
          done();
          // 					console.log('Sent ', k, ' to _tileCallbacks');
        };
      })(tileContainer /* , key*/)
    );
    
    return tileContainer;
  }
665366
function writeFiles(privKey, file, keyMode, cb) {
  // No file name - generate a random one under the system temp dir
  if (!file) {
    file = mkTempFile("_gitane", ".sh")
  }

  if (typeof(keyMode) === 'function') {
    cb = keyMode
    keyMode = 0600
  }

  var keyfile = mkTempFile("_gitaneid", ".key")
  var keyfileName = keyfile
  if (isWindows) {
    keyfileName = "\"" + keyfile.replace(/\\/g,"\\\\") + "\"";
  }

  var data = GIT_SSH_TEMPLATE.replace('$key', keyfileName)
  Step(
      function() {
      fs.writeFile(file, data, this.parallel())
      fs.writeFile(keyfile, privKey, this.parallel())
    },
    function(err) {
      if (err) {
        return cb(err, null)
      }
      // make script executable
      fs.chmod(file, 0755, this.parallel())
      // make key secret
      fs.chmod(keyfile, keyMode, this.parallel())
    },
    function(err) {
      if (err) {
        return cb(err, null)
      }

      return cb(null, file, keyfile)
    }
  )
}
1072481
def every(colors, output_dir=CACHE_DIR):
    """"""
    colors = flatten_colors(colors)
    template_dir = os.path.join(MODULE_DIR, "templates")
    template_dir_user = os.path.join(CONF_DIR, "templates")
    util.create_dir(template_dir_user)

    join = os.path.join  # Minor optimization.
    for file in [*os.scandir(template_dir),
                 *os.scandir(template_dir_user)]:
        if file.name != ".DS_Store" and not file.name.endswith(".swp"):
            template(colors, file.path, join(output_dir, file.name))

    logging.info("Exported all files.")
    logging.info("Exported all user files.")