Converts the input single value into the expected Python data type,
        raising django.core.exceptions.ValidationError if the data can't be
        converted.  Returns the converted value. Subclasses should override
        this.
507476
def value_to_python(self, value):
        
        if not isinstance(value, bytes):
            raise tldap.exceptions.ValidationError("should be bytes")
        if value is None:
            return value
        try:
            return int(value)
        except (TypeError, ValueError):
            raise tldap.exceptions.ValidationError("is invalid integer")
666927
def _check_values(self, value):
        
        key = self.to_field_name or 'pk'
        # deduplicate given values to avoid creating many querysets or
        # requiring the database backend deduplicate efficiently.
        try:
            value = frozenset(value)
        except TypeError:
            # list of lists isn't hashable, for example
            raise ValidationError(
                self.error_messages['list'],
                code='list',
            )
        for pk in value:
            try:
                self.queryset.filter(**{key: pk})
            except (ValueError, TypeError):
                raise ValidationError(
                    self.error_messages['invalid_pk_value'],
                    code='invalid_pk_value',
                    params={'pk': pk},
                )
        qs = EventOccurrence.objects.filter(**{'%s__in' % key: value})
        pks = set(force_text(getattr(o, key)) for o in qs)
        for val in value:
            if force_text(val) not in pks:
                raise ValidationError(
                    self.error_messages['invalid_choice'],
                    code='invalid_choice',
                    params={'value': val},
                )
        return qs
1126677
def convert(input, type):
        
        try:
            if not input:
                if type == Types.TYPE_STRING:
                    return ''
                else:
                    return None
            if type == Types.TYPE_STRING:
                if isinstance(input, datetime.date):
                    return input.strftime('%Y-%m-%d')
                else:
                    return input
            if type == Types.TYPE_FLOAT:
                return float(input)
            elif type == Types.TYPE_INT:
                return int(input)
            elif type == Types.TYPE_DATE:
                if isinstance(input, datetime.date):
                    return input
                else:
                    return datetime.datetime.strptime(input[0:10], '%Y-%m-%d')
            elif type == Types.TYPE_DATETIME:
                if isinstance(input, datetime.datetime):
                    return input
                else:
                    return datetime.datetime.strptime(input[0:19], '%Y-%m-%dT%H:%M:%S') # 2017-10-01T10:01:00.479+0300
            else:
                return NotImplementedError('Not supported type - {}'.format(type))
        except Exception as e:
            logging.error(e, exc_info=True)
            raise Exception(e)
1227973
def validate(self, value):
        
        if not isinstance(value, dict):
            self.raise_error('Only Python dict may be used in the DictField vs provided {0}'
                             .format(type(value).__name__))
        super(DictField, self).validate(value)
1342984
def validate(self, value):
        
        if value == '':
            if self.kwargs.get('nullable', __nullable__):
                value = None
            else:
                value = 0
            
        if not isinstance(value, Model):
            return super(ReferenceProperty, self).validate(value)

        if not value.is_saved():
            raise BadValueError(
                    '%s instance must be saved before it can be stored as a '
                    'reference' % self.reference_class.__class__.__name__)
        if not isinstance(value, self.reference_class):
            raise KindError('Property %s must be an instance of %s' %
                    (self.name, self.reference_class.__class__.__name__))

        return value
77389
def GetDataAsObject(self):
    
    if not self._data:
      return None

    if self._data_type in self._STRING_VALUE_TYPES:
      try:
        return self._data.decode('utf-16-le')

      # AttributeError is raised when self._data has no decode method.
      except AttributeError as exception:
        raise errors.WinRegistryValueError((
            'Unsupported data type: {0!s} of value: {1!s} with error: '
            '{2!s}').format(type(self._data), self._name, exception))

      except UnicodeError as exception:
        raise errors.WinRegistryValueError(
            'Unable to decode data of value: {0!s} with error: {1!s}'.format(
                self._name, exception))

    elif (self._data_type == definitions.REG_DWORD and
          self._data_size == 4):
      return self._INT32_LITTLE_ENDIAN.MapByteStream(self._data)

    elif (self._data_type == definitions.REG_DWORD_BIG_ENDIAN and
          self._data_size == 4):
      return self._INT32_BIG_ENDIAN.MapByteStream(self._data)

    elif (self._data_type == definitions.REG_QWORD and
          self._data_size == 8):
      return self._INT64_LITTLE_ENDIAN.MapByteStream(self._data)

    elif self._data_type == definitions.REG_MULTI_SZ:
      try:
        utf16_string = self._data.decode('utf-16-le')
        # TODO: evaluate the use of filter here is appropriate behavior.
        return list(filter(None, utf16_string.split('\x00')))

      # AttributeError is raised when self._data has no decode method.
      except AttributeError as exception:
        raise errors.WinRegistryValueError((
            'Unsupported data type: {0!s} of value: {1!s} with error: '
            '{2!s}').format(type(self._data), self._name, exception))

      except UnicodeError as exception:
        raise errors.WinRegistryValueError(
            'Unable to read data from value: {0!s} with error: {1!s}'.format(
                self._name, exception))

    return self._data
