Read MM_UIC1 tag from file and return as dictionary.
187884
def read_mm_uic1(fd, byte_order, dtype, count):
    """"""
    t = fd.read(8*count)
    t = struct.unpack('%s%iI' % (byte_order, 2*count), t)
    return dict((MM_TAG_IDS[k], v) for k, v in zip(t[::2], t[1::2])
                if k in MM_TAG_IDS)
1351232
def parse_readme():
    """"""
    # Get the long description from the relevant file
    here = os.path.abspath(os.path.dirname(__file__))
    readme_path = os.path.join(here, 'README.md')
    with codecs.open(readme_path, encoding='utf-8') as handle:
        long_description = handle.read()

    return long_description
366920
def _extract_mnist_labels(filename, num_labels):
  
  with gzip.open(filename) as bytestream:
    bytestream.read(8)
    buf = bytestream.read(num_labels)
    labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
  return labels
1099336
def get_tag_value(x, key):
    """"""
    if x is None:
        return ''
    result = [y['Value'] for y in x if y['Key'] == key]
    if result:
        return result[0]
    return ''
357269
def read_uic_tag(fh, tagid, planecount, offset):
    
    def read_int(count=1):
        value = struct.unpack('<%iI' % count, fh.read(4*count))
        return value[0] if count == 1 else value

    try:
        name, dtype = TIFF.UIC_TAGS[tagid]
    except IndexError:
        # unknown tag
        return '_TagId%i' % tagid, read_int()

    Fraction = TIFF.UIC_TAGS[4][1]

    if offset:
        pos = fh.tell()
        if dtype not in (int, None):
            off = read_int()
            if off < 8:
                if dtype is str:
                    return name, ''
                log.warning("read_uic_tag: invalid offset for tag '%s' (%i)",
                            name, off)
                return name, off
            fh.seek(off)

    if dtype is None:
        # skip
        name = '_' + name
        value = read_int()
    elif dtype is int:
        # int
        value = read_int()
    elif dtype is Fraction:
        # fraction
        value = read_int(2)
        value = value[0] / value[1]
    elif dtype is julian_datetime:
        # datetime
        value = julian_datetime(*read_int(2))
    elif dtype is read_uic_image_property:
        # ImagePropertyEx
        value = read_uic_image_property(fh)
    elif dtype is str:
        # pascal string
        size = read_int()
        if 0 <= size < 2**10:
            value = struct.unpack('%is' % size, fh.read(size))[0][:-1]
            value = bytes2str(stripnull(value))
        elif offset:
            value = ''
            log.warning("read_uic_tag: corrupt string in tag '%s'", name)
        else:
            raise ValueError('read_uic_tag: invalid string size %i' % size)
    elif dtype == '%ip':
        # sequence of pascal strings
        value = []
        for _ in range(planecount):
            size = read_int()
            if 0 <= size < 2**10:
                string = struct.unpack('%is' % size, fh.read(size))[0][:-1]
                string = bytes2str(stripnull(string))
                value.append(string)
            elif offset:
                log.warning("read_uic_tag: corrupt string in tag '%s'", name)
            else:
                raise ValueError('read_uic_tag: invalid string size: %i' %
                                 size)
    else:
        # struct or numpy type
        dtype = '<' + dtype
        if '%i' in dtype:
            dtype = dtype % planecount
        if '(' in dtype:
            # numpy type
            value = fh.read_array(dtype, 1)[0]
            if value.shape[-1] == 2:
                # assume fractions
                value = value[..., 0] / value[..., 1]
        else:
            # struct format
            value = struct.unpack(dtype, fh.read(struct.calcsize(dtype)))
            if len(value) == 1:
                value = value[0]

    if offset:
        fh.seek(pos + 4)

    return name, value
821045
def ReadTag(buf, pos):
  """"""
  try:
    start = pos
    while ORD_MAP_AND_0X80[buf[pos]]:
      pos += 1
    pos += 1
    return (buf[start:pos], pos)
  except IndexError:
    raise ValueError("Invalid tag")
1198258
def raw_data(tag_value):
        
        data = {}
        pieces = []
        for p in tag_value.split(' '):
            pieces.extend(p.split(';'))
        # parse components
        for piece in pieces:
            kv = piece.split('=')
            # components must by key=value
            if not len(kv) == 2:
                continue
            key, value = kv
            data[key] = value
        return data
