Save dictionary in a single file .spydata file
427501
def save_dictionary(data, filename):
    """"""
    filename = osp.abspath(filename)
    old_cwd = getcwd()
    os.chdir(osp.dirname(filename))
    error_message = None
    skipped_keys = []
    data_copy = {}

    try:
        # Copy dictionary before modifying it to fix #6689
        for obj_name, obj_value in data.items():
            # Skip modules, since they can't be pickled, users virtually never
            # would want them to be and so they don't show up in the skip list.
            # Skip callables, since they are only pickled by reference and thus
            # must already be present in the user's environment anyway.
            if not (callable(obj_value) or isinstance(obj_value,
                                                      types.ModuleType)):
                # If an object cannot be deepcopied, then it cannot be pickled.
                # Ergo, we skip it and list it later.
                try:
                    data_copy[obj_name] = copy.deepcopy(obj_value)
                except Exception:
                    skipped_keys.append(obj_name)
        data = data_copy
        if not data:
            raise RuntimeError('No supported objects to save')

        saved_arrays = {}
        if load_array is not None:
            # Saving numpy arrays with np.save
            arr_fname = osp.splitext(filename)[0]
            for name in list(data.keys()):
                try:
                    if isinstance(data[name],
                                  np.ndarray) and data[name].size > 0:
                        # Save arrays at data root
                        fname = __save_array(data[name], arr_fname,
                                             len(saved_arrays))
                        saved_arrays[(name, None)] = osp.basename(fname)
                        data.pop(name)
                    elif isinstance(data[name], (list, dict)):
                        # Save arrays nested in lists or dictionaries
                        if isinstance(data[name], list):
                            iterator = enumerate(data[name])
                        else:
                            iterator = iter(list(data[name].items()))
                        to_remove = []
                        for index, value in iterator:
                            if isinstance(value,
                                          np.ndarray) and value.size > 0:
                                fname = __save_array(value, arr_fname,
                                                     len(saved_arrays))
                                saved_arrays[(name, index)] = (
                                    osp.basename(fname))
                                to_remove.append(index)
                        for index in sorted(to_remove, reverse=True):
                            data[name].pop(index)
                except (RuntimeError, pickle.PicklingError, TypeError,
                        AttributeError, IndexError):
                    # If an array can't be saved with numpy for some reason,
                    # leave the object intact and try to save it normally.
                    pass
            if saved_arrays:
                data['__saved_arrays__'] = saved_arrays

        pickle_filename = osp.splitext(filename)[0] + '.pickle'
        # Attempt to pickle everything.
        # If pickling fails, iterate through to eliminate problem objs & retry.
        with open(pickle_filename, 'w+b') as fdesc:
            try:
                pickle.dump(data, fdesc, protocol=2)
            except (pickle.PicklingError, AttributeError, TypeError,
                    ImportError, IndexError, RuntimeError):
                data_filtered = {}
                for obj_name, obj_value in data.items():
                    try:
                        pickle.dumps(obj_value, protocol=2)
                    except Exception:
                        skipped_keys.append(obj_name)
                    else:
                        data_filtered[obj_name] = obj_value
                if not data_filtered:
                    raise RuntimeError('No supported objects to save')
                pickle.dump(data_filtered, fdesc, protocol=2)

        # Use PAX (POSIX.1-2001) format instead of default GNU.
        # This improves interoperability and UTF-8/long variable name support.
        with tarfile.open(filename, "w", format=tarfile.PAX_FORMAT) as tar:
            for fname in ([pickle_filename]
                          + [fn for fn in list(saved_arrays.values())]):
                tar.add(osp.basename(fname))
                os.remove(fname)
    except (RuntimeError, pickle.PicklingError, TypeError) as error:
        error_message = to_text_string(error)
    else:
        if skipped_keys:
            skipped_keys.sort()
            error_message = ('Some objects could not be saved: '
                             + ', '.join(skipped_keys))
    finally:
        os.chdir(old_cwd)
    return error_message
58373
def _contigs_dict_to_file(self, contigs, fname):
        ''''''
        f = pyfastaq.utils.open_file_write(fname)
        for contig in sorted(contigs, key=lambda x:len(contigs[x]), reverse=True):
            print(contigs[contig], file=f)
        pyfastaq.utils.close(f)
