Non blocking save file,
 Pre: file exists before calling
 Post: 'url' written to 'file'
164855
def save(file)
          if File.exists? file
            fail "#{file} already exists. Skipping..."
          elsif Dir.exists? file
            fail "#{file} is a directory"
          else
            directory = file.split(File::SEPARATOR)[0...-1].join(File::SEPARATOR)
            FileUtils.mkpath directory unless Dir.exists? directory
      
            callback do |response|
              inc_writes
              EM::File::write(file, response) do |length|
                @@log.info "Saving: #{file} (#{length / 1024}KiB)"
                dec_writes  
              end
            end
            get
          end
       self # Fluent interface
      end
1229856
def save(self, filename, callback=_noop_callback):
        
        with open(filename, 'wb') as fp:
            self._save(fp, callback)
827021
def save_file
      raise ArgumentError, 'Need a Path to save the file' if @path.nil?

      File.open(@path, 'w') { |file| file.write(to_s) }
    end
444780
def save(self, *args, **kwargs):
        
        if not self.pk and not self.slug:
            self.slug = self.generate_slug()

        if self.__original_file and self.file != self.__original_file:
            self.delete_real_file(self.__original_file)

        file_changed = True
        if self.pk:
            new_value = getattr(self, 'file')
            if hasattr(new_value, "file"):
                file_changed = isinstance(new_value.file, UploadedFile)
        else:
            self.cbversion = 0

        if file_changed:
            self.user_filename = os.path.basename(self.file.name)
            self.cbversion = self.cbversion + 1

        if not self.title:
            self.title = self.user_filename

        super(AssetBase, self).save(*args, **kwargs)

        if file_changed:
            signals.file_saved.send(self.file.name)
            utils.update_cache_bust_version(self.file.url, self.cbversion)
            self.reset_crops()

        if self.__original_file and self.file.name != self.__original_file.name:
            with manager.SwitchSchemaManager(None):
                for related in self.__class__._meta.get_all_related_objects(
                        include_hidden=True):
                    field = related.field
                    if getattr(field, 'denormalize', None):
                        cname = field.get_denormalized_field_name(field.name)
                        if getattr(field, 'denormalize'):
                            related.model.objects.filter(**{
                                field.name: self.pk
                            }).update(**{
                                cname: self.file.name
                            })
858070
def before_save(file_or_dir):
    
    dir_name = os.path.dirname(os.path.abspath(file_or_dir))
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)
1204321
def save(title='Save', parent=None, current_name='', folder=None,
         _before_run=None, _before_overwrite=None):
    """"""
    filechooser = gtk.FileChooserDialog(title, parent,
                                        gtk.FILE_CHOOSER_ACTION_SAVE,
                                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                         gtk.STOCK_SAVE, gtk.RESPONSE_OK))
    if current_name:
        filechooser.set_current_name(current_name)
    filechooser.set_default_response(gtk.RESPONSE_OK)

    if folder:
        filechooser.set_current_folder(folder)

    path = None
    while True:
        if _before_run:
            _before_run(filechooser)
            _before_run = None  # XXX: find better implications
        response = filechooser.run()
        if response != gtk.RESPONSE_OK:
            path = None
            break

        path = filechooser.get_filename()
        if not os.path.exists(path):
            break

        if ask_overwrite(path, parent, _before_run=_before_overwrite):
            break
        _before_overwrite = None  # XXX: same
    _destroy(filechooser)
    return path
677834
def post(path, doc = nil, options = {}, &block)
      execute('POST', path, options, doc, &block)
    end
