Create a Intel HEX record of given data.
355525
def pack_ihex(type_, address, size, data):
    

    line = '{:02X}{:04X}{:02X}'.format(size, address, type_)

    if data:
        line += binascii.hexlify(data).decode('ascii').upper()

    return ':{}{:02X}'.format(line, crc_ihex(line))
556316
def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
    """"""
    if root is None:
        root = {}
    if not array:
        return None

    if array.GetDataType() == 12:
        # IdType need to be converted to Uint32
        array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
        new_array = vtk.vtkTypeUInt32Array()
        new_array.SetNumberOfTuples(array_size)
        for i in range(array_size):
            new_array.SetValue(i, -1 if array.GetValue(i) <
                              0 else array.GetValue(i))
        pbuffer = memoryview(new_array)
    else:
        pbuffer = memoryview(array)

    pMd5 = hashlib.md5(pbuffer).hexdigest()
    ppath = os.path.join(data_dir, pMd5)
    with open(ppath, 'wb') as f:
        f.write(pbuffer)

    if compress:
        with open(ppath, 'rb') as f_in, gzip.open(os.path.join(data_dir, pMd5 + '.gz'), 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
        # Close then remove.
        os.remove(ppath)

    root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
    root['vtkClass'] = 'vtkDataArray'
    root['name'] = array.GetName()
    root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
    root['numberOfComponents'] = array.GetNumberOfComponents()
    root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
    root['ranges'] = []
    if root['numberOfComponents'] > 1:
        for i in range(root['numberOfComponents']):
            root['ranges'].append(get_range_info(array, i))
        root['ranges'].append(get_range_info(array, -1))
    else:
        root['ranges'].append(get_range_info(array, 0))

    return root
647218
def _make_record(self,row):
        """"""
        res = dict(zip(self.all_fields,row))
        for k in self.types:
            res[k] = self.types[k](res[k])
        return res
644959
def add_ihex(self, records, overwrite=False):
        

        extended_segment_address = 0
        extended_linear_address = 0

        for record in StringIO(records):
            type_, address, size, data = unpack_ihex(record.strip())

            if type_ == IHEX_DATA:
                address = (address
                           + extended_segment_address
                           + extended_linear_address)
                address *= self.word_size_bytes
                self._segments.add(_Segment(address,
                                            address + size,
                                            bytearray(data),
                                            self.word_size_bytes),
                                   overwrite)
            elif type_ == IHEX_END_OF_FILE:
                pass
            elif type_ == IHEX_EXTENDED_SEGMENT_ADDRESS:
                extended_segment_address = int(binascii.hexlify(data), 16)
                extended_segment_address *= 16
            elif type_ == IHEX_EXTENDED_LINEAR_ADDRESS:
                extended_linear_address = int(binascii.hexlify(data), 16)
                extended_linear_address <<= 16
            elif type_ in [IHEX_START_SEGMENT_ADDRESS, IHEX_START_LINEAR_ADDRESS]:
                self.execution_start_address = int(binascii.hexlify(data), 16)
            else:
                raise Error("expected type 1..5 in record {}, but got {}".format(
                    record,
                    type_))
627653
public static String toHex(byte []bytes, int offset, int len)
  {
    if (bytes == null)
      return "null";
    
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < len; i++) {
      int d1 = (bytes[offset + i] >> 4) & 0xf;
      int d2 = (bytes[offset + i]) & 0xf;

      if (d1 < 10)
        sb.append((char) ('0' + d1));
      else
        sb.append((char) ('a' + d1 - 10));

      if (d2 < 10)
        sb.append((char) ('0' + d2));
      else
        sb.append((char) ('a' + d2 - 10));
    }

    return sb.toString();
  }
1231153
def _set_data(self, data):
        """"""
        if type(data) == bytearray:
            self._data = data
        elif type(data) == str:
            if sys.version_info < (3,):
                self._data = bytearray(data)
            else:
                self._data = bytearray(data.encode('ISO-8859-1'))
        elif type(data) == list or type(data) == tuple:
            self._data = bytearray(data)
        elif sys.version_info >= (3,) and type(data) == bytes:
            self._data = bytearray(data)
        else:
            raise Exception('Data must be bytearray, string, list or tuple,'
                            ' not {}'.format(type(data)))
