Save a doc to cache
323639
def save(self, doc):
        
        self.log.debug('save()')
        self.docs.append(doc)
        self.commit()
876136
def save(self, data):
        """"""
        if not self.is_connected:
            raise Exception("No database selected")
        if not data:
            return False
        if isinstance(data, dict):
            doc = couchdb.Document()
            doc.update(data)
            self.db.create(doc)
        elif isinstance(data, couchdb.Document):
            self.db.update(data)
        elif isinstance(data, list):
            self.db.update(data)
        return True
702675
public synchronized void updateDocumentContent(Long docid, String content) throws SQLException {
        if (cache_document==CACHE_OFF) {
            edadb.updateDocumentContent(docid, content);
        } else if (cache_document==CACHE_ONLY) {
            Document docvo = documentCache.get(docid);
            if (docvo!=null) docvo.setContent(content);
        } else {
            edadb.updateDocumentContent(docid, content);
            Document docvo = documentCache.get(docid);
            if (docvo!=null) docvo.setContent(content);
        }
    }
1306020
def _pack(self, fname, encoding):
        
        (fd, tmpfile) = tempfile.mkstemp()
        os.close(fd)
        try:
            self.save(tmpfile, mode='abs', validate=False)
            document_loader, processobj, metadata, uri = load_cwl(tmpfile)
        finally:
            # cleanup tmpfile
            os.remove(tmpfile)

        with codecs.open(fname, 'wb', encoding=encoding) as f:
            f.write(print_pack(document_loader, processobj, uri, metadata))
505573
def cache_results(function):
    """"""
    def save_to_permacache():
        """Save the in-memory cache data to the permacache.

        There is a race condition here between two processes updating at the
        same time. It's perfectly acceptable to lose and/or corrupt the
        permacache information as each process's in-memory cache will remain
        in-tact.

        """
        update_from_permacache()
        try:
            with open(filename, 'wb') as fp:
                pickle.dump(cache, fp, pickle.HIGHEST_PROTOCOL)
        except IOError:
            pass  # Ignore permacache saving exceptions

    def update_from_permacache():
        """Attempt to update newer items from the permacache."""
        try:
            with open(filename, 'rb') as fp:
                permacache = pickle.load(fp)
        except Exception:  # TODO: Handle specific exceptions
            return  # It's okay if it cannot load
        for key, value in permacache.items():
            if key not in cache or value[0] > cache[key][0]:
                cache[key] = value

    cache = {}
    cache_expire_time = 3600
    try:
        filename = os.path.join(gettempdir(), 'update_checker_cache.pkl')
        update_from_permacache()
    except NotImplementedError:
        filename = None

    @wraps(function)
    def wrapped(obj, package_name, package_version, **extra_data):
        """Return cached results if available."""
        now = time.time()
        key = (package_name, package_version)
        if not obj.bypass_cache and key in cache:  # Check the in-memory cache
            cache_time, retval = cache[key]
            if now - cache_time < cache_expire_time:
                return retval
        retval = function(obj, package_name, package_version, **extra_data)
        cache[key] = now, retval
        if filename:
            save_to_permacache()
        return retval
    return wrapped
515779
def __cache(self, file, content, document):
        

        self.__files_cache.add_content(**{file: CacheData(content=content, document=document)})
690234
function _onDocumentSaved(event, doc) {
        if (!isActive() || !_server) {
            return;
        }

        var absolutePath            = doc.file.fullPath,
            liveDocument            = absolutePath && _server.get(absolutePath),
            liveEditingEnabled      = liveDocument && liveDocument.isLiveEditingEnabled  && liveDocument.isLiveEditingEnabled();

        // Skip reload if the saved document has live editing enabled
        if (liveEditingEnabled) {
            return;
        }

        // reload the page if the given document is a JS file related
        // to the current live document.
        if (_liveDocument.isRelated(absolutePath)) {
            if (doc.getLanguage().getId() === "javascript") {
                _setStatus(STATUS_RELOADING);
                _protocol.reload();
            }
        }
    }
960211
def save(self):
        
        resp = self.r_session.put(
            self.document_url,
            data=self.json(),
            headers={'Content-Type': 'application/json'}
        )
        resp.raise_for_status()