441761
function save(callback) {
            var model, request;

            model = this;

            this.constructor.dispatch('beforeSave', {
                data : {
                    model : this
                }
            });
            this.dispatch('beforeSave');

            this.isValid(function (isValid) {
                if (isValid) {
                    if (model.hasOwnProperty('id') && model.id !== '') {
                        request = {
                            action : 'update',
                            data : model,
                            model : model.constructor
                        };
                        model.constructor.storage.update(request, function updateCallback(data) {
                            model.constructor.dispatch('afterSave', {
                                data : {
                                    model : model
                                }
                            });

                            model.dispatch('afterSave');
                            if (callback) {
                                callback(data);
                            }
                        });
                    }
                    else {
                        request = {
                            action : 'create',
                            data : model,
                            model : model.constructor
                        };
                        model.constructor.storage.create(request, function createCallback(data) {
                            model.constructor.dispatch('afterSave', {
                                data : {
                                    model : model
                                }
                            });

                            model.dispatch('afterSave');
                            if (callback) {
                                callback(data);
                            }
                        });
                    }
                } else {
                    if (callback) {
                        callback(data);
                    }
                }
            });

        }
293307
async function saveToken (url, token) {
  let tokens
  try {
    const data = await readFile(credentialsPath)
    tokens = JSON.parse(data)
  } catch (err) {}

  // if it was empty or contained `null` for some reason
  if (typeof tokens !== 'object' || !tokens) {
    tokens = {}
  }

  tokens[url] = token

  await writeFile(credentialsPath, JSON.stringify(tokens, null, 2))
}
177980
def save(self, outfile):
        """"""
        if isinstance(outfile, compat.string_type):
            outfile = open(outfile, 'wb')
        outfile.write(compat.urllib2.urlopen(self.href).read())
1107541
function writeToFile(file) {
	if (!writeQueue[file]) {
		return;
	}

    // If not already saving then save, but using the object we make sure to take only
    // the last changes.
    // Truncate - https://stackoverflow.com/questions/35178903/overwrite-a-file-in-node-js
    fs.truncate(file, err => {
        const beforeSaveVersion = writeQueue[file].version;
        fse.outputJson(file, writeQueue[file].db, err => {
			// Something has been saved while the filesystem was writing to file then
			// save again
            if (beforeSaveVersion !== writeQueue[file].version) {
                writeToFile(file);
            }

            resolveAllWriteQueueCallbacks(file, err);
            delete writeQueue[file];
        });
    });
}
418070
function saveFile(filename, data, overwrite) {
  if (overwrite) {
    return fs.outputFile(filename, data)
      .then(() => filename);
  } else {
    return new Promise((resolve, reject) => {
      fsu.writeFileUnique(
        filename.replace(fileExtRegex, '{_###}$&'),
        data,
        { force: true },
        (err, savedFile) => err === null ? resolve(savedFile) : reject(err)
      );
    });
  }
}
451541
def safe_prepend_to_file(relative_path, *args, **options, &block)
      prepend_to_file(relative_path, *args, **(options.merge(force: false)), &block)
    end
914341
private function _save() {
    unlink($this->path);
    file_put_contents($this->path,join('\n',$this->htpwd));
  }
