Save or update obj as pkl file with name label 

        format can be 'text' or 'pickle'.
964184
def save(self, obj, label, format='text'):
        

        # initialize hidden state directory

        objloc = '{0}/{1}'.format(self.statedir, label)

        with open(objloc, 'w') as fp:
            if format == 'pickle':
                pickle.dump(obj, fp)
            elif format == 'text':
                fp.write(str(obj))
            else:
                print('Format {0} not recognized. Please choose either pickle or text.'.format(format))

        print('Saving {0} to label {1}'.format(obj, label))
67525
def obj_to_file(obj, filename, filetype='auto', ndarray_to_list=False, squeeze=True):
    '''

    '''
    # import json
    # with open(filename, mode='w') as f:
    #    json.dump(annotation,f)
    if ndarray_to_list:
        obj = ndarray_to_list_in_structure(obj, squeeze=squeeze)

    # write to yaml
    d = os.path.dirname(os.path.abspath(filename))
    if not os.path.exists(d):
        os.makedirs(d)

    if filetype == 'auto':
        _, ext = os.path.splitext(filename)
        filetype = ext[1:]

    if filetype in ('yaml', 'yml'):
        # import yaml
        from ruamel.yaml import YAML
        yaml = YAML(typ="unsafe")
        with open(filename, 'wt', encoding="utf-8") as f:
            yaml.dump(obj, f)
        # if sys.version_info.major == 2:
        #     with open(filename, 'wb') as f:
        #         yaml.dump(obj, f, encoding="utf-8")
        # else:
        #     with open(filename, "w", encoding="utf-8") as f:
        #         yaml.dump(obj, f)
    elif filetype in ('pickle', 'pkl'):
        f = open(filename, 'wb')
        logger.info("filename " + filename)
        # if sys.version_info[0] < 3: import cPickle as pickle
        # else: import _pickle as pickle
        import pickle
        pickle.dump(obj, f, -1)
        f.close
    elif filetype in ('streamingpicklezip', 'spklz'):
        # this is not working :-(
        import gzip
        import sPickle as pickle
        f = gzip.open(filename, 'wb', compresslevel=1)
        # f = open(filename, 'wb')
        pickle.s_dump(obj, f)
        f.close
    elif filetype in ('picklezip', 'pklz'):
        import gzip
        if sys.version_info[0] < 3: import cPickle as pickle
        else: import _pickle as pickle
        f = gzip.open(filename, 'wb', compresslevel=1)
        # f = open(filename, 'wb')
        pickle.dump(obj, f)
        f.close
    elif filetype in('mat'):

        import scipy.io as sio
        sio.savemat(filename, obj)
    else:
        logger.error('Unknown filetype ' + filetype)
103960
def save(self, model_fname='model.pkl'):
        
        with open(model_fname, 'wb') as fh:
            pickle.dump(self.stmts, fh, protocol=4)
790657
def update_label(self):
        """"""
        current_file = str(self.selectedFiles()[0])
        if not '.' in current_file.split(os.path.sep)[-1]:
            # add hdf5 extention if none given
            current_file += '.hdf5'
        if os.path.isfile(current_file):
            self.setLabelText(QtGui.QFileDialog.Accept, 'Reload')
        elif os.path.isdir(current_file):
            self.setLabelText(QtGui.QFileDialog.Accept, 'Open')
        else:
            self.setLabelText(QtGui.QFileDialog.Accept, 'Create')
906325
def save_dynamic_class(self, obj):
        
        clsdict = dict(obj.__dict__)  # copy dict proxy to a dict
        if not isinstance(clsdict.get('__dict__', None), property):
            # don't extract dict that are properties
            clsdict.pop('__dict__', None)
            clsdict.pop('__weakref__', None)

        # hack as __new__ is stored differently in the __dict__
        new_override = clsdict.get('__new__', None)
        if new_override:
            clsdict['__new__'] = obj.__new__

        # namedtuple is a special case for Spark where we use the _load_namedtuple function
        if getattr(obj, '_is_namedtuple_', False):
            self.save_reduce(_load_namedtuple, (obj.__name__, obj._fields))
            return

        save = self.save
        write = self.write

        # We write pickle instructions explicitly here to handle the
        # possibility that the type object participates in a cycle with its own
        # __dict__. We first write an empty "skeleton" version of the class and
        # memoize it before writing the class' __dict__ itself. We then write
        # instructions to "rehydrate" the skeleton class by restoring the
        # attributes from the __dict__.
        #
        # A type can appear in a cycle with its __dict__ if an instance of the
        # type appears in the type's __dict__ (which happens for the stdlib
        # Enum class), or if the type defines methods that close over the name
        # of the type, (which is common for Python 2-style super() calls).

        # Push the rehydration function.
        save(_rehydrate_skeleton_class)

        # Mark the start of the args for the rehydration function.
        write(pickle.MARK)

        # On PyPy, __doc__ is a readonly attribute, so we need to include it in
        # the initial skeleton class.  This is safe because we know that the
        # doc can't participate in a cycle with the original class.
        doc_dict = {'__doc__': clsdict.pop('__doc__', None)}

        # Create and memoize an empty class with obj's name and bases.
        save(type(obj))
        save((
            obj.__name__,
            obj.__bases__,
            doc_dict,
        ))
        write(pickle.REDUCE)
        self.memoize(obj)

        # Now save the rest of obj's __dict__. Any references to obj
        # encountered while saving will point to the skeleton class.
        save(clsdict)

        # Write a tuple of (skeleton_class, clsdict).
        write(pickle.TUPLE)

        # Call _rehydrate_skeleton_class(skeleton_class, clsdict)
        write(pickle.REDUCE)
