Override this so we can handle case of file not writable, as
            well as to make our _lastSavedState copy.
434636
def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False):
        
        self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\
                   str(set_ro)+', overwriteRO: '+str(overwriteRO))
        cantWrite = False
        inInstArea = False
        if fname in (None, ''): fname = self._taskParsObj.getFilename()
        # now do some final checks then save
        try:
            if _isInstalled(fname): # check: may be installed but not read-only
                inInstArea = cantWrite = True
            else:
                # in case of save-as, allow overwrite of read-only file
                if overwriteRO and os.path.exists(fname):
                    setWritePrivs(fname, True, True) # try make writable
                # do the save
                rv=self._taskParsObj.saveParList(filename=fname,comment=comment)
        except IOError:
            cantWrite = True

        # User does not have privs to write to this file. Get name of local
        # choice and try to use that.
        if cantWrite:
            fname = self._taskParsObj.getDefaultSaveFilename()
            # Tell them the context is changing, and where we are saving
            msg = 'Read-only config file for task "'
            if inInstArea:
                msg = 'Installed config file for task "'
            msg += self._taskParsObj.getName()+'" is not to be overwritten.'+\
                  '  Values will be saved to: \n\n\t"'+fname+'".'
            showwarning(message=msg, title="Will not overwrite!")
            # Try saving to their local copy
            rv=self._taskParsObj.saveParList(filename=fname, comment=comment)

        # Treat like a save-as (update title for ALL save ops)
        self._saveAsPostSave_Hook(fname)

        # Limit write privs if requested (only if not in the rc dir)
        if set_ro and os.path.dirname(os.path.abspath(fname)) != \
                                      os.path.abspath(self._rcDir):
            cfgpars.checkSetReadOnly(fname)

        # Before returning, make a copy so we know what was last saved.
        # The dict() method returns a deep-copy dict of the keyvals.
        self._lastSavedState = self._taskParsObj.dict()
        return rv
849639
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
        ''''''
        if filename is None:
            if self.filename is not None:
                filename = self.filename
            else:
                raise ValueError(cookiejar.MISSING_FILENAME_TEXT)

        # TODO: obtain file lock, read contents of file, and merge with
        # current content.
        go_cookies = []
        now = time.time()
        for cookie in self:
            if not ignore_discard and cookie.discard:
                continue
            if not ignore_expires and cookie.is_expired(now):
                continue
            go_cookies.append(py_to_go_cookie(cookie))
        with open(filename, "w") as f:
            f.write(json.dumps(go_cookies))
615792
protected function ensureDirectoryWritable() {
    // Reality check to prevent stomping on the local filesystem if there is
    // something wrong with the config.
    if (!$this->directory) {
      throw new BltException('Could not save data to a file because the path setting is mis-configured.');
    }

    $writable = is_dir($this->directory) || (!file_exists($this->directory) && @mkdir($this->directory, 0777, TRUE));
    $writable = $writable && is_writable($this->directory);
    if (!$writable) {
      throw new BltException(
        'Could not save data to a file because the path {path} cannot be written to.',
        ['path' => $this->directory]
      );
    }
  }
615733
public synchronized void releaseFile() {
        if (currentStatus == StreamStatus.ACTIVE) {
            // Only flush the print stream: don't close it.
            currentPrintStream.flush();

            if (!FileLogUtils.tryToClose(currentPrintStream)) {
                FileLogUtils.tryToClose(currentFileStream);
            }

            // Send to bit bucket again-- this holder is done (false -- do not replace)
            setStreamStatus(StreamStatus.INIT, null, null, DummyOutputStream.psInstance);
        }
    }
653901
function ( noPrune ) {
        removeNotFoundFiles();

        noPrune = typeof noPrune === 'undefined' ? true : noPrune;

        var entries = normalizedEntries;
        var keys = Object.keys( entries );

        if ( keys.length === 0 ) {
          return;
        }

        var me = this;

        keys.forEach( function ( entryName ) {
          var cacheEntry = entries[ entryName ];

          try {
            var meta = useChecksum ? me._getMetaForFileUsingCheckSum( cacheEntry ) : me._getMetaForFileUsingMtimeAndSize( cacheEntry );
            cache.setKey( entryName, meta );
          } catch (err) {
            // if the file does not exists we don't save it
            // other errors are just thrown
            if ( err.code !== 'ENOENT' ) {
              throw err;
            }
          }
        } );

        cache.save( noPrune );
      }
699153
protected void endPersistence(final BufferedWriter writer) throws IOException {
        // Append any additional users to the end of the file.
        for (Object currentKey : toSave.keySet()) {
            String key = (String) currentKey;
            if (!key.contains(DISABLE_SUFFIX_KEY)) {
                writeProperty(writer, key, null);
            }
        }

        toSave = null;
    }