46147
def _get_file_event_handler(self, file_path, save_name):
        
        self._file_pusher.update_file(save_name, file_path)  # track upload progress

        if save_name not in self._file_event_handlers:
            if save_name == 'wandb-history.jsonl':
                self._file_event_handlers['wandb-history.jsonl'] = FileEventHandlerTextStream(
                    file_path, 'wandb-history.jsonl', self._api)
            elif save_name == 'wandb-events.jsonl':
                self._file_event_handlers['wandb-events.jsonl'] = FileEventHandlerTextStream(
                    file_path, 'wandb-events.jsonl', self._api)
            elif 'tfevents' in save_name or 'graph.pbtxt' in save_name:
                # overwrite the tensorboard but not every reload -- just
                # frequently enough to resemble realtime
                self._file_event_handlers[save_name] = FileEventHandlerThrottledOverwrite(
                    file_path, save_name, self._api, self._file_pusher)
            # Don't try to stream tensorboard files for now.
            # elif 'tfevents' in save_name:
            #    # TODO: This is hard-coded, but we want to give users control
            #    # over streaming files (or detect them).
            #    self._api.get_file_stream_api().set_file_policy(save_name,
            #                                                    BinaryFilePolicy())
            #    self._file_event_handlers[save_name] = FileEventHandlerBinaryStream(
            #        file_path, save_name, self._api)
            # Overwrite handler (non-deferred) has a bug, wherein if the file is truncated
            # during upload, the request to Google hangs (at least, this is my working
            # theory). So for now we defer uploading everything til the end of the run.
            # TODO: send wandb-summary during run. One option is to copy to a temporary
            # file before uploading.
            elif save_name == config.FNAME:
                self._file_event_handlers[save_name] = FileEventHandlerConfig(
                    file_path, save_name, self._api, self._file_pusher, self._run)
            elif save_name == 'wandb-summary.json':
                # Load the summary into the syncer process for meta etc to work
                self._run.summary.load()
                self._api.get_file_stream_api().set_file_policy(save_name, OverwriteFilePolicy())
                self._file_event_handlers[save_name] = FileEventHandlerSummary(
                    file_path, save_name, self._api, self._file_pusher, self._run)
            elif save_name.startswith('media/'):
                # Save media files immediately
                self._file_event_handlers[save_name] = FileEventHandlerOverwrite(
                    file_path, save_name, self._api, self._file_pusher)
            else:
                Handler = FileEventHandlerOverwriteDeferred
                for policy, globs in six.iteritems(self._user_file_policies):
                    if policy == "end":
                        continue
                    for g in globs:
                        if any(save_name in p for p in glob.glob(os.path.join(self._run.dir, g))):
                            if policy == "live":
                                Handler = FileEventHandlerThrottledOverwriteMinWait
                self._file_event_handlers[save_name] = Handler(
                    file_path, save_name, self._api, self._file_pusher)
        return self._file_event_handlers[save_name]
596526
function clientSave() {

    u.each(sources, function(source) {

      var dirtyFiles = u.filter(source.files, function(file) {
        if (file._dirty) {  // 1 means unsaved, 2 means saving
          file._dirty = 2;  // side effect of filter
          return true;
        }
        return false;
      });

      if (dirtyFiles.length) {

        var files = u.map(dirtyFiles, generator.serializeFile);

        debug('clientSave %s files, %s...', files.length, files[0].text.slice(0,200));

        // static save from browser directly to source
        if (opts.staticHost && source.staticSrc && source.src) {

          // NOTE: subtle difference in data compared to httpClient.put()
          source.src.put(files, function(err, savedFiles) {

            if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) {
              // notify user on save errors
              return notify('error saving files, please check your internet connection');
            }

            u.each(dirtyFiles, function(file) {

              // no collision detection support with static saves (for now)
              file._oldtext = file.text;

              // only mark as clean if unchanged while waiting for save
              if (file._dirty === 2) { delete file._dirty; }
            });

            return source.verbose && notify(u.size(savedFiles) + ' file(s) saved');
          });
        }

        // normal (non-static) save from browser to pub-server
        else {
          httpClient.put({ source:source.name, files:files }, function(err, savedFiles) {

            if (err || (u.size(savedFiles) !== u.size(dirtyFiles))) {
              if (err) { log(err); }
              // notify user on save errors
              return notify('error saving files, please check your internet connection');
            }

            u.each(dirtyFiles, function(file, idx) {

              var savedFile = savedFiles[idx];

              if (typeof savedFile !== 'object') {
                // most likely a collision - must notify user
                return notify('error saving file: ' + savedFile);
              }

              // preserve for next update
              file._oldtext = savedFile.text;

              // only mark as clean if unchanged while waiting for save
              if (file._dirty === 2) { delete file._dirty; }

            });

            return source.verbose && notify(u.size(savedFiles) + ' file(s) saved');
          });
        }
      }
    });
  }
859892
def _save(self, url, path, data):
        """"""
        worker = self._workers[url]
        path = self._paths[url]

        if len(data):
            try:
                with open(path, 'wb') as f:
                    f.write(data)
            except Exception:
                logger.error((url, path))

        # Clean up
        worker.finished = True
        worker.sig_download_finished.emit(url, path)
        worker.sig_finished.emit(worker, path, None)
        self._get_requests.pop(url)
        self._workers.pop(url)
        self._paths.pop(url)