a method to create a new document in the collection

        :param doc_details: dictionary with document details and user id value
        :return: dictionary with document details and _id and _rev values
358350
def create(self, doc_details):

        '''
            
        '''
        
        # https://developer.couchbase.com/documentation/mobile/1.5/references/sync-gateway/admin-rest-api/index.html#/document/post__db___doc_

        title = '%s.create' % self.__class__.__name__

    # validate input
        if self.model:
            doc_details = self.model.validate(doc_details, path_to_root='', object_title='%s(doc_details={...}' % title)

    # define request fields
        from copy import deepcopy
        new_record = deepcopy(doc_details)
        url = self.bucket_url + '/'

    # send request and construct output
        response = requests.post(url, json=new_record)
        if response.status_code not in (200, 201):
            response = response.json()
            raise Exception('%s() error: %s' % (title, response))
        response = response.json()
        new_record['_id'] = response['id']
        new_record['_rev'] = response['rev']
    
        return new_record
149091
def document(cls):
    
    if cls.__doc__ is None:
        return cls

    baseclass_name = cls.mro()[-2].__name__

    try:
        return DOC_FUNCTIONS[baseclass_name](cls)
    except KeyError:
        return cls
141974
def create_edge(self, from_doc, to_doc, edge_data={}):
        

        return Edge.create(
            collection=self,
            from_doc=from_doc,
            to_doc=to_doc,
            edge_data=edge_data
        )
497623
def doc_metadata(doc):
    """"""

    r = doc['Root'].as_dict()
    r.update(doc['Contacts'].as_dict())
    r['author'] = r.get('author', r.get('creator', r.get('wrangler')))

    return r
79269
def newDoc(version):
    
    ret = libxml2mod.xmlNewDoc(version)
    if ret is None:raise treeError('xmlNewDoc() failed')
    return xmlDoc(_obj=ret)
119404
def update(self, document_id, update_spec, namespace, timestamp):
        
        db, coll = self._db_and_collection(namespace)

        meta_collection_name = self._get_meta_collection(namespace)

        self.meta_database[meta_collection_name].replace_one(
            {self.id_field: document_id, "ns": namespace},
            {self.id_field: document_id, "_ts": timestamp, "ns": namespace},
            upsert=True,
        )

        no_obj_error = "No matching object found"
        update_spec.pop("$v", None)
        updated = self.mongo[db].command(
            SON(
                [
                    ("findAndModify", coll),
                    ("query", {"_id": document_id}),
                    ("update", update_spec),
                    ("new", True),
                ]
            ),
            allowable_errors=[no_obj_error],
        )["value"]
        return updated
780218
def setMetadata(doc, m):
    """"""
    if doc.isClosed or doc.isEncrypted:
        raise ValueError("operation on closed or encrypted document")
    if type(m) is not dict:
        raise ValueError("arg2 must be a dictionary")
    for k in m.keys():
        if not k in ("author", "producer", "creator", "title", "format",
                     "encryption", "creationDate", "modDate", "subject",
                     "keywords"):
            raise ValueError("invalid dictionary key: " + k)
    d = "<</Author"
    d += getPDFstr(m.get("author", "none"))
    d += "/CreationDate"
    d += getPDFstr(m.get("creationDate", "none"))
    d += "/Creator"
    d += getPDFstr(m.get("creator", "none"))
    d += "/Keywords"
    d += getPDFstr(m.get("keywords", "none"))
    d += "/ModDate"
    d += getPDFstr(m.get("modDate", "none"))
    d += "/Producer"
    d += getPDFstr(m.get("producer", "none"))
    d += "/Subject"
    d += getPDFstr(m.get("subject", "none"))
    d += "/Title"
    d += getPDFstr(m.get("title", "none"))
    d += ">>"
    doc._setMetadata(d)
    doc.initData()
    return
401165
def get_new_document(self, cursor_pos=None):
        
        lines = []

        # Original text, before cursor.
        if self.original_document.text_before_cursor:
            lines.append(self.original_document.text_before_cursor)

        # Selected entries from the history.
        for line_no in sorted(self.selected_lines):
            lines.append(self.history_lines[line_no])

        # Original text, after cursor.
        if self.original_document.text_after_cursor:
            lines.append(self.original_document.text_after_cursor)

        # Create `Document` with cursor at the right position.
        text = '\n'.join(lines)
        if cursor_pos is not None and cursor_pos > len(text):
            cursor_pos = len(text)
        return Document(text, cursor_pos)
40973
def set_document(request, doc_id, body, errors):
    
    if doc_id in DB:
        errors['doc_id'].add('Document already exists')

    if errors:
        raise errors

    body['doc_id'] = doc_id
    DB[doc_id] = body

    # dict response for jsonify middleware
    return body
735856
def create_py3_docs():
    
    # we want the correct .rst 'type' for our data
    trans = {"methods": "function", "exceptions": "exception", "constants": "attribute"}
    data = get_py3_info()
    for k, v in data.items():
        output = []
        for name, desc in v:
            output.append("")
            output.append(".. _%s:" % name)  # reference for linking
            output.append("")
            output.append(".. py:%s:: %s" % (trans[k], name))
            output.append("")
            output.extend(auto_undent(desc))
        with open("../doc/py3-%s-info.inc" % k, "w") as f:
            f.write("\n".join(output))