819501
def _save_keyring(self, keyring_dict):
        """"""
        import gdata
        result = self.OK
        file_contents = base64.urlsafe_b64encode(pickle.dumps(keyring_dict))
        try:
            if self.docs_entry:
                extra_headers = {'Content-Type': 'text/plain',
                                 'Content-Length': len(file_contents)}
                self.docs_entry = self.client.Put(
                    file_contents,
                    self.docs_entry.GetEditMediaLink().href,
                    extra_headers=extra_headers
                )
            else:
                from gdata.docs.service import DocumentQuery
                # check for existence of folder, create if required
                folder_query = DocumentQuery(categories=['folder'])
                folder_query['title'] = self.collection
                folder_query['title-exact'] = 'true'
                docs = self.client.QueryDocumentListFeed(folder_query.ToUri())
                if docs.entry:
                    folder_entry = docs.entry[0]
                else:
                    folder_entry = self.client.CreateFolder(self.collection)
                file_handle = io.BytesIO(file_contents)
                media_source = gdata.MediaSource(
                    file_handle=file_handle,
                    content_type='text/plain',
                    content_length=len(file_contents),
                    file_name='temp')
                self.docs_entry = self.client.Upload(
                    media_source,
                    self._get_doc_title(),
                    folder_or_uri=folder_entry
                )
        except gdata.service.RequestError as ex:
            try:
                if ex.message['reason'].lower().find('conflict') != -1:
                    result = self.CONFLICT
                else:
                    # Google docs has a bug when updating a shared document
                    # using PUT from any account other that the owner.
                    # It returns an error 400 "Sorry, there was an error saving
                    # the file. Please try again"
                    # *despite* actually updating the document!
                    # Workaround by re-reading to see if it actually updated
                    msg = 'Sorry, there was an error saving the file'
                    if ex.message['body'].find(msg) != -1:
                        new_docs_entry, new_keyring_dict = self._read()
                        if new_keyring_dict == keyring_dict:
                            result = self.OK
                        else:
                            result = self.FAIL
                    else:
                        result = self.FAIL
            except Exception:
                result = self.FAIL

        return result
493445
def patch(self, keepNull = True, **docArgs) :
        """"""

        if self.URL is None :
            raise ValueError("Cannot patch a document that was not previously saved")

        payload = self._store.getPatches()
        
        if self.collection._validation['on_save'] :
            self.validate()

        if len(payload) > 0 :
            params = dict(docArgs)
            params.update({'collection': self.collection.name, 'keepNull' : keepNull})
            payload = json.dumps(payload, default=str)

            r = self.connection.session.patch(self.URL, params = params, data = payload)
            data = r.json()
            if (r.status_code == 201 or r.status_code == 202) and "error" not in data :
                self._rev = data['_rev']
            else :
                raise UpdateError(data['errorMessage'], data)

            self.modified = False

        self._store.resetPatch()
644945
def _write_cache_to_file(self):
        """"""
        with(open(self._cache_file_name, 'w')) as fp:
            fp.write(simplejson.dumps(self._cache))
510607
public void putDocumentInCache(int n, Source source)
  {

    int cachedNode = getNode(source);

    if (DTM.NULL != cachedNode)
    {
      if (!(cachedNode == n))
        throw new RuntimeException(
          "Programmer's Error!  "
          + "putDocumentInCache found reparse of doc: "
          + source.getSystemId());
      return;
    }
    if (null != source.getSystemId())
    {
      m_sourceTree.addElement(new SourceTree(n, source.getSystemId()));
    }
  }
197034
def _tmpfile(self, cache_key, use):
    """"""
    with temporary_file(suffix=cache_key.id + use, root_dir=self._cache_root,
                        permissions=self._permissions) as tmpfile:
      yield tmpfile
905677
def save doc, output, &data_iterator
    
      if output.respond_to?(:write)
        @out_stream = output
      else
        @out_stream = open(output, "w")
      end
    
      data_iterator.call(doc)
      
    end
216629
function(doc) {
      try {
        localStorage.setItem(prefix + doc.id, doc.serialize());
        return true;
      } catch (error) {
        // QUOTA_EXCEEDED
        console.error("Error while saving document to local storage",
            error);
        return false;
      }
    }
1082379
def save_bookmarks(filename, bookmarks):
    """"""
    if not osp.isfile(filename):
        return
    slots = load_bookmarks_without_file(filename)
    for slot_num, content in bookmarks.items():
        slots[slot_num] = [filename, content[0], content[1]]
    CONF.set('editor', 'bookmarks', slots)
704530
def write(content, filename='cache'):
	
	cache_path = get_cache_path(filename)
	with open(cache_path, 'w') as file:
		if content is not None:
			json.dump(content, file, indent=3, sort_keys=True)