495010
def _ic_decode(self, msg):
        """"""
        code = msg[4:16]
        if re.match(r'(0\d){6}', code):
            code = re.sub(r'0(\d)', r'\1', code)
        return {'code': code, 'user': int(msg[16:19])-1,
                'keypad': int(msg[19:21])-1}
1155495
def _canon_decode_tag(self, value, mn_tags):
        
        for i in range(1, len(value)):
            tag = mn_tags.get(i, ('Unknown', ))
            name = tag[0]
            if len(tag) > 1:
                val = tag[1].get(value[i], 'Unknown')
            else:
                val = value[i]
            try:
                logger.debug(" %s %s %s", i, name, hex(value[i]))
            except TypeError:
                logger.debug(" %s %s %s", i, name, value[i])

            # it's not a real IFD Tag but we fake one to make everybody
            # happy. this will have a "proprietary" type
            self.tags['MakerNote ' + name] = IfdTag(str(val), None, 0, None,
                                                    None, None)
471559
def read(self, size=-1):
        """"""
        bites = self.file.read(size)
        self.bytes_read += len(bites)
        self.callback(len(bites), self.bytes_read)
        return bites
358282
def read_mm_uic3(fd, byte_order, dtype, count):
    """"""
    t = numpy.fromfile(fd, byte_order+'I', 2*count)
    return {'wavelengths': t[0::2] // t[1::2]}
674471
def extract_labels(filename):
    """"""
    with gzip.open(filename) as bytestream:
        magic = _read32(bytestream)
        if magic != 2049:
            raise ValueError(
                'Invalid magic number %d in MNIST label file: %s' %
                (magic, filename))
        num_items = _read32(bytestream)
        buf = bytestream.read(num_items)
        labels = numpy.frombuffer(buf, dtype=numpy.uint8)
        return labels
1195160
def from_dict(cls, tag=None):
        

        if tag is None:
            tag = {}

        l = Tag()
        l.name = tag['name']
        return l
701972
def _parse(self, text):
        '''
        
        '''
        # ensure unicode first
        text = str(text).strip()

        if not text.startswith(DELIMITER):
            return {}, text

        try:
            _, fm, content = BOUNDARY.split(text, 2)
        except ValueError:
            # if we can't split, bail
            return {}, text
        # loader_class = self.loader_factory(self)
        metadata = yaml.load(fm, Loader=self.loader_class)
        metadata = metadata if (isinstance(metadata, dict)) else {}
        return metadata, content
173574
def read_fei_metadata(fh, byteorder, dtype, count, offsetsize):
    """"""
    result = {}
    section = {}
    data = bytes2str(stripnull(fh.read(count)))
    for line in data.splitlines():
        line = line.strip()
        if line.startswith('['):
            section = {}
            result[line[1:-1]] = section
            continue
        try:
            key, value = line.split('=')
        except ValueError:
            continue
        section[key] = astype(value)
    return result
278643
def _parse(self, text, i):
        """"""

        m = self.start_dict_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            return self._parse_dict(text, i)

        m = self.start_list_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            return self._parse_list(text, i)

        m = self.value_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            if hasattr(self.current_type, "read"):
                reader = self.current_type()
                # Give the escaped value to `read` to be symetrical with
                # `plistValue` which handles the escaping itself.
                value = reader.read(m.group(1))
                return value, i

            value = self._trim_value(m.group(1))

            if self.current_type in (None, dict, OrderedDict):
                self.current_type = self._guess_current_type(parsed, value)

            if self.current_type == bool:
                value = bool(int(value))  # bool(u'0') returns True
                return value, i

            value = self.current_type(value)

            return value, i

        m = self.hex_re.match(text, i)
        if m:
            from glyphsLib.types import BinaryData

            parsed, value = m.group(0), m.group(1)
            decoded = BinaryData.fromHex(value)
            i += len(parsed)
            return decoded, i
        else:
            self._fail("Unexpected content", text, i)
517526
def read_mm_uic2(fd, byte_order, dtype, count):
    """"""
    result = {'number_planes': count}
    values = numpy.fromfile(fd, byte_order+'I', 6*count)
    result['z_distance'] = values[0::6] // values[1::6]
    #result['date_created'] = tuple(values[2::6])
    #result['time_created'] = tuple(values[3::6])
    #result['date_modified'] = tuple(values[4::6])
    #result['time_modified'] = tuple(values[5::6])
    return result