gurudesh/pytracebugs huggingface dataset:
# Buggy code
def view(request, *args, **kwargs):
    self = cls(**initkwargs)
    # We also store the mapping of request methods to actions,
    # so that we can later set the action attribute.
    # eg. `self.action = 'list'` on an incoming GET request.
    self.action_map = actions

    # Bind methods to actions
    # This is the bit that's different to a standard view
    for method, action in actions.items():
        handler = getattr(self, action)
        setattr(self, method, handler)

    # And continue as usual
    return self.dispatch(request, *args, **kwargs)


# Traceback (AssertionError)
pip show djangorestframework
---
Name: djangorestframework
Version: 3.5.3
Location: /home/matwey/temp/venv/lib/python3.4/site-packages
Requires:
(venv)matwey@epsilon:~/temp/drf_test> python runtests.py
Creating test database for alias 'default' ('file:memorydb_default?mode=memory&amp;cache=shared')...
Operations to perform:
Synchronize unmigrated apps: rest_framework, theapp
Apply all migrations: auth, authtoken, contenttypes
Synchronizing apps without migrations:
Creating tables...
Creating table theapp_model
Running deferred SQL...
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0001_initial... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying authtoken.0001_initial... OK
Applying authtoken.0002_auto_20160226_1747... OK
test_model_head1 (tests.test.ModelTest) ... FAIL