938931
function writeDictionary( dictionary, errBuf ) {
	var writeSuccess = true,
		dict = new Dictionary();

	dict.dictionary = dictionary;
	dict.compile();

	Object.keys( dict.getAll() ).forEach( function( localeID ){
		var locale = dict.getLocale( localeID ),
			localePath = path.join( dictionary.meta.dest, localeID );

		if ( !fs.existsSync( localePath ) ) {
			mkdirp.sync( localePath );
			fs.writeFileSync(
				path.join( localePath, 'messages.json' ),
				JSON.stringify( locale, null, 2 )
			);
		} else {
			errBuf.push( 'Error (dest): directory "' + localePath + '" is not empty!' );
			writeSuccess = false;
		} // if..else
	});

	return writeSuccess;
}
499398
def _save( self, fn ):
        """"""

        # create JSON object
        j = json.dumps({ 'description': self.description(),
                         'pending': self._pending,
                         'results': self._results },
                       indent = 4,
                       cls = MetadataEncoder)

        # write to file
        with open(fn, 'w') as f:
            f.write(j)
678708
def update_data(func):
    
    default = dict([
        (param.name, param.default)
        for param in inspect.signature(func).parameters.values()
        if param.default != getattr(inspect, '_empty')
    ])

    @wraps(func)
    def wrapper(*args, **kwargs):

        default.update(kwargs)
        kwargs.update(default)
        cur_mod = sys.modules[func.__module__]
        logger = logs.get_logger(name_or_func=f'{cur_mod.__name__}.{func.__name__}', types='stream')

        root_path = cur_mod.DATA_PATH
        date_type = kwargs.pop('date_type', 'date')
        save_static = kwargs.pop('save_static', True)
        save_dynamic = kwargs.pop('save_dynamic', True)
        symbol = kwargs.get('symbol')
        file_kw = dict(func=func, symbol=symbol, root=root_path, date_type=date_type)
        d_file = cache_file(has_date=True, **file_kw)
        s_file = cache_file(has_date=False, **file_kw)

        cached = kwargs.pop('cached', False)
        if cached and save_static and files.exists(s_file):
            logger.info(f'Reading data from {s_file} ...')
            return pd.read_parquet(s_file)

        data = func(*args, **kwargs)

        if save_static:
            files.create_folder(s_file, is_file=True)
            save_data(data=data, file_fmt=s_file, append=False)
            logger.info(f'Saved data file to {s_file} ...')

        if save_dynamic:
            drop_dups = kwargs.pop('drop_dups', None)
            files.create_folder(d_file, is_file=True)
            save_data(data=data, file_fmt=d_file, append=True, drop_dups=drop_dups)
            logger.info(f'Saved data file to {d_file} ...')

        return data

    return wrapper
700256
def parse_stats_file(self, file_name):
        
        stats = {}
        try:
            with open(file_name, "r") as fhandle:
                fbuffer = []
                save_buffer = False
                for line in fhandle:
                    line = line.rstrip("\n")
                    line = self._trim(line)
                    if line == "" or line.startswith("#"):
                        continue
                    elif line.endswith("{"):
                        save_buffer = True
                        fbuffer.append(line)
                        continue
                    elif line.endswith("}"):
                        tmp_dict = self._parse_config_buffer(fbuffer)
                        fbuffer = None
                        fbuffer = list()
                        if len(tmp_dict) < 1:
                            continue

                        if tmp_dict["_type"] == "info":
                            stats["info"] = tmp_dict
                        elif tmp_dict["_type"] == "programstatus":
                            stats["programstatus"] = tmp_dict
                        else:
                            entity_type = tmp_dict["_type"]
                            if entity_type not in stats.keys():
                                stats[entity_type] = []

                            stats[entity_type].append(tmp_dict)

                        continue
                    elif save_buffer is True:
                        fbuffer.append(line)

        except Exception as exception:
            self.log.info("Caught exception: %s", exception)

        return stats
