Save intermediate FITS objects.
421589
def save_intermediate_img(self, img, name):
        """"""
        if self.intermediate_results:
            img.writeto(name, overwrite=True)
352299
def save(obj, filename, protocol=4):
    

    with open(filename, 'wb') as f:
        pickle.dump(obj, f, protocol=protocol)
583216
def save_json(obj, outfile, allow_nan=True, compression=False):
    """"""
    if compression:
        with open(outfile, 'wb') as f:
            dump(obj, f, allow_nan=allow_nan, compression=compression)
    else:
        with open(outfile, 'w') as f:
            dump(obj, f, allow_nan=allow_nan, compression=compression)
    log.info('Saved {} (id: {}) to {}'.format(type(obj), obj.id, outfile))
121999
function _saveCanvas(ctx, data) {
	var transforms;
	ctx.save();
	transforms = _cloneTransforms(data.transforms);
	data.savedTransforms.push(transforms);
}
681253
def save(self):
        
        l = []
        h = {}
        s = {}
        h_r = {}

        idx = 0
        for i in self.map_list.get_obj():
            length = 0

            if isinstance(i, list):
                for j in i:
                    if isinstance(j, AnnotationsDirectoryItem):
                        if idx % 4 != 0:
                            idx = idx + (4 - (idx % 4))

                    l.append(j)

                    c_length = j.get_length()
                    if isinstance(j, StringDataItem):
                        c_length += 1
                    h[j] = idx + length
                    h_r[idx + length] = j
                    s[idx + length] = c_length

                    length += c_length
                    #debug("SAVE" + str(j) + " @ 0x%x" % (idx+length))

                debug("SAVE " + str(i[0]) + " @0x%x (%x)" % (idx, length))

            else:
                if isinstance(i, MapList):
                    if idx % 4 != 0:
                        idx = idx + (4 - (idx % 4))

                l.append(i)
                h[i] = idx
                h_r[idx] = i

                length = i.get_length()

                s[idx] = length

                debug("SAVE " + str(i) + " @0x%x (%x)" % (idx, length))

            idx += length

        self.header.file_size = idx

        for i in l:
            idx = h[i]
            i.set_off(idx)
            if isinstance(i, CodeItem):
                last_idx = idx
                for j in i.get_obj():
                    j.set_off(last_idx)
                    #j.set_debug_info_off(0)
                    last_idx += j.get_size()

        last_idx = 0
        buff = ""
        for i in l:
            idx = h[i]

            if idx != last_idx:
                debug("Adjust alignment @%x with 00 %x" % (idx, idx - last_idx))
                buff += "\x00" * (idx - last_idx)

            buff += i.get_raw()
            if isinstance(i, StringDataItem):
                buff += "\x00"
            last_idx = idx + s[idx]

        debug("GLOBAL SIZE %d" % len(buff))

        return self.fix_checksums(buff)
816013
def save_ufunc(self, obj):
        """"""
        name = obj.__name__
        numpy_tst_mods = ['numpy', 'scipy.special']
        for tst_mod_name in numpy_tst_mods:
            tst_mod = sys.modules.get(tst_mod_name, None)
            if tst_mod and name in tst_mod.__dict__:
                return self.save_reduce(_getobject, (tst_mod_name, name))
        raise pickle.PicklingError('cannot save %s. Cannot resolve what module it is defined in'
                                   % str(obj))
508741
def save(self, commit=True):
        """"""

        # walk through the document fields
        for field_name, field in iter_valid_fields(self._meta):
            setattr(self.instance, field_name, self.cleaned_data.get(field_name))

        if commit:
            self.instance.save()

        return self.instance
916952
private void saveInlierMatches(ModelMatcher<?, ?> ransac,
								   FastQueue<AssociatedIndex> matches, PairwiseImageGraph2.Motion edge) {

		int N = ransac.getMatchSet().size();
		edge.inliers.reset();
		for (int i = 0; i < N; i++) {
			int idx = ransac.getInputIndex(i);
			edge.inliers.grow().set(matches.get(idx));
		}
	}
1159784
def _compress_obj(obj, level):
    
    return zlib.compress(pickle.dumps(obj, protocol=2), level)