======================================================================
FAIL: test_model_head1 (tests.test.ModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/matwey/temp/drf_test/tests/test.py", line 18, in test_model_head1
self.assertEqual(response.status_code, status.HTTP_200_OK)
AssertionError: 405 != 200

----------------------------------------------------------------------
Ran 1 test in 0.083s

FAILED (failures=1)
Destroying test database for alias 'default' ('file:memorydb_default?mode=memory&amp;cache=shared')...

# Fixed code
def view(request, *args, **kwargs):
    self = cls(**initkwargs)
    # We also store the mapping of request methods to actions,
    # so that we can later set the action attribute.
    # eg. `self.action = 'list'` on an incoming GET request.
    self.action_map = actions

    # Bind methods to actions
    # This is the bit that's different to a standard view
    for method, action in actions.items():
        handler = getattr(self, action)
        setattr(self, method, handler)

    if hasattr(self, "get") and not hasattr(self, "head"):
        self.head = self.get

    # And continue as usual
    return self.dispatch(request, *args, **kwargs)
# Buggy code
def to_representation(self, value):
    if self.format is None:
        return value

    # Applying a `DateField` to a datetime value is almost always
    # not a sensible thing to do, as it means naively dropping
    # any explicit or implicit timezone info.
    assert not isinstance(value, datetime.datetime), (
        "Expected a `date`, but got a `datetime`. Refusing to coerce, "
        "as this may mean losing timezone information. Use a custom "
        "read-only field and deal with timezone issues explicitly."
    )

    if self.format.lower() == ISO_8601:
        return value.isoformat()
    return value.strftime(self.format)


# Traceback (AttributeError)
Traceback (most recent call last):
File "tests.py", line 10, in test_post_root_view
response = self.view(request).render()
File "/path/to/django/views/decorators/csrf.py", line 57, in wrapped_view
return view_func(*args, **kwargs)
File "/path/to/rest_framework/viewsets.py", line 85, in view
return self.dispatch(request, *args, **kwargs)
File "/path/to/rest_framework/views.py", line 452, in dispatch
response = self.handle_exception(exc)
File "/path/to/rest_framework/views.py", line 449, in dispatch
response = handler(request, *args, **kwargs)
File "/path/to/rest_framework/mixins.py", line 57, in retrieve
return Response(serializer.data)
File "/path/to/rest_framework/serializers.py", line 467, in data
ret = super(Serializer, self).data
File "/path/to/rest_framework/serializers.py", line 213, in data
self._data = self.to_representation(self.instance)
File "/path/to/rest_framework/serializers.py", line 436, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/path/to/rest_framework/fields.py", line 940, in to_representation
return value.isoformat()
AttributeError: 'str' object has no attribute 'isoformat'

# Fixed code
def to_representation(self, value):
    if not value:
        return None

    if self.format is None:
        return value

    # Applying a `DateField` to a datetime value is almost always
    # not a sensible thing to do, as it means naively dropping
    # any explicit or implicit timezone info.
    assert not isinstance(value, datetime.datetime), (
        "Expected a `date`, but got a `datetime`. Refusing to coerce, "
        "as this may mean losing timezone information. Use a custom "
        "read-only field and deal with timezone issues explicitly."
    )

    if self.format.lower() == ISO_8601:
        if isinstance(value, str):
            value = datetime.datetime.strptime(value, "%Y-%m-%d").date()
        return value.isoformat()

    return value.strftime(self.format)
# Buggy code
def set_context(self, serializer_field):
    self.is_update = serializer_field.parent.instance is not None


# Traceback (KeyError)
======================================================================
ERROR: test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid (users.tests.unit.test_user_serializer.UserSerializationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/omer/Documents/Projects/startup/users/tests/unit/test_user_serializer.py", line 29, in test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid
sut.is_valid()
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 103, in is_valid
self._validated_data = self.run_validation(self._initial_data)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 328, in run_validation
self.run_validators(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/fields.py", line 275, in run_validators
validator(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in __call__
(field_name, value[field_name]) for field_name in self.fields
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in <listcomp>
(field_name, value[field_name]) for field_name in self.fields
KeyError: 'slug'

# Fixed code
def set_context(self, serializer_field):
    self.user = serializer_field.context["request"].user
# Buggy code
def __call__(self):
    if self.is_update:
        raise SkipField()
    if callable(self.default):
        return self.default()
    return self.default


# Traceback (KeyError)
======================================================================
ERROR: test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid (users.tests.unit.test_user_serializer.UserSerializationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/omer/Documents/Projects/startup/users/tests/unit/test_user_serializer.py", line 29, in test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid
sut.is_valid()
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 103, in is_valid
self._validated_data = self.run_validation(self._initial_data)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 328, in run_validation
self.run_validators(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/fields.py", line 275, in run_validators
validator(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in __call__
(field_name, value[field_name]) for field_name in self.fields
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in <listcomp>
(field_name, value[field_name]) for field_name in self.fields
KeyError: 'slug'

# Fixed code
def __call__(self):
    return self.user
# Buggy code
def set_context(self, serializer_field):
    # Determine the underlying model field name. This may not be the
    # same as the serializer field name if `source=<>` is set.
    self.field_name = serializer_field.source_attrs[0]
    # Determine the existing instance, if this is an update operation.
    self.instance = getattr(serializer_field.parent, "instance", None)


# Traceback (KeyError)
======================================================================
ERROR: test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid (users.tests.unit.test_user_serializer.UserSerializationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/omer/Documents/Projects/startup/users/tests/unit/test_user_serializer.py", line 29, in test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid
sut.is_valid()
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 103, in is_valid
self._validated_data = self.run_validation(self._initial_data)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 328, in run_validation
self.run_validators(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/fields.py", line 275, in run_validators
validator(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in __call__
(field_name, value[field_name]) for field_name in self.fields
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in <listcomp>
(field_name, value[field_name]) for field_name in self.fields
KeyError: 'slug'

# Fixed code
def set_context(self, serializer_field):
    """
    This hook is called by the serializer instance,
    prior to the validation call being made.
    """
    # Determine the underlying model field name. This may not be the
    # same as the serializer field name if `source=<>` is set.
    self.field_name = serializer_field.source_attrs[0]
    # Determine the existing instance, if this is an update operation.
    self.instance = getattr(serializer_field.parent, "instance", None)
# Buggy code
def set_context(self, serializer):
    # Determine the existing instance, if this is an update operation.
    self.instance = getattr(serializer, "instance", None)


# Traceback (KeyError)
======================================================================
ERROR: test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid (users.tests.unit.test_user_serializer.UserSerializationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/omer/Documents/Projects/startup/users/tests/unit/test_user_serializer.py", line 29, in test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid
sut.is_valid()
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 103, in is_valid
self._validated_data = self.run_validation(self._initial_data)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 328, in run_validation
self.run_validators(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/fields.py", line 275, in run_validators
validator(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in __call__
(field_name, value[field_name]) for field_name in self.fields
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in <listcomp>
(field_name, value[field_name]) for field_name in self.fields
KeyError: 'slug'

# Fixed code
def set_context(self, serializer):
    """
    This hook is called by the serializer instance,
    prior to the validation call being made.
    """
    # Determine the existing instance, if this is an update operation.
    self.instance = getattr(serializer, "instance", None)
# Buggy code
def __call__(self, attrs):
    # Ensure uniqueness.
    filter_kwargs = dict(
        [(field_name, attrs[field_name]) for field_name in self.fields]
    )
    queryset = self.queryset.filter(**filter_kwargs)
    if self.instance is not None:
        queryset = queryset.exclude(pk=self.instance.pk)
    if queryset.exists():
        field_names = ", ".join(self.fields)
        raise ValidationError(self.message.format(field_names=field_names))


# Traceback (KeyError)
======================================================================
ERROR: test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid (users.tests.unit.test_user_serializer.UserSerializationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/omer/Documents/Projects/startup/users/tests/unit/test_user_serializer.py", line 29, in test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid
sut.is_valid()
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 103, in is_valid
self._validated_data = self.run_validation(self._initial_data)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 328, in run_validation
self.run_validators(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/fields.py", line 275, in run_validators
validator(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in __call__
(field_name, value[field_name]) for field_name in self.fields
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in <listcomp>
(field_name, value[field_name]) for field_name in self.fields
KeyError: 'slug'

# Fixed code
def __call__(self, attrs):
    self.enforce_required_fields(attrs)
    queryset = self.queryset
    queryset = self.filter_queryset(attrs, queryset)
    queryset = self.exclude_current_instance(attrs, queryset)
    if queryset.exists():
        field_names = ", ".join(self.fields)
        raise ValidationError(self.message.format(field_names=field_names))
# Buggy code
def set_context(self, serializer):
    # Determine the underlying model field names. These may not be the
    # same as the serializer field names if `source=<>` is set.
    self.field_name = serializer.fields[self.field].source_attrs[0]
    self.date_field_name = serializer.fields[self.date_field].source_attrs[0]
    # Determine the existing instance, if this is an update operation.
    self.instance = getattr(serializer, "instance", None)


# Traceback (KeyError)
======================================================================
ERROR: test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid (users.tests.unit.test_user_serializer.UserSerializationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/omer/Documents/Projects/startup/users/tests/unit/test_user_serializer.py", line 29, in test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid
sut.is_valid()
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 103, in is_valid
self._validated_data = self.run_validation(self._initial_data)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 328, in run_validation
self.run_validators(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/fields.py", line 275, in run_validators
validator(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in __call__
(field_name, value[field_name]) for field_name in self.fields
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in <listcomp>
(field_name, value[field_name]) for field_name in self.fields
KeyError: 'slug'

# Fixed code
def set_context(self, serializer):
    """
    This hook is called by the serializer instance,
    prior to the validation call being made.
    """
    # Determine the underlying model field names. These may not be the
    # same as the serializer field names if `source=<>` is set.
    self.field_name = serializer.fields[self.field].source_attrs[0]
    self.date_field_name = serializer.fields[self.date_field].source_attrs[0]
    # Determine the existing instance, if this is an update operation.
    self.instance = getattr(serializer, "instance", None)
# Buggy code
def __call__(self, attrs):
    filter_kwargs = self.get_filter_kwargs(attrs)

    queryset = self.queryset.filter(**filter_kwargs)
    if self.instance is not None:
        queryset = queryset.exclude(pk=self.instance.pk)
    if queryset.exists():
        message = self.message.format(date_field=self.date_field)
        raise ValidationError({self.field: message})


# Traceback (KeyError)
======================================================================
ERROR: test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid (users.tests.unit.test_user_serializer.UserSerializationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/omer/Documents/Projects/startup/users/tests/unit/test_user_serializer.py", line 29, in test_that_when_serializing_a_user_with_a_modified_password_but_without_the_old_password_then_the_serializer_is_not_valid
sut.is_valid()
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 103, in is_valid
self._validated_data = self.run_validation(self._initial_data)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/serializers.py", line 328, in run_validation
self.run_validators(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/fields.py", line 275, in run_validators
validator(value)
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in __call__
(field_name, value[field_name]) for field_name in self.fields
File "/home/omer/.virtualenvs/startup/lib/python3.4/site-packages/rest_framework/validators.py", line 71, in <listcomp>
(field_name, value[field_name]) for field_name in self.fields
KeyError: 'slug'

# Fixed code
def __call__(self, attrs):
    self.enforce_required_fields(attrs)
    queryset = self.queryset
    queryset = self.filter_queryset(attrs, queryset)
    queryset = self.exclude_current_instance(attrs, queryset)
    if queryset.exists():
        message = self.message.format(date_field=self.date_field)
        raise ValidationError({self.field: message})
# Buggy code
def _getDateTime(self):
    """
    Returns a Python datetime object.

    :rtype: :class:`datetime.datetime`
    :return: Python datetime object.

    .. rubric:: Example

    >>> dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)
    >>> dt.datetime
    datetime.datetime(2008, 10, 1, 12, 30, 35, 45020)
    """
    # we are exact at the border of floating point precision
    # datetime.utcfromtimestamp will cut off but not round
    # avoid through adding extra timedelta
    _fsec, _isec = math.modf(self.timestamp)
    return datetime.datetime.utcfromtimestamp(_isec) + datetime.timedelta(seconds=_fsec)


# Traceback (ValueError)
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from obspy.core import UTCDateTime
t = UTCDateTime("2014-05-23T22:35:30")
print t
2014-05-23T22:35:30.000000Z
t = UTCDateTime("2599-05-23T22:35:30")
print t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 895, in __str__
return "%s%sZ" % (self.strftime('%Y-%m-%dT%H:%M:%S'),
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 1126, in strftime
return self._getDateTime().strftime(format)
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 492, in _getDateTime
return datetime.datetime.utcfromtimestamp(self.timestamp)
ValueError: timestamp out of range for platform time_t

# Fixed code
def _getDateTime(self):
    """
    Returns a Python datetime object.

    :rtype: :class:`datetime.datetime`
    :return: Python datetime object.

    .. rubric:: Example

    >>> dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)
    >>> dt.datetime
    datetime.datetime(2008, 10, 1, 12, 30, 35, 45020)
    """
    # datetime.utcfromtimestamp will cut off but not round
    # avoid through adding timedelta - also avoids 2038 problem
    return datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(
        seconds=self.timestamp
    )
# Buggy code
def _getDateTime(self):
    """
    Returns a Python datetime object.

    :rtype: :class:`datetime.datetime`
    :return: Python datetime object.

    .. rubric:: Example

    >>> dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)
    >>> dt.datetime
    datetime.datetime(2008, 10, 1, 12, 30, 35, 45020)
    """
    # datetime.utcfromtimestamp will cut off but not round
    # avoid through adding timedelta - also avoids 2038 problem
    return datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(
        seconds=self.timestamp
    )


# Traceback (ValueError)
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from obspy.core import UTCDateTime
t = UTCDateTime("2014-05-23T22:35:30")
print t
2014-05-23T22:35:30.000000Z
t = UTCDateTime("2599-05-23T22:35:30")
print t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 895, in __str__
return "%s%sZ" % (self.strftime('%Y-%m-%dT%H:%M:%S'),
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 1126, in strftime
return self._getDateTime().strftime(format)
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 492, in _getDateTime
return datetime.datetime.utcfromtimestamp(self.timestamp)
ValueError: timestamp out of range for platform time_t

# Fixed code
def _getDateTime(self):
    """
    Returns a Python datetime object.

    :rtype: :class:`datetime.datetime`
    :return: Python datetime object.

    .. rubric:: Example

    >>> dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)
    >>> dt.datetime
    datetime.datetime(2008, 10, 1, 12, 30, 35, 45020)
    """
    # datetime.utcfromtimestamp will cut off but not round
    # avoid through adding timedelta - also avoids the year 2038 problem
    return datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(
        seconds=self.timestamp
    )
# Buggy code
def _getDateTime(self):
    """
    Returns a Python datetime object.

    :rtype: :class:`datetime.datetime`
    :return: Python datetime object.

    .. rubric:: Example

    >>> dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)
    >>> dt.datetime
    datetime.datetime(2008, 10, 1, 12, 30, 35, 45020)
    """
    return datetime.datetime.utcfromtimestamp(self.timestamp)


# Traceback (ValueError)
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from obspy.core import UTCDateTime
t = UTCDateTime("2014-05-23T22:35:30")
print t
2014-05-23T22:35:30.000000Z
t = UTCDateTime("2599-05-23T22:35:30")
print t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 895, in __str__
return "%s%sZ" % (self.strftime('%Y-%m-%dT%H:%M:%S'),
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 1126, in strftime
return self._getDateTime().strftime(format)
File "/usr/lib/python2.7/dist-packages/obspy/core/utcdatetime.py", line 492, in _getDateTime
return datetime.datetime.utcfromtimestamp(self.timestamp)
ValueError: timestamp out of range for platform time_t

# Fixed code
def _getDateTime(self):
    """
    Returns a Python datetime object.

    :rtype: :class:`datetime.datetime`
    :return: Python datetime object.

    .. rubric:: Example

    >>> dt = UTCDateTime(2008, 10, 1, 12, 30, 35, 45020)
    >>> dt.datetime
    datetime.datetime(2008, 10, 1, 12, 30, 35, 45020)
    """
    # datetime.utcfromtimestamp will cut off but not round
    # avoid through adding timedelta - also avoids 2038 problem
    return datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(
        seconds=self.timestamp
    )
# Buggy code
def isQuakeML(filename):
    """
    Checks whether a file is QuakeML format.

    :type filename: str
    :param filename: Name of the QuakeML file to be checked.
    :rtype: bool
    :return: ``True`` if QuakeML file.

    .. rubric:: Example

    >>> isQuakeML('/path/to/quakeml.xml')  # doctest: +SKIP
    True
    """
    try:
        p = XMLParser(filename)
    except:
        False
    # check node "*/eventParameters/event" for the global namespace exists
    try:
        namespace = p._getFirstChildNamespace()
        p.xpath("eventParameters", namespace=namespace)[0]
    except:
        return False
    return True


# Traceback (ValueError)
Traceback (most recent call last):
File "/tmp/testrun/git/obspy/core/tests/test_util_xmlwrapper.py", line 49, in test_init
XMLParser(fh)
File "/tmp/testrun/git/obspy/core/util/xmlwrapper.py", line 73, in __init__
xml_doc.seek(0)
ValueError: I/O operation on closed file

# Fixed code
def isQuakeML(filename):
    """
    Checks whether a file is QuakeML format.

    :type filename: str
    :param filename: Name of the QuakeML file to be checked.
    :rtype: bool
    :return: ``True`` if QuakeML file.

    .. rubric:: Example

    >>> isQuakeML('/path/to/quakeml.xml')  # doctest: +SKIP
    True
    """
    try:
        xml_doc = XMLParser(filename)
    except:
        return False
    # check if node "*/eventParameters/event" for the global namespace exists
    try:
        namespace = xml_doc._getFirstChildNamespace()
        xml_doc.xpath("eventParameters", namespace=namespace)[0]
    except:
        return False
    return True
# Buggy code
def __init__(self, xml_doc, namespace=None):
    """
    Initializes a XMLPaser object.

    :type xml_doc: str, filename, file-like object, parsed XML document
    :param xml_doc: XML document
    :type namespace: str, optional
    :param namespace: Document-wide default namespace. Defaults to ``''``.
    """
    if isinstance(xml_doc, basestring):
        # some string - check if it starts with <?xml
        if xml_doc.strip()[0:5].upper().startswith("<?XML"):
            xml_doc = StringIO.StringIO(xml_doc)
        # parse XML file
        self.xml_doc = etree.parse(xml_doc)
    elif hasattr(xml_doc, "seek"):
        # some file-based content
        self.xml_doc = etree.parse(xml_doc)
    else:
        self.xml_doc = xml_doc
    self.xml_root = self.xml_doc.getroot()
    self.namespace = namespace or self._getRootNamespace()


# Traceback (ValueError)
Traceback (most recent call last):
File "/tmp/testrun/git/obspy/core/tests/test_util_xmlwrapper.py", line 49, in test_init
XMLParser(fh)
File "/tmp/testrun/git/obspy/core/util/xmlwrapper.py", line 73, in __init__
xml_doc.seek(0)
ValueError: I/O operation on closed file

# Fixed code
def __init__(self, xml_doc, namespace=None):
    """
    Initializes a XMLPaser object.

    :type xml_doc: str, filename, file-like object, parsed XML document
    :param xml_doc: XML document
    :type namespace: str, optional
    :param namespace: Document-wide default namespace. Defaults to ``''``.
    """
    if isinstance(xml_doc, basestring):
        # some string - check if it starts with <?xml
        if xml_doc.strip()[0:5].upper().startswith("<?XML"):
            xml_doc = StringIO.StringIO(xml_doc)
        # parse XML file
        self.xml_doc = etree.parse(xml_doc)
    elif hasattr(xml_doc, "seek"):
        # some file-based content
        xml_doc.seek(0)
        self.xml_doc = etree.parse(xml_doc)
    else:
        self.xml_doc = xml_doc
    self.xml_root = self.xml_doc.getroot()
    self.namespace = namespace or self._getRootNamespace()
# Buggy code
def __init__(self, xml_doc, namespace=None):
    """
    Initializes a XMLPaser object.

    :type xml_doc: str, filename, file-like object, parsed XML document
    :param xml_doc: XML document
    :type namespace: str, optional
    :param namespace: Document-wide default namespace. Defaults to ``''``.
    """
    if isinstance(xml_doc, basestring):
        # some string - check if it starts with <?xml
        if xml_doc.strip()[0:5].upper().startswith("<?XML"):
            xml_doc = StringIO.StringIO(xml_doc)
        # parse XML file
        self.xml_doc = etree.parse(xml_doc)
    elif hasattr(xml_doc, "seek"):
        self.xml_doc = etree.parse(xml_doc)
        # fixes a problem on debian squeeze default python installation.
        # xml.etree.parse seems to not rewind the file after parsing, see
        # http://tests.obspy.org/?id=3430#0
        xml_doc.seek(0)
    else:
        self.xml_doc = xml_doc
    self.xml_root = self.xml_doc.getroot()
    self.namespace = namespace or self._getRootNamespace()


# Traceback (ValueError)
Traceback (most recent call last):
File "/tmp/testrun/git/obspy/core/tests/test_util_xmlwrapper.py", line 49, in test_init
XMLParser(fh)
File "/tmp/testrun/git/obspy/core/util/xmlwrapper.py", line 73, in __init__
xml_doc.seek(0)
ValueError: I/O operation on closed file

# Fixed code
def __init__(self, xml_doc, namespace=None):
    """
    Initializes a XMLPaser object.

    :type xml_doc: str, filename, file-like object, parsed XML document
    :param xml_doc: XML document
    :type namespace: str, optional
    :param namespace: Document-wide default namespace. Defaults to ``''``.
    """
    if isinstance(xml_doc, basestring):
        # some string - check if it starts with <?xml
        if xml_doc.strip()[0:5].upper().startswith("<?XML"):
            xml_doc = StringIO.StringIO(xml_doc)
        # parse XML file
        self.xml_doc = etree.parse(xml_doc)
    elif hasattr(xml_doc, "seek"):
        # some file-based content
        xml_doc.seek(0)
        self.xml_doc = etree.parse(xml_doc)
        # fixes a problem on debian squeeze default python installation.
        # xml.etree.parse seems to not rewind the file after parsing, see
        # http://tests.obspy.org/?id=3430#0
        xml_doc.seek(0)
    else:
        self.xml_doc = xml_doc
    self.xml_root = self.xml_doc.getroot()
    self.namespace = namespace or self._getRootNamespace()
# Buggy code
def __setattr__(self, key, value):
    self[key] = value


# Traceback (KeyError)
捕获未处理异常,异常具体堆栈->[Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/blueapps/account/decorators.py", line 20, in wrapped_view
return view_func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner
return func(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/bkoauth/decorators.py", line 17, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/app/gcloud/apigw/decorators.py", line 77, in wrapper
return view_func(request, *args, **kwargs)
File "/app/gcloud/apigw/decorators.py", line 122, in wrapper
return view_func(request, *args, **kwargs)
File "/app/gcloud/apigw/decorators.py", line 215, in wrapper
return view_func(request, *args, **kwargs)
File "/app/gcloud/apigw/views/get_task_detail.py", line 68, in get_task_detail
data = task.get_task_detail()
File "/app/gcloud/taskflow3/models.py", line 1372, in get_task_detail
out['name'] = constants[out['key']]['name']
KeyError: '__dict__'

# Fixed code
def __setattr__(self, key, value):
    # 内建属性不放入 key 中
    if key.startswith("__") and key.endswith("__"):
        super().__setattr__(key, value)
    else:
        self[key] = value
# Buggy code
def get_user_info(request):
    client = get_client_by_request(request)
    auth = getattr(client, settings.ESB_AUTH_COMPONENT_SYSTEM)
    _get_user_info = getattr(auth, settings.ESB_AUTH_GET_USER_INFO)
    user_info = _get_user_info({})
    if "data" in user_info:
        user_info["data"]["bk_supplier_account"] = 0
    return user_info


# Traceback (ImportError)
------STARTING: Migrate Database------
Traceback (most recent call last):
File "manage.py", line 27, in <module>
execute_from_command_line(sys.argv)
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py", line 112, in create
mod = import_module(mod_path)
File "/cache/.bk/env/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/app/code/pipeline/apps.py", line 18, in <module>
from rediscluster import StrictRedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py", line 7, in <module>
from .client import StrictRedisCluster, RedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py", line 10, in <module>
from .connection import (
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py", line 11, in <module>
from .nodemanager import NodeManager
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py", line 12, in <module>
from redis._compat import b, unicode, bytes, long, basestring
ImportError: cannot import name b
------FAILURE: Migrate Database------

# Fixed code
def get_user_info(request):
    client = get_client_by_user(request.user.username)
    auth = getattr(client, settings.ESB_AUTH_COMPONENT_SYSTEM)
    _get_user_info = getattr(auth, settings.ESB_AUTH_GET_USER_INFO)
    user_info = _get_user_info({})
    if user_info["result"]:
        user_info["data"]["bk_supplier_account"] = 0
    return user_info
# Buggy code
def get_job_instance_log(request, biz_cc_id):
    client = get_client_by_request(request)
    job_instance_id = request.GET.get("job_instance_id")
    log_kwargs = {"bk_biz_id": biz_cc_id, "job_instance_id": job_instance_id}
    log_result = client.job.get_job_instance_log(log_kwargs)
    return JsonResponse(log_result)


# Traceback (ImportError)
------STARTING: Migrate Database------
Traceback (most recent call last):
File "manage.py", line 27, in <module>
execute_from_command_line(sys.argv)
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py", line 112, in create
mod = import_module(mod_path)
File "/cache/.bk/env/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/app/code/pipeline/apps.py", line 18, in <module>
from rediscluster import StrictRedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py", line 7, in <module>
from .client import StrictRedisCluster, RedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py", line 10, in <module>
from .connection import (
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py", line 11, in <module>
from .nodemanager import NodeManager
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py", line 12, in <module>
from redis._compat import b, unicode, bytes, long, basestring
ImportError: cannot import name b
------FAILURE: Migrate Database------

# Fixed code
def get_job_instance_log(request, biz_cc_id):
    client = get_client_by_user(request.user.username)
    job_instance_id = request.GET.get("job_instance_id")
    log_kwargs = {"bk_biz_id": biz_cc_id, "job_instance_id": job_instance_id}
    log_result = client.job.get_job_instance_log(log_kwargs)
    return JsonResponse(log_result)
# Buggy code
def job_get_job_tasks_by_biz(request, biz_cc_id):
    client = get_client_by_request(request)
    job_result = client.job.get_job_list({"bk_biz_id": biz_cc_id})
    if not job_result["result"]:
        message = _(
            "查询作业平台(JOB)的作业模板[app_id=%s]接口job.get_task返回失败: %s"
        ) % (biz_cc_id, job_result["message"])
        logger.error(message)
        result = {"result": False, "data": [], "message": message}
        return JsonResponse(result)
    task_list = []
    for task in job_result["data"]:
        task_list.append(
            {
                "value": task["bk_job_id"],
                "text": task["name"],
            }
        )
    return JsonResponse({"result": True, "data": task_list})


# Traceback (ImportError)
------STARTING: Migrate Database------
Traceback (most recent call last):
File "manage.py", line 27, in <module>
execute_from_command_line(sys.argv)
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py", line 112, in create
mod = import_module(mod_path)
File "/cache/.bk/env/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/app/code/pipeline/apps.py", line 18, in <module>
from rediscluster import StrictRedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py", line 7, in <module>
from .client import StrictRedisCluster, RedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py", line 10, in <module>
from .connection import (
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py", line 11, in <module>
from .nodemanager import NodeManager
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py", line 12, in <module>
from redis._compat import b, unicode, bytes, long, basestring
ImportError: cannot import name b
------FAILURE: Migrate Database------

# Fixed code
def job_get_job_tasks_by_biz(request, biz_cc_id):
    client = get_client_by_user(request.user.username)
    job_result = client.job.get_job_list({"bk_biz_id": biz_cc_id})
    if not job_result["result"]:
        message = _(
            "查询作业平台(JOB)的作业模板[app_id=%s]接口job.get_task返回失败: %s"
        ) % (biz_cc_id, job_result["message"])
        logger.error(message)
        result = {"result": False, "data": [], "message": message}
        return JsonResponse(result)
    task_list = []
    for task in job_result["data"]:
        task_list.append(
            {
                "value": task["bk_job_id"],
                "text": task["name"],
            }
        )
    return JsonResponse({"result": True, "data": task_list})
# Buggy code
def get_bk_user(request):
    bkuser = None
    if request.weixin_user and not isinstance(request.weixin_user, AnonymousUser):
        try:
            user_property = UserProperty.objects.get(
                key="wx_userid", value=request.weixin_user.userid
            )
            bkuser = user_property.user
        except UserProperty.DoesNotExist:
            bkuser = None
    return bkuser or AnonymousUser()


# Traceback (ImportError)
------STARTING: Migrate Database------
Traceback (most recent call last):
File "manage.py", line 27, in <module>
execute_from_command_line(sys.argv)
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/cache/.bk/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/cache/.bk/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/cache/.bk/env/lib/python2.7/site-packages/django/apps/config.py", line 112, in create
mod = import_module(mod_path)
File "/cache/.bk/env/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/app/code/pipeline/apps.py", line 18, in <module>
from rediscluster import StrictRedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/__init__.py", line 7, in <module>
from .client import StrictRedisCluster, RedisCluster
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/client.py", line 10, in <module>
from .connection import (
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/connection.py", line 11, in <module>
from .nodemanager import NodeManager
File "/cache/.bk/env/lib/python2.7/site-packages/rediscluster/nodemanager.py", line 12, in <module>
from redis._compat import b, unicode, bytes, long, basestring
ImportError: cannot import name b
------FAILURE: Migrate Database------

# Fixed code
def get_bk_user(request):
    bkuser = None
    if request.weixin_user and not isinstance(request.weixin_user, AnonymousUser):
        user_model = get_user_model()
        try:
            user_property = UserProperty.objects.get(
                key="wx_userid", value=request.weixin_user.userid
            )
        except UserProperty.DoesNotExist:
            logger.warning(
                "user[wx_userid=%s] not in UserProperty" % request.weixin_user.userid
            )
        else:
            bkuser = user_model.objects.get(username=user_property.user.username)
    return bkuser or AnonymousUser()
# Buggy code
def __init__(self, *args, **kwargs):
    super().__init__(*args)
    self._meta = {}
    self.names = kwargs.pop("names", None)
    self.csv_kwargs = kwargs
    # CSV reader needs a list of files
    # (Assume flat directory structure if this is a dir)
    if len(self.paths) == 1 and self.fs.isdir(self.paths[0]):
        self.paths = self.fs.glob(self.fs.sep.join([self.paths[0], "*"]))


# Traceback (AttributeError)
AttributeErrorTraceback (most recent call last)
<ipython-input-1-84910288ec3f> in <module>
44         del gdf
45 path_out = '/raid/criteo/tests/jp_csv_orig/'
---> 46 file_to_pq(train_set, 'csv', output_folder=path_out, cols=cols, dtypes=dtypes)

<ipython-input-1-84910288ec3f> in file_to_pq(target_files, file_type, output_folder, cols, dtypes)
34     old_file_path = None
35     writer = None
---> 36     for gdf in tar:
37 #         gdf.to_parquet(output_folder)
38         file_path = os.path.join(output_folder, os.path.split(tar.itr.file_path)[1].split('.')[0])

/nvtabular/nvtabular/io.py in __iter__(self)
329     def __iter__(self):
330         for path in self.paths:
--> 331             yield from GPUFileIterator(path, **self.kwargs)
332
333

/nvtabular/nvtabular/io.py in __iter__(self)
271         for chunk in self.engine:
272             if self.dtypes:
--> 273                 self._set_dtypes(chunk)
274             yield chunk
275             chunk = None

AttributeError: 'GPUFileIterator' object has no attribute '_set_dtypes'

# Fixed code
def __init__(self, *args, **kwargs):
    super().__init__(*args)
    self._meta = {}
    self.csv_kwargs = kwargs
    self.names = self.csv_kwargs.get("names", None)
    # CSV reader needs a list of files
    # (Assume flat directory structure if this is a dir)
    if len(self.paths) == 1 and self.fs.isdir(self.paths[0]):
        self.paths = self.fs.glob(self.fs.sep.join([self.paths[0], "*"]))
# Buggy code
def to_ddf(self, columns=None):
    return dask_cudf.read_csv(
        self.paths, names=self.names, chunksize=self.part_size, **self.csv_kwargs
    )[columns]


# Traceback (AttributeError)
AttributeErrorTraceback (most recent call last)
<ipython-input-1-84910288ec3f> in <module>
44         del gdf
45 path_out = '/raid/criteo/tests/jp_csv_orig/'
---> 46 file_to_pq(train_set, 'csv', output_folder=path_out, cols=cols, dtypes=dtypes)

<ipython-input-1-84910288ec3f> in file_to_pq(target_files, file_type, output_folder, cols, dtypes)
34     old_file_path = None
35     writer = None
---> 36     for gdf in tar:
37 #         gdf.to_parquet(output_folder)
38         file_path = os.path.join(output_folder, os.path.split(tar.itr.file_path)[1].split('.')[0])

/nvtabular/nvtabular/io.py in __iter__(self)
329     def __iter__(self):
330         for path in self.paths:
--> 331             yield from GPUFileIterator(path, **self.kwargs)
332
333

/nvtabular/nvtabular/io.py in __iter__(self)
271         for chunk in self.engine:
272             if self.dtypes:
--> 273                 self._set_dtypes(chunk)
274             yield chunk
275             chunk = None

AttributeError: 'GPUFileIterator' object has no attribute '_set_dtypes'

# Fixed code
def to_ddf(self, columns=None):
    return dask_cudf.read_csv(self.paths, chunksize=self.part_size, **self.csv_kwargs)[
        columns
    ]
# Buggy code
def _predict(self, X):
    """Collect results from clf.predict calls."""
    return np.asarray([clf.predict(X) for clf in self.clfs_]).T


# Traceback (TypeError)
Traceback (most recent call last):
File "/_mlxtend_bug/reproduce.py", line 16, in <module>
print(clf.predict(test))
File "/venv/py3/lib/python3.4/site-packages/mlxtend/classifier/ensemble_vote.py", line 197, in predict
arr=predictions)
File "/venv/py3/lib/python3.4/site-packages/numpy/lib/shape_base.py", line 132, in apply_along_axis
res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))
File "/venv/py3/lib/python3.4/site-packages/mlxtend/classifier/ensemble_vote.py", line 195, in <lambda>
weights=self.weights)),
TypeError: Cannot cast array data from dtype('<U1') to dtype('int64') according to the rule 'safe'

# Fixed code
def _predict(self, X):
    """Collect results from clf.predict calls."""

    if self.refit:
        return np.asarray([clf.predict(X) for clf in self.clfs_]).T
    else:
        return np.asarray([self.le_.transform(clf.predict(X)) for clf in self.clfs_]).T