206439
def validate(self, value, model_instance):
        
        if not isinstance(value, base.StateWrapper):
            raise exceptions.ValidationError(self.error_messages['wrong_type'] % value)
        elif not value.workflow == self.workflow:
            raise exceptions.ValidationError(self.error_messages['wrong_workflow'] % value.workflow)
        elif value.state not in self.workflow.states:
            raise exceptions.ValidationError(self.error_messages['invalid_state'] % value.state)
1318731
def _cast_to_type(self, value):
        
        if not isinstance(value, dict):
            self.fail('invalid', value=value)
        return value
906246
def value_to_python(self, value):
        
        if not isinstance(value, bytes):
            raise tldap.exceptions.ValidationError("should be a bytes")

        length = len(value) - 8
        if length % 4 != 0:
            raise tldap.exceptions.ValidationError("Invalid sid")

        length = length // 4

        array = struct.unpack('<bbbbbbbb' + 'I' * length, value)

        if array[1] != length:
            raise tldap.exceptions.ValidationError("Invalid sid")

        if array[2:7] != (0, 0, 0, 0, 0):
            raise tldap.exceptions.ValidationError("Invalid sid")

        array = ("S", ) + array[0:1] + array[7:]
        return "-".join([str(i) for i in array])
220882
def to_single_data(input):
    
    if (isinstance(input, (list, tuple)) and len(input) == 1):
        return input[0]
    else:
        assert isinstance(input, dict), input
        return input
325642
def validate(self, value):
        
        try:
            v = int(value)
            if v not in self.allowed:
                return None
            return value
        except ValueError:
            return None
1254200
def convert(data):
    
    try:
        st = basestring
    except NameError:
        st = str
    if isinstance(data, st):
        return str(data)
    elif isinstance(data, Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, Iterable):
        return type(data)(map(convert, data))
    else:
        return data
1014308
def validate_element(self, value):
        
        # If value is str is it considered valid.  Satisfies "required=True".
        if isinstance(value, bytes):
            try:
                six.text_type(value, 'UTF-8')
            except UnicodeDecodeError as err:
                try:
                    _ = self.name
                except AttributeError:
                    validation_error = ValidationError(
                        'Field encountered non-UTF-8 string %r: %s' % (value,
                                                                       err))
                else:
                    validation_error = ValidationError(
                        'Field %s encountered non-UTF-8 string %r: %s' % (
                            self.name, value, err))
                    validation_error.field_name = self.name
                raise validation_error
        else:
            return super(StringField, self).validate_element(value)
        return value
77542
def _validate(self, value):
        
        if value is None:
            raise ValueError('The pk for %s is not "auto-increment", you must fill it' %
                            self._model.__name__)
        value = self.normalize(value)

        # Check that this pk does not already exist
        if self.exists(value):
            raise UniquenessError('PKField %s already exists for model %s)' %
                                  (value, self._instance.__class__))

        return value
908516
def to_python(self, value):
        
        if not value:
            return {}
        elif isinstance(value, six.string_types):
            res = loads(value)
            assert isinstance(res, dict)
            return JSONDict(**res)
        else:
            return value
418059
def validate(self, raw_data, **kwargs):
        
        try:
            converted_data = int(raw_data)
            return super(IntegerField, self).validate(converted_data)
        except ValueError:
            raise ValidationException(self.messages['invalid'], repr(raw_data))
1197551
def to_internal_value_single(self, data, serializer):
        """"""
        related_model = serializer.Meta.model
        if isinstance(data, related_model):
            return data
        try:
            instance = related_model.objects.get(pk=data)
        except related_model.DoesNotExist:
            raise ValidationError(
                "Invalid value for '%s': %s object with ID=%s not found" %
                (self.field_name, related_model.__name__, data)
            )
        return instance