Converts Python object to Weld object.

        Args:
            obj: Python object that needs to be converted to Weld format

        Returns:
            Weld formatted object
964752
def encode(self, obj):
        
        if isinstance(obj, np.ndarray):
            if obj.ndim == 1 and obj.dtype == 'int16':
                numpy_to_weld = self.utils.numpy_to_weld_int16_arr
            elif obj.ndim == 1 and obj.dtype == 'int32':
                numpy_to_weld = self.utils.numpy_to_weld_int_arr
            elif obj.ndim == 1 and obj.dtype == 'int64':
                numpy_to_weld = self.utils.numpy_to_weld_long_arr
            elif obj.ndim == 1 and obj.dtype == 'float32':
                numpy_to_weld = self.utils.numpy_to_weld_float_arr
            elif obj.ndim == 1 and obj.dtype == 'float64':
                numpy_to_weld = self.utils.numpy_to_weld_double_arr
            elif obj.ndim == 2 and obj.dtype == 'int16':
                numpy_to_weld = self.utils.numpy_to_weld_int16_arr_arr
            elif obj.ndim == 2 and obj.dtype == 'int32':
                numpy_to_weld = self.utils.numpy_to_weld_int_arr_arr
            elif obj.ndim == 2 and obj.dtype == 'int64':
                numpy_to_weld = self.utils.numpy_to_weld_long_arr_arr
            elif obj.ndim == 2 and obj.dtype == 'float32':
                numpy_to_weld = self.utils.numpy_to_weld_float_arr_arr
            elif obj.ndim == 2 and obj.dtype == 'float64':
                numpy_to_weld = self.utils.numpy_to_weld_double_arr_arr
            elif obj.ndim == 2 and obj.dtype == 'bool':
                numpy_to_weld = self.utils.numpy_to_weld_bool_arr_arr
            elif obj.ndim == 1 and obj.dtype == 'bool':
                numpy_to_weld = self.utils.numpy_to_weld_bool_arr
            else:
                numpy_to_weld = self.utils.numpy_to_weld_char_arr_arr
        elif isinstance(obj, str):
            numpy_to_weld = self.utils.numpy_to_weld_char_arr
        else:
            raise Exception("Unable to encode; invalid object type")

        numpy_to_weld.restype = self.py_to_weld_type(obj).ctype_class
        numpy_to_weld.argtypes = [py_object]
        weld_vec = numpy_to_weld(obj)
        return weld_vec
1238831
def pprint(obj, file_=None):
    

    if file_ is None:
        file_ = sys.stdout

    # functions, methods
    if callable(obj) and hasattr(obj, "_code"):
        obj._code.pprint(file_)
        return

    # classes
    if isinstance(obj, type) and hasattr(obj, "_constructors"):
        constructors = obj._constructors
        for names, func in sorted(constructors.items()):
            func._code.pprint(file_)
        return

    raise TypeError("unkown type")
773921
def value_to_string(self, obj):
        
        statefield = self.to_python(self.value_from_object(obj))
        return statefield.state.name
1017431
def POINTER(obj):
    

    p = ctypes.POINTER(obj)
    if not isinstance(p.from_param, classmethod):
        def from_param(cls, x):
            if x is None:
                return cls()
            else:
                return x
        p.from_param = classmethod(from_param)

    return p
388333
def weld_count(array):
    
    obj_id, weld_obj = create_weld_object(array)

    weld_template = _weld_count_code

    weld_obj.weld_code = weld_template.format(array=obj_id)

    return weld_obj
164422
def _make_object_dict(self, obj):
        
        data = {}
        for attr in dir(obj):
            if attr[0] is not '_' and attr is not 'status':
                datum = getattr(obj, attr)
                if not isinstance(datum, types.MethodType):
                    data.update(self._handle_object(attr,datum))
        return data
823877
def as_ppmodel(cls, obj):
        
        if isinstance(obj, cls):
            return obj

        # obj is a string
        if ":" not in obj:
            mode, plasmon_freq = obj, None
        else:
            # Extract mode and plasmon_freq
            mode, plasmon_freq = obj.split(":")
            try:
                plasmon_freq = float(plasmon_freq)
            except ValueError:
                plasmon_freq, unit = plasmon_freq.split()
                plasmon_freq = units.Energy(float(plasmon_freq), unit).to("Ha")

        return cls(mode=mode, plasmon_freq=plasmon_freq)
998734
def json_dumps(cls, obj, **kwargs):
        
        if 'cls' not in kwargs:
            kwargs['cls'] = cls.json_encoder
        return json.dumps(obj, **kwargs)
1137405
def _to_component(obj, allow_hierarchy=True):
    

    def _to_str(obj):
        return "{}:{}".format(obj.kind, obj.component)

    if isinstance(obj, str):
        # TODO: check to see if valid?, use allow_hierarchy
        # TODO: when passed labels this is going to give the wrong thing, but that might be fixable in the HierarchyParameter set_value check
        #~ raise NotImplementedError # need to get object from bundle and pass to _to_str
        return obj
    elif isinstance(obj, ParameterSet):
        # TODO: be smarter about this and don't assume only 1 will be returned
        if 'repr' in obj.to_flat_dict().keys():
            return obj.get_value(qualifier='repr')

        else:
            # make sure we only have things in the 'component' context
            obj = obj.filter(context='component')
            return _to_str(obj)

    elif isinstance(obj, Parameter):
        if obj.qualifier == 'repr':
            return obj.get_value()
        else:
            return _to_str(obj)

    else:
        raise NotImplementedError("could not parse {}".format(obj))
