Coerce a value into a model object based on a class-type (cls).
    :param cls: class type to coerce into
    :param value: value to be coerced
    :return: original value or coerced value (value')
339773
def to_model(cls, value):
    

    if isinstance(value, cls) or value is None:
        pass  # skip if right type or value is None

    elif issubclass(cls, Enum):
        value = cls(value)

    elif is_model(cls) and isinstance(value, dict):
        value = convert_key_to_attr_names(cls, value)
        value = cls(**value)

    else:
        value = cls(value)

    return value
74141
def convert(self, value, view):
        
        if isinstance(value, NUMERIC_TYPES):
            return value
        else:
            self.fail(
                u'must be numeric, not {0}'.format(type(value).__name__),
                view,
                True
            )
1235291
def _user_object_converter(cls):
    # type: (Type[Any]) -> _AggregateConverter
    """"""
    def _from_dict(dict_value):
        try:
            object_value = cls(**dict_value)
        except TypeError:
            # Constructor does not support keyword arguments, try setting each
            # field individually.
            object_value = cls()
            for field_name, field_value in dict_value.items():
                setattr(object_value, field_name, field_value)

        return object_value

    def _to_dict(value):
        if value:
            return value.__dict__

        return {}

    return _AggregateConverter(from_dict=_from_dict, to_dict=_to_dict)
954504
def cast(self, value, **opts):
        
        if isinstance(value, self.result_type):
            return value
        if self._is_null(value):
            return None
        try:
            opts_ = self.opts.copy()
            opts_.update(opts)
            return self._cast(value, **opts_)
        except Exception as e:
            if not isinstance(e, ConverterError):
                e = ConverterError(None, exc=e)
            e.converter = self.__class__
            raise e
1156337
def coerce(value):
        
        if isinstance(value, ListCell):
            return value
        elif isinstance(value, (list)):
            return ListCell(value)
        else:
            return ListCell([value])
961912
def _cast_to_type(self, value):
        
        if not isinstance(value, list):
            self.fail('invalid', value=value)
        return value
281791
def coerce(cls, key, value):
        
        if not isinstance(value, MutableList):
            if isinstance(value, list):
                return MutableList(value)
            # this call will raise ValueError
            return Mutable.coerce(key, value)
        else:
            return value
1212552
def _cast(self, value):
        
        if self.type != 'text':
            value = utils.cast(self.TYPES.get(self.type)['cast'], value)
        return value
3708
def encode(cls, value):
        
        try:
            coerced = list(value)
            if coerced == value:
                return json.dumps(coerced).encode(cls._encoding)
        except TypeError:
            pass

        raise InvalidValue('not a list')
506377
def constraint_from_type(cls, value):
        
        if value is None:
            return None
        value_type = type(value)
        if value_type in (str, int, bool):
            return value_type
        raise ParameterError('Parameter type cannot be %s' % value_type)
1023650
private Object convert(Object value, Class type) {

		Object convertedObject = null;

		if (type.equals(String.class)) {

			// strings can be returned immediately
			return value.toString();

		} else if (value instanceof Number) {

			Number number = (Number) value;

			if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
				return number.intValue();

			} else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
				return number.longValue();

			} else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
				return number.doubleValue();

			} else if (type.equals(Float.class) || type.equals(Float.TYPE)) {
				return number.floatValue();

			} else if (type.equals(Short.class) || type.equals(Integer.TYPE)) {
				return number.shortValue();

			} else if (type.equals(Byte.class) || type.equals(Byte.TYPE)) {
				return number.byteValue();

			}

		} else if (value instanceof List) {

			return value;

		} else if (value instanceof Map) {
			return value;
		}

		// fallback
		try {

			Method valueOf = type.getMethod("valueOf", String.class);
			if (valueOf != null) {

				convertedObject = valueOf.invoke(null, value.toString());

			} else {

				logger.warn("Unable to find static valueOf method for type {}", type);
			}

		} catch (Throwable t) {

			logger.warn("Unable to deserialize value {} of type {}, Class has no static valueOf method.", new Object[]{value, type});
		}

		return convertedObject;
	}
642237
def to_python(self, value: Optional[str]) -> Optional[Any]:
        
        # https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
        # log.debug("to_python: {}, {}", value, type(value))
        if isinstance(value, datetime.datetime):
            return value
        if value is None:
            return value
        if value == '':
            return None
        return iso_string_to_python_datetime(value)
1048256
def _coerceValue(self,value,strict=0):
        
        try:
            if isinstance(value,str):
                # allow single blank-separated string as input
                value = value.split()
            if len(value) != len(self.value):
                raise IndexError
            v = len(self.value)*[0]
            for i in range(len(v)):
                v[i] = self._coerceOneValue(value[i],strict)
            return v
        except (IndexError, TypeError):
            raise ValueError("Value must be a " + repr(len(self.value)) +
                    "-element array for " + self.name)
519668
def to_one_str(cls, value, *args, **kwargs):
        
        if kwargs.get('wrapper'):
            return cls._wrapper_to_one_str(value)

        return _es.to_dict_str(value)
89125
def coerce(value):
        
        is_number = lambda x: isinstance(x, (int, float, complex)) #is x an instance of those things
        if isinstance(value, IntervalCell) or issubclass(value.__class__,IntervalCell): 
            #if intervalcell or subclass, return the subclass
            return value
        elif is_number(value):
            return IntervalCell(value, value)
        elif hasattr(value, 'low') and hasattr(value, 'high'):
            # duck type
            assert value.low <= value.high, "Invalid low/high in %s" % str(value)
            return value
        elif isinstance(value, (list, tuple)) and all(map(is_number, value)):
            if len(value) == 1:
                low, high = value[0], value[0]
            elif len(value) == 2:
                low, high = value
            else:
                low, high = min(value), max(value)
            if high < low:
                raise Contradiction("Low must be lte High") 
            return IntervalCell(low, high)
        else:
            raise Exception("Don't know how to coerce %s" % (type(value)))
1236217
def _value_to_python(value):
  """"""

  assert isinstance(value, struct_pb2.Value)
  field = value.WhichOneof('kind')
  if field == 'number_value':
    return value.number_value
  elif field == 'string_value':
    return value.string_value
  elif field == 'bool_value':
    return value.bool_value
  else:
    raise ValueError('Unknown struct_pb2.Value oneof field set: %s' % field)
1147423
def example_value(self):
        
        from .serializable import Serializable
        inst = self._static_example_value()
        if inst is tr.Undefined and issubclass(self.klass, Serializable):
            return self.klass.example_instance()
        return inst