Parses a basic VAR="value data" file contents into a dict

    :param data:
        A unicode string of the file data

    :return:
        A dict of parsed name/value data
338565
def _parse_env_var_file(data):
    

    output = {}
    for line in data.splitlines():
        line = line.strip()
        if not line or '=' not in line:
            continue
        parts = line.split('=')
        if len(parts) != 2:
            continue
        name = parts[0]
        value = parts[1]
        if len(value) > 1:
            if value[0] == '"' and value[-1] == '"':
                value = value[1:-1]
        output[name] = value
    return output
110032
def to_python(self, data):
        
        if data is None:
            return ''
        if isinstance(data, unicode):
            data = data.encode(DEFAULT_ENCODING)
        else:
            data = str(data)
        return data
233070
def _parse_line_vars(self, line):
        
        key_values = {}

        # Undocumented feature allows json in vars sections like so:
        #   [prod:vars]
        #   json_like_vars=[{'name': 'htpasswd_auth'}]
        # We'll try this first. If it fails, we'll fall back to normal var
        # lines. Since it's undocumented, we just assume some things.
        k, v = line.strip().split('=', 1)
        if v.startswith('['):
            try:
                list_res = ihateyaml.safe_load(v)
                if isinstance(list_res[0], dict):
                    key_values = list_res[0]
                    return key_values
            except ValueError:
                pass

        # Guess it's not YAML. Parse as normal host variables
        tokens = shlex.split(line.strip())
        key_values = self._parse_vars(tokens)
        return key_values
77389
def GetDataAsObject(self):
    
    if not self._data:
      return None

    if self._data_type in self._STRING_VALUE_TYPES:
      try:
        return self._data.decode('utf-16-le')

      # AttributeError is raised when self._data has no decode method.
      except AttributeError as exception:
        raise errors.WinRegistryValueError((
            'Unsupported data type: {0!s} of value: {1!s} with error: '
            '{2!s}').format(type(self._data), self._name, exception))

      except UnicodeError as exception:
        raise errors.WinRegistryValueError(
            'Unable to decode data of value: {0!s} with error: {1!s}'.format(
                self._name, exception))

    elif (self._data_type == definitions.REG_DWORD and
          self._data_size == 4):
      return self._INT32_LITTLE_ENDIAN.MapByteStream(self._data)

    elif (self._data_type == definitions.REG_DWORD_BIG_ENDIAN and
          self._data_size == 4):
      return self._INT32_BIG_ENDIAN.MapByteStream(self._data)

    elif (self._data_type == definitions.REG_QWORD and
          self._data_size == 8):
      return self._INT64_LITTLE_ENDIAN.MapByteStream(self._data)

    elif self._data_type == definitions.REG_MULTI_SZ:
      try:
        utf16_string = self._data.decode('utf-16-le')
        # TODO: evaluate the use of filter here is appropriate behavior.
        return list(filter(None, utf16_string.split('\x00')))

      # AttributeError is raised when self._data has no decode method.
      except AttributeError as exception:
        raise errors.WinRegistryValueError((
            'Unsupported data type: {0!s} of value: {1!s} with error: '
            '{2!s}').format(type(self._data), self._name, exception))

      except UnicodeError as exception:
        raise errors.WinRegistryValueError(
            'Unable to read data from value: {0!s} with error: {1!s}'.format(
                self._name, exception))

    return self._data
489730
def data_item(data):
    
    if isinstance(data, ndict):
        # OK, we have something that looks like {0: ('a', 'b')}
        # or something that is a regular dictionary
        # so try to return 'a' regardless of the length
        for item in data:
            return repr(data[item][0])
    elif isinstance(data, dict):
        for item in data:
            return repr(data[item])
    elif isinstance(data, list):
        return repr(data[0])
    return repr(data)
621662
def parse(self, data: bytes, context=None):
        
        stream = BytesIO(data)
        return self.parse_stream(stream, context)
1231512
def _read_data(path):
    
    data = {}
    with open(path, "r") as f_obj:
        var = ""
        for line in f_obj:
            if "<-" in line:
                if len(var):
                    key, var = _process_data_var(var)
                    data[key] = var
                var = ""
            var += " " + line.strip()
        if len(var):
            key, var = _process_data_var(var)
            data[key] = var
    return data
1341156
def _load_data(self):
        
        ipa_canonical_string_to_ascii_str = dict()
        for line in load_data_file(
            file_path=self.DATA_FILE_PATH,
            file_path_is_relative=True,
            line_format=u"sxA"
        ):
            i_desc, i_ascii = line
            if len(i_ascii) == 0:
                raise ValueError("Data file '%s' contains a bad line: '%s'" % (self.DATA_FILE_PATH, line))
            key = (variant_to_canonical_string(i_desc),)
            ipa_canonical_string_to_ascii_str[key] = i_ascii[0]
        return ipa_canonical_string_to_ascii_str
1238173
def _parse_raw_data(self):
        
        if self.uuid == _XMP_UUID:
            txt = self.raw_data.decode('utf-8')
            elt = ET.fromstring(txt)
            self.data = ET.ElementTree(elt)
        elif self.uuid == _GEOTIFF_UUID:
            self.data = tiff_header(self.raw_data)
        elif self.uuid == _EXIF_UUID:
            # Cut off 'EXIF\0\0' part.
            self.data = tiff_header(self.raw_data[6:])
        else:
            self.data = self.raw_data
