Saves the classifier to `filepath`.
        Because this classifier needs to save the dataset, it must
        be something that can be pickled and not something like an
        iterator.
13249
def save(self, filepath):
        

        if not filepath or not isinstance(filepath, str):
            raise ValueError("Invalid filepath")

        with open(filepath, "wb") as filehandler:
            pickle.dump(self, filehandler)
1064253
def pickFilepath( self ):
        
        mode = self.filepathMode()
        
        filepath = ''
        filepaths = []
        curr_dir = nativestring(self._filepathEdit.text())
        if ( not curr_dir ):
            curr_dir = QDir.currentPath()
        
        if mode == XFilepathEdit.Mode.SaveFile:
            filepath = QFileDialog.getSaveFileName( self,
                                                    self.windowTitle(),
                                                    curr_dir,
                                                    self.filepathTypes() )
                                                    
        elif mode == XFilepathEdit.Mode.OpenFile:
            filepath = QFileDialog.getOpenFileName( self,
                                                    self.windowTitle(),
                                                    curr_dir,
                                                    self.filepathTypes() )
        
        elif mode == XFilepathEdit.Mode.OpenFiles:
            filepaths = QFileDialog.getOpenFileNames( self,
                                                      self.windowTitle(),
                                                      curr_dir,
                                                      self.filepathTypes() )
        
        else:
            filepath = QFileDialog.getExistingDirectory( self,
                                                         self.windowTitle(),
                                                         curr_dir )
        
        if filepath:
            if type(filepath) == tuple:
                filepath = filepath[0]
            self.setFilepath(nativestring(filepath))
        elif filepaths:
            self.setFilepaths(map(str, filepaths))
1191594
private File saveExampleSet(ExampleSet outputSet, String outputDir) throws IOException
	{
		logger.info("");

		//
		//File tmp = File.createTempFile("train", null);
		//tmp.deleteOnExit();
		File tmp = new File(outputDir + "train");

		BufferedWriter out = new BufferedWriter(new FileWriter(tmp));
		outputSet.write(out);
		out.close();

		// add the example set to the model
		//model.add(tmp, "train");

		return tmp;
	}
1121808
def save_features(paths: List[str], datas: List[np.ndarray],
                  compressed: bool = False) -> List:
    
    fnames = []  # type: List[str]
    for path, data in zip(paths, datas):
        fnames.append(save_feature(path, data, compressed))
    return fnames
784910
def save(self, filePath) :
		""""""
		self.filename = filePath
		f = open(filePath, 'w')
		f.write(self.toStr())
		f.flush()
		f.close()
860329
def save_data(self):
        
        if len(self.data.keys()) == 0:
            return

        # Sort everything by episode.
        assert 'episode' in self.data
        sorted_indexes = np.argsort(self.data['episode'])
        sorted_data = {}
        for key, values in self.data.items():
            assert len(self.data[key]) == len(sorted_indexes)
            # We convert to np.array() and then to list to convert from np datatypes to native datatypes.
            # This is necessary because json.dump cannot handle np.float32, for example.
            sorted_data[key] = np.array([self.data[key][idx] for idx in sorted_indexes]).tolist()

        # Overwrite already open file. We can simply seek to the beginning since the file will
        # grow strictly monotonously.
        with open(self.filepath, 'w') as f:
            json.dump(sorted_data, f)
537588
def save(self, path=None, complevel=1, complib='zlib'):
        
        if path is None:
            path = self.hexuid + '.hdf5'
        elif os.path.isdir(path):
            path += os.sep + self.hexuid + '.hdf5'
        elif not (path.endswith('.hdf5') or path.endswith('.hdf')):
            raise ValueError('File path must have a ".hdf5" or ".hdf" extension.')
        with pd.HDFStore(path, 'w', complevel=complevel, complib=complib) as store:
            store['kwargs'] = pd.Series()
            store.get_storer('kwargs').attrs.metadata = self._rel()
            fc = 0    # Field counter (see special handling of fields below)
            for name, data in self._data().items():
                if hasattr(data, '_revert_categories'):
                    data._revert_categories()
                name = name[1:] if name.startswith('_') else name
                if isinstance(data, Field):    # Fields are handled separately
                    fname = 'FIELD{}_'.format(fc) + name + '/'
                    store[fname + 'data'] = pd.DataFrame(data)
                    for i, field in enumerate(data.field_values):
                        ffname = fname + 'values' + str(i)
                        if isinstance(field, pd.Series):
                            store[ffname] = pd.Series(field)
                        else:
                            store[ffname] = pd.DataFrame(field)
                    fc += 1
                elif isinstance(data, Series):
                    s = pd.Series(data)
                    if isinstance(data.dtype, pd.types.dtypes.CategoricalDtype):
                        s = s.astype('O')
                    store[name] = s
                elif isinstance(data, DataFrame):
                    store[name] = pd.DataFrame(data)
                elif isinstance(data, SparseSeries):
                    s = pd.SparseSeries(data)
                    if isinstance(data.dtype, pd.types.dtypes.CategoricalDtype):
                        s = s.astype('O')
                    store[name] = s
                elif isinstance(data, SparseDataFrame):
                    store[name] = pd.SparseDataFrame(data)
                else:
                    if hasattr(data, 'dtype') and isinstance(data.dtype, pd.types.dtypes.CategoricalDtype):
                        data = data.astype('O')
                    else:
                        for col in data:
                            if isinstance(data[col].dtype, pd.types.dtypes.CategoricalDtype):
                                data[col] = data[col].astype('O')
                    store[name] = data
                if hasattr(data, '_set_categories'):
                    data._set_categories()