22868
def field_pk_from_json(self, data):
        """"""
        model = get_model(data['app'], data['model'])
        return PkOnlyModel(self, model, data['pk'])
184629
def save_global(self, obj, name=None, pack=struct.pack):
        
        if obj.__module__ == "__builtin__" or obj.__module__ == "builtins":
            if obj in _BUILTIN_TYPE_NAMES:
                return self.save_reduce(_builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj)

        if name is None:
            name = obj.__name__

        modname = getattr(obj, "__module__", None)
        if modname is None:
            try:
                # whichmodule() could fail, see
                # https://bitbucket.org/gutworth/six/issues/63/importing-six-breaks-pickling
                modname = pickle.whichmodule(obj, name)
            except Exception:
                modname = '__main__'

        if modname == '__main__':
            themodule = None
        else:
            __import__(modname)
            themodule = sys.modules[modname]
            self.modules.add(themodule)

        if hasattr(themodule, name) and getattr(themodule, name) is obj:
            return Pickler.save_global(self, obj, name)

        typ = type(obj)
        if typ is not obj and isinstance(obj, (type, _class_type)):
            self.save_dynamic_class(obj)
        else:
            raise pickle.PicklingError("Can't pickle %r" % obj)
832770
def save(cls,instance,filename):
        """"""
        filename = cls.correct_file_extension(filename)
        try:
            with open(filename,'wb') as f:
                pickle.dump(instance,f,protocol=pickle.HIGHEST_PROTOCOL)
        except MemoryError as e:
            print ('{} occurred, will downsampled the saved file by 20.'
                   .format(type(e).__name__))
            copy_instance = instance.copy()
            copy_instance.H = copy_instance.H[::20,:,:]
            copy_instance.Y = copy_instance.Y[::20,:]
            with open(filename,'wb') as f:
                pickle.dump(copy_instance,f,protocol=pickle.HIGHEST_PROTOCOL)
1314264
def save_json(obj, filename, **kwargs):
    

    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(obj, f, **kwargs)
1188824
def save_object(self, obj):
        
        obj.save()
        try:
            save_object(obj, editor=self)
        except DisciplineException:
            pass
871966
def save(self, filename):
        
        import dill

        tmpmodelparams = self.modelparams.copy()
        # fv_extern_src = None
        fv_extern_name = None
        # try:
        #     fv_extern_src = dill.source.getsource(tmpmodelparams['fv_extern'])
        #     tmpmodelparams.pop('fv_extern')
        # except:
        #     pass

        # fv_extern_name = dill.source.getname(tmpmodelparams['fv_extern'])
        if "fv_extern" in tmpmodelparams:
            tmpmodelparams.pop("fv_extern")

        sv = {
            "modelparams": tmpmodelparams,
            "mdl": self.mdl,
            # 'fv_extern_src': fv_extern_src,
            # 'fv_extern_src_name': fv_extern_src_name,
            # 'fv_extern_name': fv_extern_src_name,
            #
        }
        sss = dill.dumps(self.modelparams)
        logger.debug("pickled " + str(sss))

        dill.dump(sv, open(filename, "wb"))
900353
def save_object_to_db(self,
                          obj: Any,
                          table: str,
                          fieldlist: Sequence[str],
                          is_new_record: bool) -> None:
        """"""
        if is_new_record:
            pkvalue = getattr(obj, fieldlist[0])
            if pkvalue is None:
                self.insert_object_into_db_pk_unknown(obj, table, fieldlist)
            else:
                self.insert_object_into_db_pk_known(obj, table, fieldlist)
        else:
            self.update_object_in_db(obj, table, fieldlist)
320026
def _pk(self, obj):
        
        pk_values = tuple(getattr(obj, c.name)
                          for c in obj.__mapper__.primary_key)
        if len(pk_values) == 1:
            return pk_values[0]
        return pk_values
1053163
def dump_pickle(name, obj):
    ''''''
    with open(name,"wb") as f:
        pickle.dump(obj,f,2);
    pass;
881368
def _save(self):
        
        with open(self._pickle_file, 'wb') as source:
            pickler = pickle.Pickler(source, pickle.HIGHEST_PROTOCOL)

            for attribute in self._pickle_attributes:
                attr = getattr(self, attribute, None)
                pickler.dump(attr)
52495
def save_object(self, obj):
        
        obj.pre_save(self.jurisdiction.jurisdiction_id)

        filename = '{0}_{1}.json'.format(obj._type, obj._id).replace('/', '-')

        self.info('save %s %s as %s', obj._type, obj, filename)
        self.debug(json.dumps(OrderedDict(sorted(obj.as_dict().items())),
                              cls=utils.JSONEncoderPlus, indent=4, separators=(',', ': ')))

        self.output_names[obj._type].add(filename)

        with open(os.path.join(self.datadir, filename), 'w') as f:
            json.dump(obj.as_dict(), f, cls=utils.JSONEncoderPlus)

        # validate after writing, allows for inspection on failure
        try:
            obj.validate()
        except ValueError as ve:
            if self.strict_validation:
                raise ve
            else:
                self.warning(ve)

        # after saving and validating, save subordinate objects
        for obj in obj._related:
            self.save_object(obj)
569687
def pickledump(theobject, fname):
    """"""
    fhandle = open(fname, 'wb')
    pickle.dump(theobject, fhandle)