Create and return a new Session Token based on the contents
        of a JSON document.

        :type json_doc: str
        :param json_doc: A string containing a JSON document with a
            previously saved Credentials object.
771232
def from_json(cls, json_doc):
        
        d = json.loads(json_doc)
        token = cls()
        token.__dict__.update(d)
        return token
308380
def on_doctree_read(app, document):
    
    cache: Dict[type, Dict[str, object]] = {}
    for desc_node in document.traverse(addnodes.desc):
        if desc_node.get("domain") != "py":
            continue
        signature_node = desc_node.traverse(addnodes.desc_signature)[0]
        module_name = signature_node.get("module")
        object_name = signature_node.get("fullname")
        object_type = desc_node.get("objtype")
        module = importlib.import_module(module_name)
        if object_type == "class":
            handle_class(signature_node, module, object_name, cache)
        elif object_type in ("method", "attribute", "staticmethod", "classmethod"):
            handle_method(signature_node, module, object_name, cache)
1253811
def write_json_document(title, body):
    
    if not title.endswith('.json'):
        title += '.json'

    json_body = create_json_str(body)

    if os.path.exists(title):
        juicer.utils.Log.log_warn("Cart file '%s' already exists, overwriting with new data." % title)

    f = open(title, 'w')
    f.write(json_body)
    f.flush()
    f.close()
33388
def save_doc(self, doc, doc_id=None, following_attachments=None):
        ''''''

        self.log("save_document called for doc: %r", doc)

        d = defer.Deferred()

        try:
            if not isinstance(doc, (str, unicode, )):
                raise ValueError('Doc should be either str or unicode')
            doc = json.loads(doc)
            doc = self._set_id_and_revision(doc, doc_id)

            self.increase_stat('save_doc')

            self._documents[doc['_id']] = doc
            if doc['_id'] not in self._attachments:
                self._attachments[doc['_id']] = dict()
            attachments = doc.get('_attachments', dict())
            for name in attachments:
                if attachments[name].get('follows'):
                    if name not in following_attachments:
                        raise ValueError("Document id %s had attachment name"
                                         " %s marked with follows=True, but"
                                         " it was not passed to save_doc() "
                                         % (doc['_id'], name))

                    del attachments[name]['follows']
                    attachments[name]['stub'] = True
                    b = following_attachments[name].get_body()
                    self._attachments[doc['_id']][name] = b

                elif name not in self._attachments[doc['_id']]:
                    raise ValueError("Document id %s body has attachment "
                                     "named %s "
                                     "but it is not in our cache " %
                                     (doc['_id'], name))
            for name in self._attachments[doc['_id']].keys():
                if name not in attachments:
                    del self._attachments[doc['_id']][name]
                    self.log('Deleted attachment %s of the doc: %s because '
                             'its not in the _attachments key' %
                             (name, doc['_id']))

            self._expire_cache(doc['_id'])

            r = Response(ok=True, id=doc['_id'], rev=doc['_rev'])
            self._analize_changes(doc)
            d.callback(r)
        except (ConflictError, ValueError, ) as e:
            d.errback(e)

        return d
193025
def login(self, username, json_document):
        
        url = '{}u/{}'.format(self.url, username)
        make_request(
            url, method='PUT', body=json_document, timeout=self.timeout)
62549
function JsonFind(doc) {
  const possibleJson = JSON.stringify(doc);

  if (possibleJson === undefined) {
    throw new Error('Object is invalid JSON');
  } else if (isAtom(doc) || doc === null) {
    return doc;
  } else {
    return Object.assign(Object.create(JSON_DATA), doc);
  }
}
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)
      }
    })
}
827478
def from_json(cls, json_data):
        
        new_instance = cls()
        for field_name, field_obj in cls._get_fields().items():
            if isinstance(field_obj, NestedDocumentField):
                if field_name in json_data:
                    nested_field = field_obj.__get__(new_instance, new_instance.__class__)
                    if not nested_field:
                        # here, we have to create an instance of the nested document,
                        # since we have a JSON object for it
                        nested_field = field_obj.nested_klass()

                    nested_document = nested_field.from_json(json_data[field_name])
                    field_obj.__set__(new_instance, nested_document)
            elif isinstance(field_obj, BaseField):
                if field_name in json_data:
                    value = field_obj.from_json(json_data[field_name])
                    field_obj.__set__(new_instance, value)
            else:
                continue

        return new_instance
