dict (dynamo name) -> obj
13061
def _load(cls, attrs, *, context, **kwargs):
        
        return unpack_from_dynamodb(
            model=cls,
            attrs=attrs or {},
            expected=cls.Meta.columns,
            context=context, **kwargs)
494443
def sobject_to_json(obj, key_to_lower=False):
    
    import json
    data = sobject_to_dict(obj, key_to_lower=key_to_lower, json_serialize=True)
    return json.dumps(data)
1010320
def sync(obj, engine):
    """"""
    snapshot = Condition()
    # Only expect values (or lack of a value) for columns that have been explicitly set
    for column in sorted(_obj_tracking[obj]["marked"], key=lambda col: col.dynamo_name):
        value = getattr(obj, column.name, None)
        value = engine._dump(column.typedef, value)
        condition = column == value
        # The renderer shouldn't try to dump the value again.
        # We're dumping immediately in case the value is mutable,
        # such as a set or (many) custom data types.
        condition.dumped = True
        snapshot &= condition
    _obj_tracking[obj]["snapshot"] = snapshot
1075016
def as_dict(self):
        """"""
        def conv(v):
            if isinstance(v, SerializableAttributesHolder):
                return v.as_dict()
            elif isinstance(v, list):
                return [conv(x) for x in v]
            elif isinstance(v, dict):
                return {x:conv(y) for (x,y) in v.items()}
            else:
                return v
        return {k.replace('_', '-'): conv(v) for (k, v) in self._attributes.items()}
367679
def get_obj_attrs(obj):
    
    pr = {}
    if obj is not None:
        if isinstance(obj, numpy.core.records.record):
            for name in obj.dtype.names:
                pr[name] = getattr(obj, name)
        elif hasattr(obj, '__dict__') and obj.__dict__:
            pr = obj.__dict__
        elif hasattr(obj, '__slots__'):
            for slot in obj.__slots__:
                if hasattr(obj, slot):
                    pr[slot] = getattr(obj, slot)
        elif isinstance(obj, dict):
            pr = obj.copy()
        else:
            for name in dir(obj):
                try:
                    value = getattr(obj, name)
                    if not name.startswith('__') and not inspect.ismethod(value):
                        pr[name] = value
                except:
                    continue

    return pr
234239
def json_repr(obj):
    

    def serialize(obj):
        """Recursively walk object's hierarchy.
        """
        if obj is None:
            return None
        if isinstance(obj, Enum):
            return str(obj)
        if isinstance(obj, (bool, int, float, str)):
            return obj
        if isinstance(obj, dict):
            obj = obj.copy()
            for key in sorted(obj.keys()):
                obj[key] = serialize(obj[key])
            return obj
        if isinstance(obj, list):
            return [serialize(item) for item in obj]
        if isinstance(obj, tuple):
            return tuple(serialize([item for item in obj]))
        if hasattr(obj, '__dict__'):
            return serialize(obj.__dict__)
        return repr(obj)

    return json.dumps(serialize(obj))
1166533
def delete_object(self, object):
        
        #pdb.set_trace()
        self.db.engine.delete_key(object)#, userid='abc123', id='1')
        print('dynamo.delete_object(%s)' % object)
604153
def model_to_dict(instance, **options):
    ""

    options = _defaults(options)
    attrs = {}

    if options['prehook']:
        if isinstance(options['prehook'], collections.Callable):
            instance = options['prehook'](instance)
            if instance is None:
                return attrs

    # Items in the `fields` list are the output aliases, not the raw
    # accessors (field, method, property names)
    for alias in options['fields']:

        # Get the accessor for the object
        accessor = options['aliases'].get(alias, alias)

        # Create the key that will be used in the output dict
        key = options['prefix'] + alias

        # Optionally camelcase the key
        if options['camelcase']:
            key = convert_to_camel(key)

        # Get the field value. Use the mapped value to the actually property or
        # method name. `value` may be a number of things, so the various types
        # are checked below.
        value = get_field_value(instance, accessor,
                                allow_missing=options['allow_missing'])

        # Related objects, perform some checks on their options
        if isinstance(value, (models.Model, QuerySet)):
            _options = _defaults(options['related'].get(accessor, {}))

            # If the `prefix` follows the below template, generate the
            # `prefix` for the related object
            if '%(accessor)s' in _options['prefix']:
                _options['prefix'] = _options['prefix'] % {'accessor': alias}

            if isinstance(value, models.Model):
                if len(_options['fields']) == 1 and _options['flat'] \
                        and not _options['merge']:
                    value = list(serialize(value, **_options).values())[0]
                else:
                    # Recurse, get the dict representation
                    _attrs = serialize(value, **_options)

                    # Check if this object should be merged into the parent,
                    # otherwise nest it under the accessor name
                    if _options['merge']:
                        attrs.update(_attrs)
                        continue

                    value = _attrs
            else:
                value = serialize(value, **_options)

        attrs[key] = value

    # Apply post-hook to serialized attributes
    if options['posthook']:
        attrs = options['posthook'](instance, attrs)

    return attrs