846424
def save(self, path):
        
        path = os.path.expandvars(os.path.expanduser(path))
        with open(path, "wb") as f:
            pickle.dump(self.roots, f)
972196
def save(self, filepath = None, password = None, keyfile = None):
        
        
        if (password is None and keyfile is not None and keyfile != "" and
            type(keyfile) is str):
            self.keyfile = keyfile
        elif (keyfile is None and password is not None and password != "" and
              type(password is str)):
            self.password = password
        elif (keyfile is not None and password is not None and
              keyfile != "" and password != "" and type(keyfile) is str and
              type(password) is str):
            self.keyfile = keyfile
            self.password = password

        if self.read_only:
            raise KPError("The database has been opened read-only.")
        elif ((self.password is None and self.keyfile is None) or 
              (filepath is None and self.filepath is None) or 
              (keyfile == "" and password == "")):
            raise KPError("Need a password/keyfile and a filepath to save the "
                          "file.")
        elif ((type(self.filepath) is not str and self.filepath is not None) or
              (type(self.password) is not str and self.password is not None) or
              (type(self.keyfile) is not str and self.keyfile is not None)):
            raise KPError("filepath, password and keyfile  must be strings.")
        elif self._num_groups == 0:
            raise KPError("Need at least one group!")
        
        content = bytearray()

        # First, read out all groups
        for i in self.groups:
            # Get the packed bytes
            # j stands for a possible field type
            for j in range(1, 10):
                ret_save = self._save_group_field(j, i)
                # The field type and the size is always in front of the data
                if ret_save is not False:
                    content += struct.pack('<H', j)
                    content += struct.pack('<I', ret_save[0])
                    content += ret_save[1]
            # End of field
            content += struct.pack('<H', 0xFFFF)
            content += struct.pack('<I', 0) 

        # Same with entries
        for i in self.entries:
            for j in range(1, 15):
                ret_save = self._save_entry_field(j, i)
                if ret_save is not False:
                    content += struct.pack('<H', j)
                    content += struct.pack('<I', ret_save[0])
                    content += ret_save[1]
            content += struct.pack('<H', 0xFFFF)
            content += struct.pack('<I', 0)

        # Generate new seed and new vector; calculate the new hash
        Random.atfork()
        self._final_randomseed = Random.get_random_bytes(16)
        self._enc_iv = Random.get_random_bytes(16)
        sha_obj = SHA256.new()
        sha_obj.update(bytes(content))
        self._contents_hash = sha_obj.digest()
        del sha_obj

        # Pack the header
        header = bytearray()
        header += struct.pack('<I', 0x9AA2D903)
        header += struct.pack('<I', 0xB54BFB65)
        header += struct.pack('<I', self._enc_flag)
        header += struct.pack('<I', self._version)
        header += struct.pack('<16s', self._final_randomseed)
        header += struct.pack('<16s', self._enc_iv)
        header += struct.pack('<I', self._num_groups)
        header += struct.pack('<I', self._num_entries)
        header += struct.pack('<32s', self._contents_hash)
        header += struct.pack('<32s', self._transf_randomseed)
        if self._key_transf_rounds < 150000:
            self._key_transf_rounds = 150000
        header += struct.pack('<I', self._key_transf_rounds)

        # Finally encrypt everything...
        if self.password is None:
            masterkey = self._get_filekey()
        elif self.password is not None and self.keyfile is not None:
            passwordkey = self._get_passwordkey()
            filekey = self._get_filekey()
            sha = SHA256.new()
            sha.update(passwordkey+filekey)
            masterkey = sha.digest()
        else:
            masterkey = self._get_passwordkey()
        final_key = self._transform_key(masterkey)
        encrypted_content = self._cbc_encrypt(content, final_key)
        del content
        del masterkey
        del final_key
        
        # ...and write it out
        if filepath is not None:
            try:
                handler = open(filepath, "wb")
            except IOError:
                raise KPError("Can't open {0}".format(filepath))
            if self.filepath is None:
                self.filepath = filepath
        elif filepath is None and self.filepath is not None:
            try:
                handler = open(self.filepath, "wb")
            except IOError:
                raise KPError("Can't open {0}".format(self.filepath))
        else:
            raise KPError("Need a filepath.")

        try:
            handler.write(header+encrypted_content)
        except IOError:
            raise KPError("Can't write to file.")
        finally:
            handler.close()
        
        if not path.isfile(self.filepath+".lock"):
            try:
                lock = open(self.filepath+".lock", "w")
                lock.write('')
            except IOError:
                raise KPError("Can't create lock-file {0}".format(self.filepath
                                                                  +".lock"))
            else:
                lock.close()
        return True