7310
def from_json(cls, json_str):
        
        vocab_dict = json.loads(json_str)

        unknown_token = vocab_dict.get('unknown_token')
        vocab = cls(unknown_token=unknown_token)
        vocab._idx_to_token = vocab_dict.get('idx_to_token')
        vocab._token_to_idx = vocab_dict.get('token_to_idx')
        if unknown_token:
            vocab._token_to_idx = DefaultLookupDict(vocab._token_to_idx[unknown_token],
                                                    vocab._token_to_idx)
        vocab._reserved_tokens = vocab_dict.get('reserved_tokens')
        vocab._padding_token = vocab_dict.get('padding_token')
        vocab._bos_token = vocab_dict.get('bos_token')
        vocab._eos_token = vocab_dict.get('eos_token')
        return vocab
715043
def safe_json_response(method):
    

    def _safe_document(document):
        """ function modifies the document in place
            it iterates over the json document and stringify all non-string types
            :return: modified document """
        assert isinstance(document, dict), 'Error: provided document is not of DICT type: {0}' \
            .format(document.__class__.__name__)

        for key, value in document.items():
            if isinstance(value, dict):
                document[key] = {k: str(v) for k, v in value.items()}
            elif isinstance(value, list):
                document[key] = [str(v) for v in value]
            else:
                document[key] = str(document[key])
        return document

    @functools.wraps(method)
    def _wrapper(self, *args, **kwargs):
        try:
            document = method(self, *args, **kwargs)
            return _safe_document(document)
        except Exception as e:
            return self.reply_server_error(e)

    return _wrapper
672965
def update(self, doc: dict, doc_id: str):
        
        body = {
            'doc': doc
        }
        self.instance.update(self.index, self.doc_type, doc_id, body=body)
215746
def write_document(doc, fnm):
    
    with codecs.open(fnm, 'wb', 'ascii') as f:
        f.write(json.dumps(doc, indent=2))
131234
function extractJSONPath(doc, expr) {
  // typeof null is 'object' hence the explicit check here
  if (typeof doc !== 'object' || doc === null) {
    return '';
  }

  let results;

  try {
    results = jsonpath.query(doc, expr);
  } catch (queryErr) {
    debug(queryErr);
  }

  if (!results) {
    return '';
  }

  if (results.length > 1) {
    return results[randomInt(0, results.length - 1)];
  } else {
    return results[0];
  }
}
345847
def get_certification_document(current_block: dict, self_cert_document: Identity, from_pubkey: str) -> Certification:
    
    # construct Certification Document
    return Certification(version=10, currency=current_block['currency'], pubkey_from=from_pubkey,
                                  identity=self_cert_document,
                                  timestamp=BlockUID(current_block['number'], current_block['hash']), signature="")
323014
def prep_doc(self, doc_obj):
        
        doc = doc_obj._data.copy()
        for key, prop in list(doc_obj._base_properties.items()):
            prop.validate(doc.get(key), key)
            raw_value = prop.get_python_value(doc.get(key))
            if prop.unique:
                self.check_unique(doc_obj, key, raw_value)
            value = prop.get_db_value(raw_value)
            doc[key] = value

        doc['_doc_type'] = get_doc_type(doc_obj.__class__)
        return doc
346206
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity:
    

    # get current block BlockStamp
    timestamp = BlockUID(current_block['number'], current_block['hash'])

    # create keys from credentials
    key = SigningKey.from_credentials(salt, password)

    # create identity document
    identity = Identity(
        version=10,
        currency=current_block['currency'],
        pubkey=key.pubkey,
        uid=uid,
        ts=timestamp,
        signature=None
    )

    # sign document
    identity.sign([key])

    return identity
63988
def annotate_json(self, text, annotators=None):
        
        # WARN(chaganty): I'd like to deprecate this function -- we
        # should just use annotate().json
        #properties = {
        #    'annotators': ','.join(annotators or self.default_annotators),
        #    'outputFormat': 'json',
        #}
        #return self._request(text, properties).json(strict=False)

        doc = self.annotate(text, annotators)
        return doc.json