927098
def flush
      begin
        valid_existing_file?(@file)
        raise ReadOnlyThresholdsFile if @readonly
        hash = current_hash
        file = File.open(@file, 'w+')
        raise ThresholdAtomicLockFailure, 'The @file state/hash changed before we could flush the file' unless stored_hash == hash
        file.write self.sort.to_s
        file.close

      rescue NonExistantThresholdFile
        raise ReadOnlyThresholdsFile if @readonly
        file = File.open(@file, 'w')
        file.write self.sort.to_s
        file.close
      end

      stored_hash=current_hash
      return true
    end
647530
function dirtyFileSaveCancelled() {
        UpdateInfoBar.showUpdateBar({
            type: "warning",
            title: Strings.WARNING_TYPE,
            description: Strings.UPDATE_ON_NEXT_LAUNCH
        });
    }
477527
protected FileWrapper handleAddFileAndUpdateCandidateDescription(Integer candidateId, File file, String candidateDescription,
                                                                   String externalId, FileParams params, boolean deleteFile) {
        // first add the file
        FileWrapper fileWrapper = this.handleAddFileWithFile(Candidate.class, candidateId, file, externalId, params, deleteFile);

        // second update the candidate
        try {

            Candidate candidateToUpdate = new Candidate();
            candidateToUpdate.setId(candidateId);

            if (!StringUtils.isBlank(candidateDescription)) {
                candidateToUpdate.setDescription(candidateDescription);
                this.updateEntity(candidateToUpdate);
            }
        } catch (Exception e) {
            log.error("Error reading file to resume text", e);
        }

        return fileWrapper;
    }
448606
private void checkAllowedNonFileState(StorageState curState, Object name)
      throws IOException {
    switch (curState) {
    case NON_EXISTENT:
    case NOT_FORMATTED:
    case NORMAL:
      break;
    default:
      throwIOException("ImageManager bad state: " + curState + " for: "
          + name.toString());
    }
  }
930312
def _write_file_safely(local_path, fileinfo, response):
    """"""
    try:
        _write_file(local_path, fileinfo, response)
    except BaseException as e:
        logger.warning("{} interrupted writing {} -- "
                       "cleaning up partial file".format(
                       e.__class__.__name__, local_path))
        os.remove(local_path)
        raise e
903405
public boolean needPersistence(long fileId) {
    if (isFilePersisting(fileId) || isFilePersisted(fileId)) {
      return false;
    }

    try {
      String ufsFingerprint = ufsFingerprint(fileId);
      if (ufsFingerprint != null) {
        // mark as persisted
        addPersistedFile(fileId, ufsFingerprint);
        return false;
      }
    } catch (Exception e) {
      LOG.warn("Failed to check if file {} exists in under storage system: {}",
               fileId, e.getMessage());
      LOG.debug("Exception: ", e);
    }
    return true;
  }
1210286
function setUnusableRecord(state, unusableRecord) {
  Object.defineProperty(state, 'unusableRecord',
    {value: unusableRecord, writable: true, configurable: true, enumerable: false});
}
570908
private void captureUploadStateIfPossible() {
        if (origReq.getSSECustomerKey() == null) {
            persistableUpload = new PersistableUpload(origReq.getBucketName(),
                    origReq.getKey(), origReq.getFile()
                            .getAbsolutePath(), multipartUploadId,
                    configuration.getMinimumUploadPartSize(),
                    configuration.getMultipartUploadThreshold());
            notifyPersistableTransferAvailability();
        }
    }
303734
public long lastModified(final File file) {
        if (System.getSecurityManager() == null)
            return file.lastModified();
        return AccessController.doPrivileged(new PrivilegedAction<Long>() {
            @Override
            public Long run() {
                return new Long(file.lastModified());
            }
        }, controlContext).longValue();
    }
358361
@Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mExpandableAdapter.onSaveInstanceState(outState);
        outState.putSerializable(SAVED_TEST_DATA_ITEM_LIST, mTestDataItemList);
    }
563500
protected long writeOutput(OutputStream out, ValueData value) throws IOException
   {
      if (value.isByteArray())
      {
         byte[] buff = value.getAsByteArray();
         out.write(buff);

         return buff.length;
      }
      else
      {
         InputStream in;
         if (value instanceof StreamPersistedValueData)
         {

            StreamPersistedValueData streamed = (StreamPersistedValueData)value;
            if (streamed.isPersisted())
            {
               // already persisted in another Value, copy it to this Value
               in = streamed.getAsStream();
            }
            else
            {
               in = streamed.getStream();
               if (in == null)
               {
                  in = new FileInputStream(streamed.getTempFile());
               }
            }
         }
         else
         {
            in = value.getAsStream();
         }

         try
         {
            return copy(in, out);
         }
         finally
         {
            in.close();
         }
      }
   }