969297
def encode(obj):
    
    if hasattr(obj, 'json'):
        return obj.json
    if hasattr(obj, '__json__'):
        return obj.__json__()
    return dumps(obj)
610096
def class_to_str(obj):
    
    mod_str = obj.__module__
    name_str = obj.__name__
    if mod_str == '__main__':
        return name_str
    else:
        return '.'.join([mod_str, name_str])
805116
def convert(self, obj):
        
        if self.pristine_if_invalid:
            raise NotImplementedError('pristine_if_invalid option is not supported yet')

        nex = get_nexml_el(obj)
        assert nex
        # Create the new objects as locals. This section should not
        #   mutate obj, so that if there is an exception the object
        #   is unchanged on the error exit
        otusById = nex['otusById']
        otusElementOrder = nex['^ot:otusElementOrder']
        otus = self.convert_otus(otusById, otusElementOrder)
        nex['otus'] = otus
        treesById = nex['treesById']
        treesElementOrder = nex['^ot:treesElementOrder']
        trees = self.convert_trees(treesById, treesElementOrder)
        # add the locals to the object
        nex['trees'] = trees
        nex['@nexml2json'] = str(DIRECT_HONEY_BADGERFISH)
        # Make the struct leaner
        if self.remove_old_structs:
            del nex['otusById']
            del nex['^ot:otusElementOrder']
            del nex['treesById']
            del nex['^ot:treesElementOrder']
        return obj
1084362
def to_json(obj):
    
    try:
        return json.dumps(obj, default=lambda obj: {k.lower(): v for k, v in obj.__dict__.items()},
                          sort_keys=False, separators=(',', ':')).encode()
    except Exception as e:
        logger.info("to_json: ", e, obj)
566942
def format_object_attrs(obj):
    
    attrs = []
    if hasattr(obj, 'dtype'):
        attrs.append(('dtype', "'{}'".format(obj.dtype)))
    if getattr(obj, 'name', None) is not None:
        attrs.append(('name', default_pprint(obj.name)))
    max_seq_items = get_option('display.max_seq_items') or len(obj)
    if len(obj) > max_seq_items:
        attrs.append(('length', len(obj)))
    return attrs
1177925
function weld (keys, values) {
  var object = {}
  for (var i = keys.length - 1; i >= 0; i--) object[keys[i]] = values[i]
  return object
}
1176226
def _format_obj(self, item=None):
        
        # Order here matters, odd behavior with tuples
        if item is None:
            return getattr(self, 'number')(item)
        elif isinstance(item, self.str_):
            #: String
            return item + " "
        elif isinstance(item, bytes):
            #: Bytes
            return getattr(self, 'bytes')(item)
        elif isinstance(item, self.numeric_):
            #: Float, int, etc.
            return getattr(self, 'number')(item)
        elif isinstance(item, self.dict_):
            #: Dict
            return getattr(self, 'dict')(item)
        elif isinstance(item, self.list_):
            #: List
            return getattr(self, 'list')(item)
        elif isinstance(item, tuple):
            #: Tuple
            return getattr(self, 'tuple')(item)
        elif isinstance(item, types.GeneratorType):
            #: Generator
            return getattr(self, 'generator')(item)
        elif isinstance(item, self.set_):
            #: Set
            return getattr(self, 'set')(item)
        elif isinstance(item, deque):
            #: Deque
            return getattr(self, 'deque')(item)
        elif isinstance(item, Sequence):
            #: Sequence
            return getattr(self, 'sequence')(item)
        #: Any other object
        return getattr(self, 'object')(item)
1180445
def _object_contents(obj):
    
    try:
        # Test if obj is a method.
        return _function_contents(obj.__func__)

    except AttributeError:
        try:
            # Test if obj is a callable object.
            return _function_contents(obj.__call__.__func__)

        except AttributeError:
            try:
                # Test if obj is a code object.
                return _code_contents(obj)

            except AttributeError:
                try:
                    # Test if obj is a function object.
                    return _function_contents(obj)

                except AttributeError as ae:
                    # Should be a pickle-able Python object.
                    try:
                        return _object_instance_content(obj)
                        # pickling an Action instance or object doesn't yield a stable
                        # content as instance property may be dumped in different orders
                        # return pickle.dumps(obj, ACTION_SIGNATURE_PICKLE_PROTOCOL)
                    except (pickle.PicklingError, TypeError, AttributeError) as ex:
                        # This is weird, but it seems that nested classes
                        # are unpickable. The Python docs say it should
                        # always be a PicklingError, but some Python
                        # versions seem to return TypeError.  Just do
                        # the best we can.
                        return bytearray(repr(obj), 'utf-8')