501808
function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
  var metaDocId = '_local/doc_' + docId;
  var defaultMetaDoc = {_id: metaDocId, keys: []};
  var docData = docIdsToChangesAndEmits[docId];
  var indexableKeysToKeyValues = docData.indexableKeysToKeyValues;
  var changes = docData.changes;

  function getMetaDoc() {
    if (isGenOne(changes)) {
      // generation 1, so we can safely assume initial state
      // for performance reasons (avoids unnecessary GETs)
      return Promise.resolve(defaultMetaDoc);
    }
    return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc));
  }

  function getKeyValueDocs(metaDoc) {
    if (!metaDoc.keys.length) {
      // no keys, no need for a lookup
      return Promise.resolve({rows: []});
    }
    return view.db.allDocs({
      keys: metaDoc.keys,
      include_docs: true
    });
  }

  function processKvDocs(metaDoc, kvDocsRes) {
    var kvDocs = [];
    var oldKeysMap = {};

    for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
      var row = kvDocsRes.rows[i];
      var doc = row.doc;
      if (!doc) { // deleted
        continue;
      }
      kvDocs.push(doc);
      oldKeysMap[doc._id] = true;
      doc._deleted = !indexableKeysToKeyValues[doc._id];
      if (!doc._deleted) {
        var keyValue = indexableKeysToKeyValues[doc._id];
        if ('value' in keyValue) {
          doc.value = keyValue.value;
        }
      }
    }

    var newKeys = Object.keys(indexableKeysToKeyValues);
    newKeys.forEach(function (key) {
      if (!oldKeysMap[key]) {
        // new doc
        var kvDoc = {
          _id: key
        };
        var keyValue = indexableKeysToKeyValues[key];
        if ('value' in keyValue) {
          kvDoc.value = keyValue.value;
        }
        kvDocs.push(kvDoc);
      }
    });
    metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
    kvDocs.push(metaDoc);

    return kvDocs;
  }

  return getMetaDoc().then(function (metaDoc) {
    return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
      return processKvDocs(metaDoc, kvDocsRes);
    });
  });
}
391701
function(details) {
        const tabId = details.tabId;
        if ( tabId > 0 && details.type === 'main_frame' ) {
            µBlock.tabContextManager.push(tabId, details.url);
        }
        this.fromTabId(tabId);
        this.realm = '';
        this.type = details.type;
        this.setURL(details.url);
        this.docId = details.type !== 'sub_frame'
            ? details.frameId
            : details.parentFrameId;
        if ( this.tabId > 0 ) {
            if ( this.docId === 0 ) {
                this.docOrigin = this.tabOrigin;
                this.docHostname = this.tabHostname;
                this.docDomain = this.tabDomain;
            } else if ( details.documentUrl !== undefined ) {
                this.setDocOriginFromURL(details.documentUrl);
            } else {
                const pageStore = µBlock.pageStoreFromTabId(this.tabId);
                const docStore = pageStore && pageStore.frames.get(this.docId);
                if ( docStore ) {
                    this.docOrigin = undefined;
                    this.docHostname = docStore.pageHostname;
                    this.docDomain = docStore.pageDomain;
                } else {
                    this.setDocOrigin(this.tabOrigin);
                }
            }
        } else if ( details.documentUrl !== undefined ) {
            const origin = this.originFromURI(
                µBlock.normalizePageURL(0, details.documentUrl)
            );
            this.setDocOrigin(origin).setTabOrigin(origin);
        } else if ( this.type === 'sub_frame' ) {
            const origin = this.originFromURI(this.url);
            this.setDocOrigin(origin).setTabOrigin(origin);
        } else {
            this.setDocOrigin(this.tabOrigin);
        }
        this.filter = undefined;
        return this;
    }
667255
def doc_dict(self):
        """"""
        doc = {
            'type': self.__class__.__name__,
            'description': self.description,
            'default': self.default,
            'required': self.required
        }
        if hasattr(self, 'details'):
            doc['detailed_description'] = self.details
        return doc
861786
def add_insert(self, document):
        
        validate_is_document_type("document", document)
        # Generate ObjectId client side.
        if not (isinstance(document, RawBSONDocument) or '_id' in document):
            document['_id'] = ObjectId()
        self.ops.append((_INSERT, document))
312413
function initDocument (docName) {
  return db.getDocument(dbName, docName)
    .then(response => response.data._rev) // document already exists
    .catch(response => {
      if (response.status === 404) {
        // create new document
        return db.createDocument(dbName, {foo: 'bar'}, docName)
          .then(response => response.data.rev)
      } else {
        // real error
        return Promise.reject(response)
      }
    })
}
289036
def as_doc(self):
        
        doc = SON([("$ref", self.collection),
                   ("$id", self.id)])
        if self.database is not None:
            doc["$db"] = self.database
        doc.update(self.__kwargs)
        return doc
199830
def add_doc(self, doc):
        
        if isinstance(doc, HelloDoc) and doc.validate():
            self.docs.append(doc)
        else:
            if not doc.validate():
                raise Exception("HelloDoc Errors %s" % (doc.errors,))
            else:
                raise Exception("add_doc doc must be an instance of class HelloDoc")