462927
def save(self, writer=None):
        

        if self.path is None:
            raise ValueError('No path given to save the data set.')

        self.save_at(self.path, writer)
820519
def __load(self, path):
        """"""
        try:
            path = os.path.abspath(path)
            with open(path, 'rb') as df:
                # loaded_dataset = pickle.load(df)
                self.__data, self.__classes, self.__labels, \
                self.__dtype, self.__description, \
                self.__num_features, self.__feature_names = pickle.load(df)

            # ensure the loaded dataset is valid
            self.__validate(self.__data, self.__classes, self.__labels)

        except IOError as ioe:
            raise IOError('Unable to read the dataset from file: {}', format(ioe))
        except:
            raise
249
def save(self, filename):
        

        with open(filename, 'wb') as savefile:
            pickle.dump(self.__dict__,
                        savefile,
                        protocol=pickle.HIGHEST_PROTOCOL)
367491
def save(self, path):
        
        f = h5py.File(path, 'w')
        try:
            fm_group = f.create_group('Datamat')
            for field in self.fieldnames():
                try:
                    fm_group.create_dataset(field, data = self.__dict__[field])
                except (TypeError,) as e:
                    # Assuming field is an object array that contains dicts which
                    # contain numpy arrays as values
                    sub_group = fm_group.create_group(field)
                    for i, d in enumerate(self.__dict__[field]):
                        index_group = sub_group.create_group(str(i))
                        print((field, d))
                        for key, value in list(d.items()):
                            index_group.create_dataset(key, data=value)

            for param in self.parameters():
                fm_group.attrs[param]=self.__dict__[param]
        finally:
            f.close()
377252
def save_analysis(self, filepath=None, **kwargs):
        
        # We pass a copy of the analysis attribute dictionary.
        dict_obj = deepcopy(self.analysis_output)
        # If no filepath is provided we create one.
        if filepath is None:
            filepath = "_".join(
                (str(self.system_id), "pywindow_analysis")
            )
            filepath = '/'.join((os.getcwd(), filepath))
        # Dump the dictionary to json file.
        Output().dump2json(dict_obj, filepath, default=to_list, **kwargs)
        return
1229604
def copy_file(self, filepath):
        
        copy_file = False
        try:
            copy_file = self.data[filepath]['copy']
        except KeyError:
            return False
        return copy_file
1088696
def save_dataset(self, dataset_id, filename=None, writer=None, overlay=None, compute=True, **kwargs):
        """"""
        if writer is None and filename is None:
            writer = 'geotiff'
        elif writer is None:
            writer = self.get_writer_by_ext(os.path.splitext(filename)[1])

        writer, save_kwargs = load_writer(writer,
                                          ppp_config_dir=self.ppp_config_dir,
                                          filename=filename,
                                          **kwargs)
        return writer.save_dataset(self[dataset_id],
                                   overlay=overlay, compute=compute,
                                   **save_kwargs)
1024924
def save_datasets(self, datasets, filename=None, **kwargs):
        """"""
        logger.info('Saving datasets to NetCDF4/CF.')
        # XXX: Should we combine the info of all datasets?
        filename = filename or self.get_filename(**datasets[0].attrs)
        datas, start_times, end_times = self._collect_datasets(datasets, kwargs)

        dataset = xr.Dataset(datas)
        try:
            dataset['time_bnds'] = make_time_bounds(dataset,
                                                    start_times,
                                                    end_times)
            dataset['time'].attrs['bounds'] = "time_bnds"
        except KeyError:
            logger.warning('No time dimension in datasets, skipping time bounds creation.')

        header_attrs = kwargs.pop('header_attrs', None)

        if header_attrs is not None:
            dataset.attrs.update({k: v for k, v in header_attrs.items() if v})

        dataset.attrs['history'] = ("Created by pytroll/satpy on " +
                                    str(datetime.utcnow()))
        dataset.attrs['conventions'] = 'CF-1.7'
        engine = kwargs.pop("engine", 'h5netcdf')
        for key in list(kwargs.keys()):
            if key not in ['mode', 'format', 'group', 'encoding', 'unlimited_dims', 'compute']:
                kwargs.pop(key, None)
        return dataset.to_netcdf(filename, engine=engine, **kwargs)