/* Convert the given files to the format used by the Storage module,
and return the Intel Hex file for it all.
509505
function toIntelHex(files) {
  var saveAddress, saveSize;
  try {
    saveAddress = Espruino.Core.Env.getData().chip.saved_code.address;
    saveSize = Espruino.Core.Env.getData().chip.saved_code.page_size *
               Espruino.Core.Env.getData().chip.saved_code.pages;
  } catch (e) {
    throw new Error("Board JSON not found or doesn't contain the relevant saved_code section");
  }
  var buffer = new Uint8Array(saveSize);
  buffer.fill(0xFF); // fill with 255 for emptiness
  var offset = 0;
  for (var filename in files) {
    console.log(`Storage: set ${JSON.stringify(filename)} at ${offset} (${files[filename].length} bytes)`);
    offset = setStorageBufferFile(buffer, offset, filename, files[filename]);
  }
  if (offset>saveSize)
    throw new Error(`Too much code to save (${offset} vs ${saveSize} bytes)`);
  // Now work out intel hex
  function h(d) { var n = "0123456789ABCDEF"; return n[(d>>4)&15]+n[d&15]; }
  function ihexline(bytes) {
    bytes.push(1+(~bytes.reduce((a,b)=>a+b)&255)); // checksum - yay JS!
    return ":"+bytes.map(h).join("")+"\r\n";
  }
  var lastHighAddr = -1;
  var ihex = "";
  for (var idx=0;idx<saveSize;idx+=16) {
    var addr = saveAddress+idx;
    var highAddr = addr>>16;
    if (highAddr != lastHighAddr) {
      lastHighAddr = highAddr;
      ihex += ihexline([2,0,0,4,(highAddr>>8)&255,highAddr&255]);
    }
    var bytes = [
      16/*bytes*/,
      (addr>>8)&0xFF, addr&0xFF,
      0]; // record type
    for (var j=0;j<16;j++) bytes.push(buffer[idx+j]);
    ihex += ihexline(bytes);
  }
  // END OF FILE marker (so don't copy this if you're trying to manually merge files!)
  ihex += ":00000001FF\r\n";
  return ihex;
}
1037411
function decodeFile (args) {
    var file = args.file;
    var next = args.next;

    if (file.encoding && (isTypedArray(file.data) || Array.isArray(file.data))) {
      try {
        // Normalize the data to 2-byte characters
        var characterArray = new Uint16Array(file.data);

        // Convert the characters to a string
        var string = String.fromCharCode.apply(null, characterArray);

        // Remove the byte order mark, if any
        return stripBOM(string);
      }
      catch (err) {
        // Unknown encoding, so just call the next decoder plugin
        next();
      }
    }
    else {
      // The file data is not a supported data type, so call the next decoder plugin
      next();
    }
  }
739412
function decodeFile (args) {
    var file = args.file;
    var next = args.next;
    var decoder;

    if (textDecoderIsSupported && file.encoding && isTypedArray(file.data)) {
      try {
        // Attempt to create a TextDecoder for this encoding
        decoder = new TextDecoder(file.encoding, { ignoreBOM: false, fatal: true });
      }
      catch (err) {
        // Unknown encoding, so just call the next decoder plugin
        next();
      }

      // Decode the data
      return decoder.decode(file.data);
    }
    else {
      // The file data is not a supported data type, so call the next decoder plugin
      next();
    }
  }
83540
def _hex_to_octets(addr):
    '''
    
    '''
    return '{0}:{1}:{2}:{3}'.format(
        int(addr[6:8], 16),
        int(addr[4:6], 16),
        int(addr[2:4], 16),
        int(addr[0:2], 16),
    )
557835
function _filesToFile (files, target, separator, callback) {

			if ("undefined" === typeof files) {
				throw new ReferenceError("missing \"files\" argument");
			}
				else if ("object" !== typeof files || !(files instanceof Array)) {
					throw new TypeError("\"files\" argument is not an Array");
				}
			else if ("undefined" === typeof target) {
				throw new ReferenceError("missing \"target\" argument");
			}
				else if ("string" !== typeof target) {
					throw new TypeError("\"target\" argument is not a string");
				}
			else if ("undefined" === typeof callback && "undefined" === typeof separator) {
				throw new ReferenceError("missing \"callback\" argument");
			}
				else if ("function" !== typeof callback && "function" !== typeof separator) {
					throw new TypeError("\"callback\" argument is not a function");
				}
			else {

				const _target = target.trim();

				if ("" === _target) {
					throw new Error("\"target\" argument is empty");
				}
				else {

					const _callback = "undefined" === typeof callback ? separator : callback;

					Promise.resolve().then(() => {
						return isFileProm(_target);
					}).then((exists) => {

						return !exists ? Promise.resolve() : new Promise((resolve, reject) => {

							fs.unlink(_target, (err) => {
								return err ? reject(err) : resolve();
							});

						});

					}).then(() => {

						if (!files.length) {

							return new Promise((resolve, reject) => {

								fs.writeFile(_target, "", (err) => {
									return err ? reject(err) : resolve();
								});

							});

						}
						else {

							return filesToStreamProm(files, "string" === typeof separator ? separator : " ").then((readStream) => {

								return new Promise((resolve, reject) => {

									let error = false;
									readStream.once("error", (_err) => {
										error = true; reject(_err);
									}).pipe(fs.createWriteStream(_target, { "flags": "a" }).once("error", (_err) => {
										error = true; reject(_err);
									}).once("close", () => {

										if (!error) {
											resolve();
										}

									}));

								});

							});

						}

					}).then(() => {
						_callback(null);
					}).catch(_callback);

				}

			}

		}