1116966
def _read_var_data(self):
        

        var_bundles = OrderedDict()
        var_attrs = OrderedDict()

        n_vars = 0

        while self.fp.tell() < self.fsize:

            var_attr = OrderedDict()

            # read first and second header lines
            line = self.fp.readline('20sffii')
            modelname, res0, res1, halfpolar, center180 = line

            line = self.fp.readline('40si40sdd40s7i')
            category_name, number, unit, tau0, tau1, reserved = line[:6]
            dim0, dim1, dim2, dim3, dim4, dim5, skip = line[6:]
            var_attr['number'] = number

            # Decode byte-strings to utf-8
            category_name = str(category_name, 'utf-8')
            var_attr['category'] = category_name.strip()
            unit = str(unit, 'utf-8')

            # get additional metadata from tracerinfo / diaginfo
            try:
                cat_df = self.diaginfo_df[
                    self.diaginfo_df.name == category_name.strip()
                ]
                # TODO: Safer logic for handling case where more than one
                #       tracer metadata match was made
                # if len(cat_df > 1):
                #     raise ValueError(
                #         "More than one category matching {} found in "
                #         "diaginfo.dat".format(
                #             category_name.strip()
                #         )
                #     )
                # Safe now to select the only row in the DataFrame
                cat = cat_df.T.squeeze()

                tracer_num = int(cat.offset) + int(number)
                diag_df = self.tracerinfo_df[
                    self.tracerinfo_df.tracer == tracer_num
                ]
                # TODO: Safer logic for handling case where more than one
                #       tracer metadata match was made
                # if len(diag_df > 1):
                #     raise ValueError(
                #         "More than one tracer matching {:d} found in "
                #         "tracerinfo.dat".format(tracer_num)
                #     )
                # Safe now to select only row in the DataFrame
                diag = diag_df.T.squeeze()
                diag_attr = diag.to_dict()

                if not unit.strip():  # unit may be empty in bpch
                    unit = diag_attr['unit']  # but not in tracerinfo
                var_attr.update(diag_attr)
            except:
                diag = {'name': '', 'scale': 1}
                var_attr.update(diag)
            var_attr['unit'] = unit

            vname = diag['name']
            fullname = category_name.strip() + "_" + vname

            # parse metadata, get data or set a data proxy
            if dim2 == 1:
                data_shape = (dim0, dim1)         # 2D field
            else:
                data_shape = (dim0, dim1, dim2)
            var_attr['original_shape'] = data_shape

            # Add proxy time dimension to shape
            data_shape = tuple([1, ] + list(data_shape))
            origin = (dim3, dim4, dim5)
            var_attr['origin'] = origin

            timelo, timehi = cf.tau2time(tau0), cf.tau2time(tau1)

            pos = self.fp.tell()
            # Note that we don't pass a dtype, and assume everything is
            # single-fp floats with the correct endian, as hard-coded
            var_bundle = BPCHDataBundle(
                data_shape, self.endian, self.filename, pos, [timelo, timehi],
                metadata=var_attr,
                use_mmap=self.use_mmap, dask_delayed=self.dask_delayed
            )
            self.fp.skipline()

            # Save the data as a "bundle" for concatenating in the final step
            if fullname in var_bundles:
                var_bundles[fullname].append(var_bundle)
            else:
                var_bundles[fullname] = [var_bundle, ]
                var_attrs[fullname] = var_attr
                n_vars += 1

        self.var_data = var_bundles
        self.var_attrs = var_attrs
81467
def get_unicode(data):
    
    # if this is a common string, return its unicode representation
    if isinstance(data, str):
        return safe_unicode(data)

    # if this is a list of values, return list of unicode values
    if isinstance(data, list):
        return [get_unicode(item) for item in data]

    # if this is a dictionary, return dictionary of unicode keys and values
    if isinstance(data, dict):
        return {
            get_unicode(key): get_unicode(value)
            for key, value in data.iteritems()
        }
    # if it's anything else, return it in its original form
    return data
319712
def read_dict(file_name, clear_none=False, encoding='utf-8'):
    
    with open(file_name, 'rb') as f:
        data = f.read()

    if encoding is not None:
        data = data.decode(encoding)

    line_list = data.splitlines()
    data = []
    i = 0
    for line in line_list:
        i += 1
        try:
            line = force_text(line).strip()
            data.append(line)
        except:
            print('read error line %s' % i)
    if clear_none:
        data = [t for t in data if t != '']
    data = deque(data)
    return data
313987
def parse_radl(data):
    
    if not isinstance(data, list):
        if os.path.isfile(data):
            f = open(data)
            data = "".join(f.readlines())
            f.close()
        data = json.loads(data)
    data = encode_simple(data)
    res = RADL()
    for aspect in [p_aspect(a) for a in data]:
        res.add(aspect)
    return res
549258
def value_from_datadict(self, data, files, name):
        
        clear = self.checkbox.value_from_datadict(data, files, self.clear_checkbox_name(name))
        if clear:
            return self.empty_value
        return self.widget.value_from_datadict(data, files, name)
918229
def parse_dict(self, data_dict):
        
        assert isinstance(data_dict, dict)
        string_repr = json.dumps(data_dict)
        return self.parse_JSON(string_repr)
1371243
def parse_data_to_internal(self, data=None):
        
        if data is None:
            kwargs = self.kwargs
            data = np.loadtxt(
                open(self.location_dat, "rb"), **kwargs
            )
        if self.filetype is "pickle":
            pickle.dump(data, open(self.location_internal, "wb"))
        elif self.filetype is "hickle":
            import hickle
            hickle.dump(data, open(self.location_internal, "wb"))
        else:
            raise ValueError(
                "Invalid filetype {} (must be {} or {})".format(
                    self.filetype, "pickle", "hickle"
                )
            )
125204
def to_str(data):
    
    if isinstance(data, bytes):
        return codecs.decode(data, TEXT_ENCODING)
    return data