Convert attribute values from numpy objects to native Python objects,
    for use in to_dict
506021
def decode_numpy_dict_values(attrs: Mapping[K, V]) -> Dict[K, V]:
    
    attrs = dict(attrs)
    for k, v in attrs.items():
        if isinstance(v, np.ndarray):
            attrs[k] = v.tolist()
        elif isinstance(v, np.generic):
            attrs[k] = v.item()
    return attrs
10436
def to_dict(obj):
    
    d = _to_json_type(obj)
    if isinstance(d, dict):
        return scrub_dict(d)
    else:
        raise ValueError("The value provided must be an object.")
1107706
def from_dict(cls, arr_dict, dtype=None, fillna=False, **kwargs):
        
        # i hope order of keys == order or values
        if dtype is None:
            names = sorted(list(arr_dict.keys()))
        else:
            dtype = np.dtype(dtype)
            dt_names = [f for f in dtype.names]
            dict_names = [k for k in arr_dict.keys()]
            missing_names = set(dt_names) - set(dict_names)
            if missing_names:
                if fillna:
                    dict_names = dt_names
                    for missing_name in missing_names:
                        arr_dict[missing_name] = np.nan
                else:
                    raise KeyError(
                        'Dictionary keys and dtype fields do not match!'
                    )
            names = list(dtype.names)

        arr_dict = cls._expand_scalars(arr_dict)
        data = [arr_dict[key] for key in names]
        return cls(np.rec.fromarrays(data, names=names, dtype=dtype), **kwargs)
1125223
def to_native_types(self, slicer=None, na_rep=None, date_format=None,
                        quoting=None, **kwargs):
        

        values = self.values
        i8values = self.values.view('i8')

        if slicer is not None:
            values = values[..., slicer]
            i8values = i8values[..., slicer]

        from pandas.io.formats.format import _get_format_datetime64_from_values
        fmt = _get_format_datetime64_from_values(values, date_format)

        result = tslib.format_array_from_datetime(
            i8values.ravel(), tz=getattr(self.values, 'tz', None),
            format=fmt, na_rep=na_rep).reshape(i8values.shape)
        return np.atleast_2d(result)
904932
def pytype_to_ctype(t):
    
    if isinstance(t, List):
        return 'pythonic::types::list<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Set):
        return 'pythonic::types::set<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Dict):
        tkey, tvalue = t.__args__
        return 'pythonic::types::dict<{0},{1}>'.format(pytype_to_ctype(tkey),
                                                       pytype_to_ctype(tvalue))
    elif isinstance(t, Tuple):
        return 'decltype(pythonic::types::make_tuple({0}))'.format(
            ", ".join('std::declval<{}>()'.format(pytype_to_ctype(p))
                      for p in t.__args__)
        )
    elif isinstance(t, NDArray):
        dtype = pytype_to_ctype(t.__args__[0])
        ndim = len(t.__args__) - 1
        shapes = ','.join(('long'
                           if s.stop == -1 or s.stop is None
                           else 'std::integral_constant<long, {}>'.format(
                               s.stop)
                           ) for s in t.__args__[1:])
        pshape = 'pythonic::types::pshape<{0}>'.format(shapes)
        arr = 'pythonic::types::ndarray<{0},{1}>'.format(
                    dtype, pshape)
        if t.__args__[1].start == -1:
            return 'pythonic::types::numpy_texpr<{0}>'.format(arr)
        elif any(s.step is not None and s.step < 0 for s in t.__args__[1:]):
            slices = ", ".join(['pythonic::types::normalized_slice'] * ndim)
            return 'pythonic::types::numpy_gexpr<{0},{1}>'.format(arr, slices)
        else:
            return arr
    elif isinstance(t, Pointer):
        return 'pythonic::types::pointer<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Fun):
        return 'pythonic::types::cfun<{0}({1})>'.format(
            pytype_to_ctype(t.__args__[-1]),
            ", ".join(pytype_to_ctype(arg) for arg in t.__args__[:-1]),
        )
    elif t in PYTYPE_TO_CTYPE_TABLE:
        return PYTYPE_TO_CTYPE_TABLE[t]
    else:
        raise NotImplementedError("{0}:{1}".format(type(t), t))
908516
def to_python(self, value):
        
        if not value:
            return {}
        elif isinstance(value, six.string_types):
            res = loads(value)
            assert isinstance(res, dict)
            return JSONDict(**res)
        else:
            return value
1055708
def as_dict(self):
        
        self.clean()
        d = OrderedDict()
        all_props = self.__class__.CONFIG_PROPERTIES
        for attr_name, attr_config in six.iteritems(all_props):
            value = self._config[attr_name]
            attr_type = attr_config.attr_type
            if attr_type:
                if value:
                    if issubclass(attr_type, list):
                        if issubclass(attr_type, NamedTupleList):
                            d[attr_name] = [i._asdict() for i in value]
                        else:
                            d[attr_name] = value[:]
                    elif attr_type is dict:
                        d[attr_name] = dict(value)
            elif value is not NotSet:
                d[attr_name] = value
        return d