1128515
def get_file_hash(self, *algorithms: str):
        '''
        
        '''
        from .hashs import hashfile_hexdigest
        return hashfile_hexdigest(self._path, algorithms)
583337
private File getTarFile(String name) {
        File hexCache = new File(dotHexCachePath);
        File[] files = hexCache.listFiles(new HexFileNameFilter(name));
        if (files != null && files.length > 0) {
            Arrays.sort(files, Collections.reverseOrder());
            return files[0];
        }
        logger.warn("Couldn't find tar file of {}", name);
        return null;
    }
787211
def convert(f, opts = {})
      opts = opts.dup
      f = f.to_s.downcase
      allowed = %w(jpeg jpg png)
      raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f)
      self.format_override = f == 'jpeg' ? 'jpg' : f
      opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality)
      write_opts.merge!(opts)
      get_image
    end
700825
def convert_to_file(cgi_input, output_file, twobit_ref, twobit_name, var_only=False):
    """"""

    if isinstance(output_file, str):
        output_file = auto_zip_open(output_file, 'w')

    conversion = convert(cgi_input=cgi_input, twobit_ref=twobit_ref, twobit_name=twobit_name, var_only=var_only)
    for line in conversion:
        output_file.write(line + "\n")
    output_file.close()
1353059
function formatFileOutput(mappings, type) {
  var string = JSON.stringify(mappings, null, 2);
  if (type === '.js') {
    return 'module.exports=' + string;
  } else if (type === '.json') {
    return string;
  }
}
39517
function outputFile(options, conf) {
    const json = JSON.stringify(options),
          sha1 = crypto.createHash('sha1').update(json).digest('hex'),
          format = options.format || DEF_FORMAT;
    return conf.storage + path.sep + sha1 + '.' + format;
}
66985
def load_fw(path):
    """"""
    fname = os.path.realpath(path)
    exists = os.path.isfile(fname)
    if not exists or not os.access(fname, os.R_OK):
        _LOGGER.error(
            'Firmware path %s does not exist or is not readable',
            path)
        return None
    try:
        intel_hex = IntelHex()
        with open(path, 'r') as file_handle:
            intel_hex.fromfile(file_handle, format='hex')
        return intel_hex.tobinstr()
    except (IntelHexError, TypeError, ValueError) as exc:
        _LOGGER.error(
            'Firmware not valid, check the hex file at %s: %s', path, exc)
        return None
239323
function getFormatChunksFrom (rawValues, prefix) {
      getFormatChunksFrom_accumulator.length = 0;

      var rawValuesLength = rawValues.length;
      var i;

      for (i = 0; i < rawValuesLength; i++) {
        getFormatChunksFrom_accumulator.push('_' + prefix + '_' + i);
      }

      return getFormatChunksFrom_accumulator;
    }
686048
def file_hash(load, fnd):
    '''
    
    '''
    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    if not all(x in load for x in ('path', 'saltenv')):
        return ''
    ret = {'hash_type': __opts__['hash_type']}
    relpath = fnd['rel']
    path = fnd['path']
    hashdest = os.path.join(__opts__['cachedir'],
                            'hgfs/hash',
                            load['saltenv'],
                            '{0}.hash.{1}'.format(relpath,
                                                  __opts__['hash_type']))
    if not os.path.isfile(hashdest):
        ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
        with salt.utils.files.fopen(hashdest, 'w+') as fp_:
            fp_.write(ret['hsum'])
        return ret
    else:
        with salt.utils.files.fopen(hashdest, 'rb') as fp_:
            ret['hsum'] = salt.utils.stringutils.to_unicode(fp_.read())
        return ret
1068828
def format_file_params(files):
        '''
            
        '''
        files_payload = {}
        if files:
            for idx, filename in enumerate(files):
                files_payload["file[" + str(idx) + "]"] = open(filename, 'rb')
        return files_payload
895542
function _0xColorToHex(color, convertToStr) {
        var hexColor = tinycolor(color.replace("0x", "#"));
        hexColor._format = "0x";

        if (convertToStr) {
            return hexColor.toString();
        }
        return hexColor;
    }
505818
private FileStatus versionBasedGetFileInfo(String src) throws IOException {
    if (namenodeVersion >= ClientProtocol.OPTIMIZE_FILE_STATUS_VERSION) {
      return HdfsFileStatus.toFileStatus(namenode.getHdfsFileInfo(src), src);
    } else {
      return namenode.getFileInfo(src);
    }
  }