Transform to a MongoDB-safe value.
508292
def to_foreign(self, obj, name, value):  # pylint:disable=unused-argument
		""""""
		
		from marrow.mongo import Document
		
		kind = self._kind(obj if isclass(obj) else obj.__class__)
		
		if isinstance(value, Document):
			if __debug__ and kind and issubclass(kind, Document) and not isinstance(value, kind):
				raise ValueError("Not an instance of " + kind.__name__ + " or a sub-class: " + repr(value))
			
			return value
		
		if isinstance(kind, Field):
			kind.validator.validate(value, FieldContext(kind, obj))
			return kind.transformer.foreign(value, FieldContext(kind, obj))
		
		if kind:
			value = kind(**value)
		
		return value
757159
def deepvalues(mapping):
    """"""
    values = vals_sorted_by_key(mapping)
    for obj in values:
        mapping = False
        try:
            obj.items
        except AttributeError:
            pass
        else:
            mapping = True
            for subobj in deepvalues(obj):
                yield subobj
        if not mapping:
            yield obj
670414
def coerce(cls, key, value):
        """"""

        if isinstance(value, string_types):
            value = value.strip()
            if value[0] == '[':  # It's json encoded, probably
                try:
                    value = json.loads(value)
                except ValueError:
                    raise ValueError("Failed to parse JSON: '{}' ".format(value))
            else:
                value = value.split(',')

        if not value:
            value = []

        self = MutationList((MutationObj.coerce(key, v) for v in value))
        self._key = key
        return self
65706
def to_representation(self, value):
        """"""
        value = apply_subfield_projection(self, value, deep=True)
        return super().to_representation(value)
1249932
def get_value(self, node):
        """"""
        if not isinstance(node, ast.Dict):
            raise TypeError("must be a dictionary")

        evaluator = SafeEvaluator()
        try:
            value = evaluator.run(node)
        except Exception as ex:
            # TODO: Handle errors.
            raise ex

        try:
            # Ensure value is a serializable dictionary.
            value = json.loads(json.dumps(value))
            if not isinstance(value, dict):
                raise TypeError
        except (TypeError, ValueError):
            raise TypeError("must be serializable")

        return value
1240707
def prepare_data(self, data=None):
        '''
        
        '''
        data = data or self.export_data(native=True)
        # make sure we don't persist a null _id and let MongoDB auto-generate it
        if '_id' in data and data['_id'] is None:
            del data['_id']
        return data
1344495
def to_python(self, value, context=None):
        """"""
        value = value.copy()
        res = {}
        errors = []
        for field, schema in self._fields.items():
            name = schema.get_attr('name', field)
            if name in value:
                try:
                    res[field] = schema.to_python(
                        value.pop(name),
                        context=context
                    )
                except exceptions.ValidationErrors as ex:
                    self._update_errors_by_exception(errors, ex, name)
        self._raise_exception_when_errors(errors, value)
        res.update(value)
        return res
1048839
def clean(self, value):
        """"""

        if not isinstance(value, (list, tuple, set, GeneratorType)):
            value = [value]

        gen = (self.param_type.clean(x) for x in value)

        if isinstance(value, GeneratorType):
            return gen
        else:
            return list(gen)
530123
def coerce(cls, key, value):
        """"""

        if not isinstance(value, MutableDict):
            if isinstance(value, dict):
                return MutableDict(value)
            elif isinstance(value, six.string_types):
                # Assume JSON string
                if value:
                    return MutableDict(simplejson.loads(value, use_decimal=True))
                else:
                    return MutableDict()  # Empty value is an empty dict

            # this call will raise ValueError
            return Mutable.coerce(key, value)
        else:
            return value
1180801
function safeFormat(value, formatter) {
  if (value == null || isNaN(value)) {
    return value;
  }

  return formatter(value);
}
1137214
def transform_incoming(self, son, collection):
        

        def transform_value(value):
            if isinstance(value, collections.MutableMapping):
                if "_id" in value and "_ns" in value:
                    return DBRef(value["_ns"], transform_value(value["_id"]))
                else:
                    return transform_dict(SON(value))
            elif isinstance(value, list):
                return [transform_value(v) for v in value]
            return value

        def transform_dict(object):
            for (key, value) in object.items():
                object[key] = transform_value(value)
            return object

        return transform_dict(SON(son))
540024
def clean_new(self, value):
        """"""
        value = self.schema_class(value).full_clean()
        return self.object_class(**value)
953584
def clean(self, value):
        
        value = super(MongoEmbedded, self).clean(value)
        return self.document_class(**value)
957930
def _encode(cls, value):
        """"""

        value = json.dumps(value)
        return cls._ENC_RE.sub(lambda x: '%%%2x' % ord(x.group(0)), value)
60288
def to_set(self):
        '''
        '''
        if self.closed():
            raise ValueError("Attempt to call to_set() on a closed Queryable.")

        if isinstance(self._iterable, set):
            return self._iterable
        s = set()
        for item in self:
            if item in s:
                raise ValueError("Duplicate item value {0} in sequence "
                    "during to_set()".format(repr(item)))
            s.add(item)
        # Ideally we would close here
        #self.close()
        return s
957414
function transform(value, options) {
  options = options || {};

  return traverse(value, {
    beforeObject: function(v) {
      if (options.removeFormats &&
          typeof v.format === 'string' &&
          typeof v.type === 'string' &&
          v.type !== 'string') {
        delete v.format;
      }

      return v;
    },
    afterObject: function(v) {
      if (options.convertRefs &&
          typeof v.type === 'string' &&
          constants.notModel.indexOf(v.type) < 0) {
        return { $ref: v.type };
      }

      return v;
    },
  });
}
256766
def db_value(self, value):
        """"""
        if isinstance(value, string_types):
            value = arrow.get(value)

        if isinstance(value, arrow.Arrow):
            value = value.datetime

        return super(ArrowDateTimeField, self).db_value(value)