504127
def fit(args, network, data_loader, eval_metrics=None, batch_end_callback=None):
    """"""
    # kvstore
    kv = mx.kvstore.create(args.kv_store)

    # logging
    head = '%(asctime)-15s Node[' + str(kv.rank) + '] %(message)s'
    if 'log_file' in args and args.log_file is not None:
        log_file = args.log_file
        log_dir = args.log_dir
        log_file_full_name = os.path.join(log_dir, log_file)
        if not os.path.exists(log_dir):
            os.mkdir(log_dir)
        logger = logging.getLogger()
        handler = logging.FileHandler(log_file_full_name)
        formatter = logging.Formatter(head)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)
        logger.info('start with arguments %s', args)
    else:
        logging.basicConfig(level=logging.DEBUG, format=head)
        logging.info('start with arguments %s', args)

    # load model
    model_prefix = args.model_prefix
    if model_prefix is not None:
        model_prefix += "-%d" % (kv.rank)
    model_args = {}
    if args.load_epoch is not None:
        assert model_prefix is not None
        tmp = mx.model.FeedForward.load(model_prefix, args.load_epoch)
        model_args = {'arg_params' : tmp.arg_params,
                      'aux_params' : tmp.aux_params,
                      'begin_epoch' : args.load_epoch}
    # save model
    save_model_prefix = args.save_model_prefix
    if save_model_prefix is None:
        save_model_prefix = model_prefix
    checkpoint = None if save_model_prefix is None else mx.callback.do_checkpoint(save_model_prefix)

    # data
    (train, val) = data_loader(args, kv)

    # train
    devs = mx.cpu() if args.gpus is None else [
        mx.gpu(int(i)) for i in args.gpus.split(',')]

    epoch_size = args.num_examples / args.batch_size

    if args.kv_store == 'dist_sync':
        epoch_size /= kv.num_workers
        model_args['epoch_size'] = epoch_size

    if 'lr_factor' in args and args.lr_factor < 1:
        model_args['lr_scheduler'] = mx.lr_scheduler.FactorScheduler(
            step=max(int(epoch_size * args.lr_factor_epoch), 1),
            factor=args.lr_factor)

    if 'clip_gradient' in args and args.clip_gradient is not None:
        model_args['clip_gradient'] = args.clip_gradient

    # disable kvstore for single device
    if 'local' in kv.type and (
            args.gpus is None or len(args.gpus.split(',')) is 1):
        kv = None

    mod = mx.mod.Module(network, context=devs)

    if eval_metrics is None:
        eval_metrics = ['accuracy']
        # TopKAccuracy only allows top_k > 1
        for top_k in [5, 10, 20]:
            eval_metrics.append(mx.metric.create('top_k_accuracy', top_k=top_k))

    if batch_end_callback is not None:
        if not isinstance(batch_end_callback, list):
            batch_end_callback = [batch_end_callback]
    else:
        batch_end_callback = []
    batch_end_callback.append(mx.callback.Speedometer(args.batch_size, 50))

    mod.fit(train_data=train, eval_metric=eval_metrics, eval_data=val, optimizer='sgd',
            optimizer_params={'learning_rate':args.lr, 'momentum': 0.9, 'wd': 0.00001},
            num_epoch=args.num_epochs, batch_end_callback=batch_end_callback,
            initializer=mx.init.Xavier(factor_type="in", magnitude=2.34),
            kvstore=kv, epoch_end_callback=checkpoint, **model_args)
103878
def saveToObject(self):
        """"""
        details = self._component.auto_details()
        for field, widget in self.inputWidgets.items():
            self._component.set(field, widget.value())
        self.attributesSaved.emit(self._component.__class__.__name__, self._component.stateDict())
727595
def _save_fastq_space(items):
    
    to_cleanup = {}
    for data in (utils.to_single_data(x) for x in items):
        for fname in data.get("files", []):
            if os.path.realpath(fname).startswith(dd.get_work_dir(data)):
                to_cleanup[fname] = data["config"]
    for fname, config in to_cleanup.items():
        utils.save_diskspace(fname, "Cleanup prep files after alignment finished", config)
68918
def save(cls, filename, config):
        
        mode = os.O_WRONLY | os.O_TRUNC | os.O_CREAT
        with os.fdopen(os.open(filename, mode, 0o600), 'w') as fname:
            yaml.safe_dump(config, fname, indent=4, default_flow_style=False)
1309077
def save_data(self, idx):
        """"""
        for name in self:
            actual = getattr(self, name)
            diskflag = getattr(self, '_%s_diskflag' % name)
            ramflag = getattr(self, '_%s_ramflag' % name)
            if diskflag:
                file_ = getattr(self, '_%s_file' % name)
                ndim = getattr(self, '_%s_ndim' % name)
                length_tot = 1
                for jdx in range(ndim):
                    length = getattr(self, '_%s_length_%s' % (name, jdx))
                    length_tot *= length
                if ndim:
                    raw = struct.pack(length_tot*'d', *actual.flatten())
                else:
                    raw = struct.pack('d', actual)
                file_.write(raw)
            elif ramflag:
                array = getattr(self, '_%s_array' % name)
                array[idx] = actual
810470
def save_object(filename, obj):
    """"""
    logging.info('saving {}...'.format(filename))
    try:
        with gzip.GzipFile(filename, 'wb') as f:
            f.write(pickle.dumps(obj, 1))
    except Exception as e:
        logging.error('save failure: {}'.format(e))
        raise
429692
def save(self, *args, **kwargs):
        """"""
        objects = self.get_filtered_manager()
        old_pos = getattr(self, '_original_sort_order', None)
        new_pos = self.sort_order

        if old_pos is None and self._unique_togethers_changed():
            self.sort_order = None
            new_pos = None

        try:
            with transaction.atomic():
                self._save(objects, old_pos, new_pos)
        except IntegrityError:
            with transaction.atomic():
                old_pos = objects.filter(pk=self.pk).values_list(
                    'sort_order', flat=True)[0]
                self._save(objects, old_pos, new_pos)

        # Call the "real" save() method.
        super(Orderable, self).save(*args, **kwargs)
577521
def _zip(self) -> ObjectValue:
        """"""
        res = ObjectValue(self.siblings.copy(), self.timestamp)
        res[self.name] = self.value
        return res