1225957
def dict_to_object(source):
    """"""
    target = inspectable_class.InspectableClass()
    for k, v in source.items():
        setattr(target, k, v)
    return target
1260319
def deep_convert_dict(value):
    
    to_ret = value
    if isinstance(value, OrderedDict):
        to_ret = dict(value)

    try:
        for k, v in to_ret.items():
            to_ret[k] = deep_convert_dict(v)
    except AttributeError:
        pass

    return to_ret
976597
def obj2str(obj):
    """"""
    if isinstance(obj, str_types):
        return obj.encode("utf-8")
    elif isinstance(obj, pathlib.Path):
        return obj2str(str(obj))
    elif isinstance(obj, (bool, int, float)):
        return str(obj).encode("utf-8")
    elif obj is None:
        return b"none"
    elif isinstance(obj, np.ndarray):
        return obj.tostring()
    elif isinstance(obj, tuple):
        return obj2str(list(obj))
    elif isinstance(obj, list):
        return b"".join(obj2str(o) for o in obj)
    elif isinstance(obj, dict):
        return obj2str(list(obj.items()))
    elif hasattr(obj, "identifier"):
        return obj2str(obj.identifier)
    elif isinstance(obj, h5py.Dataset):
        return obj2str(obj[0])
    else:
        raise ValueError("No rule to convert object '{}' to string.".
                         format(obj.__class__))
96614
def _from_dict(cls, values, value_filter, dictionary, allow_unset=True):
        """"""
        if not isinstance(dictionary, Mapping):
            raise TypeError('dictionary should be mapping')
        obj = cls(values, value_filter)
        values = obj.__values
        for name, value in dictionary.items():
            if not isinstance(name, string_types):
                raise TypeError('Key %s is not a string' % str(name))
            setattr(values, name, value)
        if obj.missing and not allow_unset:
            raise ValueError('%d value(s) are unset' % len(obj.missing))
        return obj
518760
def dict_to_object(self, obj):  # pylint: disable=no-self-use
        """"""
        if not isinstance(obj, dict):
            return obj
        if 'sensor_id' in obj:
            sensor = Sensor(obj['sensor_id'])
            for key, val in obj.items():
                setattr(sensor, key, val)
            return sensor
        if all(k in obj for k in ['id', 'type', 'values']):
            child = ChildSensor(
                obj['id'], obj['type'], obj.get('description', ''))
            child.values = obj['values']
            return child
        if all(k.isdigit() for k in obj.keys()):
            return {int(k): v for k, v in obj.items()}
        return obj
103813
def copy_from_dict(self, attributes):
    
    for attribute_name, attribute_value in attributes.items():
      # Not using startswith to improve performance.
      if attribute_name[0] == '_':
        continue
      setattr(self, attribute_name, attribute_value)
403732
def dict_to_numpy_array(d):
    
    return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))
980212
def _ConvertAttributeValueToDict(cls, attribute_value):
    
    if isinstance(attribute_value, py2to3.BYTES_TYPE):
      encoded_value = binascii.b2a_qp(attribute_value)
      encoded_value = codecs.decode(encoded_value, 'ascii')
      attribute_value = {
          '__type__': 'bytes',
          'stream': '{0:s}'.format(encoded_value)
      }

    elif isinstance(attribute_value, (list, tuple)):
      json_list = []
      for list_element in attribute_value:
        json_dict = cls._ConvertAttributeValueToDict(list_element)
        json_list.append(json_dict)

      if isinstance(attribute_value, list):
        attribute_value = json_list
      else:
        attribute_value = {
            '__type__': 'tuple',
            'values': json_list
        }

    elif isinstance(attribute_value, collections.Counter):
      attribute_value = cls._ConvertCollectionsCounterToDict(attribute_value)

    elif isinstance(attribute_value, dfvfs_path_spec.PathSpec):
      attribute_value = cls._ConvertPathSpecToDict(attribute_value)

    elif isinstance(attribute_value, containers_interface.AttributeContainer):
      attribute_value = cls._ConvertAttributeContainerToDict(attribute_value)

    return attribute_value
1043271
def dict_to_cognito(attributes, attr_map=None):
    
    if attr_map is None:
        attr_map = {}
    for k,v in attr_map.items():
        if v in attributes.keys():
            attributes[k] = attributes.pop(v)

    return [{'Name': key, 'Value': value} for key, value in attributes.items()]
1227479
def to_python(self):
        """"""
        mapping = {}
        for row in self.rows:
            mapping[row[0]] = _format_python_value(row[1])
        return mapping