328431
def data_to_uuid(data):
    """"""
    string = data_to_hexstring(data)
    return string[0:8]+'-'+string[8:12]+'-'+string[12:16]+'-'+string[16:20]+'-'+string[20:32]
1059424
def write_crc32(fo, bytes):
    """"""
    data = crc32(bytes) & 0xFFFFFFFF
    fo.write(pack('>I', data))
158344
def hex(self):
        """"""
        addrstr = '000000'
        if self.addr is not None:
            addrstr = binascii.hexlify(self.addr).decode()
        return addrstr
1262912
def __shxRecords(self):
        """"""
        f = self.__getFileObj(self.shx)
        f.seek(100)
        for i in range(len(self._shapes)):
            f.write(pack(">i", self._offsets[i] // 2))
            f.write(pack(">i", self._lengths[i]))
1201432
def bin2hex(fin, fout, offset=0):
    
    h = IntelHex()
    try:
        h.loadbin(fin, offset)
    except IOError:
        e = sys.exc_info()[1]     # current exception
        txt = 'ERROR: unable to load bin file:', str(e)
        print(txt)
        return 1

    try:
        h.tofile(fout, format='hex')
    except IOError:
        e = sys.exc_info()[1]     # current exception
        txt = "ERROR: Could not write to file: %s: %s" % (fout, str(e))
        print(txt)
        return 1

    return 0
119135
def to_ascii_hex(value: int, digits: int) -> str:
    """"""
    if digits < 1:
        return ''
    text = ''
    for _ in range(0, digits):
        text = chr(ord('0') + (value % 0x10)) + text
        value //= 0x10
    return text
875959
def write_hex(fout, buf, offset, width=16):
    

    skipped_zeroes = 0
    for i, chunk in enumerate(chunk_iter(buf, width)):
        # zero skipping
        if chunk == (b"\x00" * width):
            skipped_zeroes += 1
            continue
        elif skipped_zeroes != 0:
            fout.write("  -- skipped zeroes: {}\n".format(skipped_zeroes))
            skipped_zeroes = 0

        # starting address of the current line
        fout.write("{:016x}  ".format(i * width + offset))

        # bytes column
        column = "  ".join([" ".join(["{:02x}".format(c) for c in subchunk])
                            for subchunk in chunk_iter(chunk, 8)])
        w = width * 2 + (width - 1) + ((width // 8) - 1)
        if len(column) != w:
            column += " " * (w - len(column))
        fout.write(column)

        # ASCII character column
        fout.write("  |")
        for c in chunk:
            if c in PRINTABLE_CHARS:
                fout.write(chr(c))
            else:
                fout.write(".")
        if len(chunk) < width:
            fout.write(" " * (width - len(chunk)))
        fout.write("|")

        fout.write("\n")
920729
def to_hex_string(data):
    '''  '''
    if isinstance(data, int):
        return '%02X' % data
    return ':'.join([('%02X' % o) for o in data])
1237390
def make_data():
    """"""
    a = { (1,1):.25, (1,2):.15, (1,3):.2,
          (2,1):.3,  (2,2):.3,  (2,3):.1,
          (3,1):.15, (3,2):.65, (3,3):.05,
          (4,1):.1,  (4,2):.05,  (4,3):.8
          }
    epsilon = 0.01
    I,p = multidict({1:5, 2:6, 3:8, 4:20})
    K,LB = multidict({1:.2, 2:.3, 3:.2})
    return I,K,a,p,epsilon,LB
579962
public static String toHex(byte[] data, int length) {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i != length; i++) {
            int v = data[i] & 0xff;

            buffer.append(DIGITS.charAt(v >> 4));
            buffer.append(DIGITS.charAt(v & 0xf));
        }

        return buffer.toString();
    }
458549
def _generate_vdev(self, base, offset):
        
        vdev = hex(int(base, 16) + offset)[2:]
        return vdev.rjust(4, '0')