1276625
def save(filename=ConfigPath):
    """"""
    default_values = defaults()
    parser = configparser.RawConfigParser()
    parser.optionxform = str # Force case-sensitivity on names
    try:
        save_types = basestring, int, float, tuple, list, dict, type(None)
        for k, v in sorted(globals().items()):
            if not isinstance(v, save_types) or k.startswith("_") \
            or default_values.get(k, parser) == v: continue # for k, v
            try: parser.set("DEFAULT", k, json.dumps(v))
            except Exception: pass
        if parser.defaults():
            with open(filename, "wb") as f:
                f.write("# %s %s configuration written on %s.\n" % (Title, Version,
                        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
                parser.write(f)
        else: # Nothing to write: delete configuration file
            try: os.unlink(filename)
            except Exception: pass
    except Exception:
        logging.warn("Error writing config to %s.", filename, exc_info=True)
243691
def load_data(self, filename, ext):
        """"""
        from spyder_kernels.utils.iofuncs import iofunctions
        from spyder_kernels.utils.misc import fix_reference_name

        glbs = self._mglobals()

        load_func = iofunctions.load_funcs[ext]
        data, error_message = load_func(filename)

        if error_message:
            return error_message

        for key in list(data.keys()):
            new_key = fix_reference_name(key, blacklist=list(glbs.keys()))
            if new_key != key:
                data[new_key] = data.pop(key)

        try:
            glbs.update(data)
        except Exception as error:
            return str(error)

        return None
500394
def save_pstat(self, path):
        
        stats = {}
        for s in self.stats:
            if not s.exclude:
                stats.update(s.to_dict())

        with open(path, 'wb') as f:
            marshal.dump(stats, f)
185406
def save(self, filename=None, debug=False):
        """"""
        if not filename: filename = self.name
        with open(filename, "w") as f: # save config data file
            f.write(self.toJson(self.attrs))
        if self.debug or debug:
            print("saved configuration %s"%(self.name))
            for k,v in sorted(iteritems(self.attrs)):
                print("%15s : %s"%(k,v))
1072080
def _save(self):
        
        # See Issue 1086 and 1242 for background on why this
        # method contains all the exception handling.
        fname = self.filename()

        def _write_file(fname):
            if PY2:
                # Python 2
                with codecs.open(fname, 'w', encoding='utf-8') as configfile:
                    self._write(configfile)
            else:
                # Python 3
                with open(fname, 'w', encoding='utf-8') as configfile:
                    self.write(configfile)

        try:  # the "easy" way
            _write_file(fname)
        except EnvironmentError:
            try:  # the "delete and sleep" way
                if osp.isfile(fname):
                    os.remove(fname)
                time.sleep(0.05)
                _write_file(fname)
            except Exception as e:
                print("Failed to write user configuration file to disk, with "
                      "the exception shown below")  # spyder: test-skip
                print(e)
145001
def _save_pys(self, filepath):
        

        try:
            with Bz2AOpen(filepath, "wb",
                          main_window=self.main_window) as outfile:
                interface = Pys(self.grid.code_array, outfile)
                interface.from_code_array()

        except (IOError, ValueError), err:
            try:
                post_command_event(self.main_window, self.StatusBarMsg,
                                   text=err)
                return
            except TypeError:
                # The main window does not exist any more
                pass

        return not outfile.aborted
31229
def _update_sub_file_dict(self, sub_files):
        """"""
        sub_files.file_dict.clear()
        for job_details in self.jobs.values():
            if job_details.file_dict is not None:
                sub_files.update(job_details.file_dict)
            if job_details.sub_file_dict is not None:
                sub_files.update(job_details.sub_file_dict)
682268
def save(self, filename=None):
        """"""
        if self.__fname is None and filename is None:
            raise ValueError('Config loaded from string, no filename specified')
        conf = self.__config
        cpa = dict_to_cp(conf)
        with open(self.__fname if filename is None else filename, 'w') as f:
            cpa.write(f)
891651
def save_key_file(self):
        """"""
        if self.client_key is None:
            return

        if self.key_file_path:
            key_file_path = self.key_file_path
        else:
            key_file_path = self._get_key_file_path()

        logger.debug('save keyfile to %s', key_file_path);

        with open(key_file_path, 'w+') as f:
            raw_data = f.read()
            key_dict = {}

            if raw_data:
                key_dict = json.loads(raw_data)

            key_dict[self.ip] = self.client_key

            f.write(json.dumps(key_dict))
686043
def store(self):
        
        with open(self.filename, "wb") as f:
            pickle.dump(self, f)
1228024
def save(yaml_dict, filepath):
    '''
    
    '''
    yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)