1142719
def dict_from_object(obj: object):
    """"""

    # If object is a dict instance, no need to convert.
    return (obj if isinstance(obj, dict)
            else {attr: getattr(obj, attr)
                  for attr in dir(obj) if not attr.startswith('_')})
841147
def get_properties(self, obj):
        """"""
        properties = {}

        for field_name, field in sorted(obj.fields.items()):
            schema = self._get_schema_for_field(obj, field)
            properties[field.name] = schema

        return properties
1336691
def named_objs(objlist, namesdict=None):
    
    objs = OrderedDict()

    if namesdict is not None:
        objtoname = {hashable(v): k for k, v in namesdict.items()}

    for obj in objlist:
        if namesdict is not None and hashable(obj) in objtoname:
            k = objtoname[hashable(obj)]
        elif hasattr(obj, "name"):
            k = obj.name
        elif hasattr(obj, '__name__'):
            k = obj.__name__
        else:
            k = as_unicode(obj)
        objs[k] = obj
    return objs
1024568
def as_dict(self):
        
        out = {}
        for prop in self:
            propval = getattr(self, prop)

            if hasattr(propval, 'for_json'):
                out[prop] = propval.for_json()
            elif isinstance(propval, list):
                out[prop] = [getattr(x, 'for_json', lambda:x)() for x in propval]
            elif isinstance(propval, (ProtocolBase, LiteralValue)):
                out[prop] = propval.as_dict()
            elif propval is not None:
                out[prop] = propval

        return out
205282
function objectSchema(obj) {
  const props = Object.entries(obj).reduce(
    (reduced, [key, val]) => Object.assign(reduced, { [key]: typeof val }),
    {}
  );
  return props;
}
568
def getName(obj):
    
    # elastic search does not like '.' in dict keys, so we replace by /
    def sanitize(name):
        return name.replace(".", "/")
    if isinstance(obj, _BuildStepFactory):
        klass = obj.factory
    else:
        klass = type(obj)
    name = ""
    klasses = (klass, ) + inspect.getmro(klass)
    for klass in klasses:
        if hasattr(klass, "__module__") and klass.__module__.startswith("buildbot."):
            return sanitize(name + klass.__module__ + "." + klass.__name__)
        else:
            name += ">"
    return sanitize(type(obj).__name__)
1261466
def unpack_from_dynamodb(*, attrs, expected, model=None, obj=None, engine=None, context=None, **kwargs):
    """"""
    context = context or {"engine": engine}
    engine = engine or context.get("engine", None)
    if not engine:
        raise ValueError("You must provide engine or a context with an engine.")
    if model is None and obj is None:
        raise ValueError("You must provide a model or obj to unpack.")
    if model is not None and obj is not None:
        raise ValueError("Only specify model or obj.")
    if model:
        obj = model.Meta.init()

    for column in expected:
        value = attrs.get(column.dynamo_name, None)
        value = engine._load(column.typedef, value, context=context, **kwargs)
        setattr(obj, column.name, value)
    return obj
308807
def nameddict(name, props):
    
    class NamedDict(object):
        def __init__(self, *args, **kwargs):
            self.__store = {}.fromkeys(props)
            if args:
                for i, k in enumerate(props[:len(args)]):
                    self[k] = args[i]
            for k, v in kwargs.items():
                self[k] = v

        def __getattr__(self, key):
            # print '+', key
            if key.startswith('_NamedDict__'):
                return self.__dict__[key]
            else:
                return self.__store[key]

        def __setattr__(self, key, value):
            # print '-', key
            if key.startswith('_NamedDict__'):
                object.__setattr__(self, key, value)
            else:
                self.__setitem__(key, value)
                # self.__store[key] = value

        def __getitem__(self, key):
            return self.__store[key]

        def __setitem__(self, key, value):
            if key not in props:
                raise AttributeError("NamedDict(%s) has no attribute %s, avaliables are %s" % (
                    name, key, props))
            self.__store[key] = value

        def __dict__(self):
            return self.__store

        def __str__(self):
            return 'NamedDict(%s: %s)' % (name, str(self.__store))

    return NamedDict
238191
def safe_repr(obj):
    
    name = getattr(obj, '__name__', getattr(obj.__class__, '__name__'))
    if name == 'ndict':
        name = 'dict'
    return name or repr(obj)