gurudesh/pytracebugs huggingface dataset:
# Buggy code
def update(self):
    super().update()
    if self.lifetime_elapsed <= self.in_duration:
        u = self.lifetime_elapsed / self.in_duration
        self.alpha = arcade.lerp(self.start_alpha, self.mid_alpha, u)
    else:
        u = (self.lifetime_elapsed - self.in_duration) / self.out_duration
        self.alpha = arcade.lerp(self.mid_alpha, self.end_alpha, u)


# Traceback (TypeError)
$ python -m arcade.examples.particle_fireworks
Traceback (most recent call last):
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 357, in <module>
arcade.run()
File "C:\cache\repo\arcade\arcade\window_commands.py", line 246, in run
pyglet.app.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\__init__.py", line 144, in run
event_loop.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 175, in run
self._run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 187, in _run
timeout = self.idle()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 314, in idle
window.dispatch_event('on_draw')
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\window\__init__.py", line 1330, in dispatch_event
if EventDispatcher.dispatch_event(self, *args) != False:
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 428, in dispatch_event
self._raise_dispatch_exception(event_type, args, getattr(self, event_type), exception)
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 482, in _raise_dispatch_exception
raise exception
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 423, in dispatch_event
if getattr(self, event_type)(*args):
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 332, in on_draw
e.draw()
File "C:\cache\repo\arcade\arcade\emitter.py", line 167, in draw
self._particles.draw()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 803, in draw
self._calculate_sprite_buffer()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 619, in _calculate_sprite_buffer
calculate_colors()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 490, in calculate_colors
self._sprite_color_data.append(sprite.alpha)
TypeError: integer argument expected, got float
Error in sys.excepthook:

Original exception was:

# Fixed code
def update(self):
    super().update()
    if self.lifetime_elapsed <= self.in_duration:
        u = self.lifetime_elapsed // self.in_duration
        self.alpha = arcade.lerp(self.start_alpha, self.mid_alpha, u)
    else:
        u = (self.lifetime_elapsed - self.in_duration) // self.out_duration
        self.alpha = arcade.lerp(self.mid_alpha, self.end_alpha, u)
# Buggy code
def update(self):
    """Advance the Particle's simulation"""
    super().update()
    self.alpha = arcade.utils.lerp(
        self.start_alpha, self.end_alpha, self.lifetime_elapsed / self.lifetime_original
    )


# Traceback (TypeError)
$ python -m arcade.examples.particle_fireworks
Traceback (most recent call last):
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 357, in <module>
arcade.run()
File "C:\cache\repo\arcade\arcade\window_commands.py", line 246, in run
pyglet.app.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\__init__.py", line 144, in run
event_loop.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 175, in run
self._run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 187, in _run
timeout = self.idle()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 314, in idle
window.dispatch_event('on_draw')
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\window\__init__.py", line 1330, in dispatch_event
if EventDispatcher.dispatch_event(self, *args) != False:
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 428, in dispatch_event
self._raise_dispatch_exception(event_type, args, getattr(self, event_type), exception)
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 482, in _raise_dispatch_exception
raise exception
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 423, in dispatch_event
if getattr(self, event_type)(*args):
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 332, in on_draw
e.draw()
File "C:\cache\repo\arcade\arcade\emitter.py", line 167, in draw
self._particles.draw()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 803, in draw
self._calculate_sprite_buffer()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 619, in _calculate_sprite_buffer
calculate_colors()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 490, in calculate_colors
self._sprite_color_data.append(sprite.alpha)
TypeError: integer argument expected, got float
Error in sys.excepthook:

Original exception was:

# Fixed code
def update(self):
    """Advance the Particle's simulation"""
    super().update()
    self.alpha = arcade.utils.lerp(
        self.start_alpha,
        self.end_alpha,
        self.lifetime_elapsed // self.lifetime_original,
    )
# Buggy code
def update(self):
    super().update()
    if self.lifetime_elapsed <= self.in_duration:
        u = self.lifetime_elapsed // self.in_duration
        self.alpha = arcade.lerp(self.start_alpha, self.mid_alpha, u)
    else:
        u = (self.lifetime_elapsed - self.in_duration) // self.out_duration
        self.alpha = arcade.lerp(self.mid_alpha, self.end_alpha, u)


# Traceback (TypeError)
$ python -m arcade.examples.particle_fireworks
Traceback (most recent call last):
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 357, in <module>
arcade.run()
File "C:\cache\repo\arcade\arcade\window_commands.py", line 246, in run
pyglet.app.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\__init__.py", line 144, in run
event_loop.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 175, in run
self._run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 187, in _run
timeout = self.idle()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 314, in idle
window.dispatch_event('on_draw')
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\window\__init__.py", line 1330, in dispatch_event
if EventDispatcher.dispatch_event(self, *args) != False:
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 428, in dispatch_event
self._raise_dispatch_exception(event_type, args, getattr(self, event_type), exception)
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 482, in _raise_dispatch_exception
raise exception
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 423, in dispatch_event
if getattr(self, event_type)(*args):
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 332, in on_draw
e.draw()
File "C:\cache\repo\arcade\arcade\emitter.py", line 167, in draw
self._particles.draw()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 803, in draw
self._calculate_sprite_buffer()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 619, in _calculate_sprite_buffer
calculate_colors()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 490, in calculate_colors
self._sprite_color_data.append(sprite.alpha)
TypeError: integer argument expected, got float
Error in sys.excepthook:

Original exception was:

# Fixed code
def update(self):
    super().update()
    if self.lifetime_elapsed <= self.in_duration:
        u = self.lifetime_elapsed / self.in_duration
        self.alpha = clamp(arcade.lerp(self.start_alpha, self.mid_alpha, u), 0, 255)
    else:
        u = (self.lifetime_elapsed - self.in_duration) / self.out_duration
        self.alpha = clamp(arcade.lerp(self.mid_alpha, self.end_alpha, u), 0, 255)
# Buggy code
def update(self):
    """Advance the Particle's simulation"""
    super().update()
    self.alpha = arcade.utils.lerp(
        self.start_alpha,
        self.end_alpha,
        self.lifetime_elapsed // self.lifetime_original,
    )


# Traceback (TypeError)
$ python -m arcade.examples.particle_fireworks
Traceback (most recent call last):
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\scott\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 357, in <module>
arcade.run()
File "C:\cache\repo\arcade\arcade\window_commands.py", line 246, in run
pyglet.app.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\__init__.py", line 144, in run
event_loop.run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 175, in run
self._run()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 187, in _run
timeout = self.idle()
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\app\base.py", line 314, in idle
window.dispatch_event('on_draw')
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\window\__init__.py", line 1330, in dispatch_event
if EventDispatcher.dispatch_event(self, *args) != False:
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 428, in dispatch_event
self._raise_dispatch_exception(event_type, args, getattr(self, event_type), exception)
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 482, in _raise_dispatch_exception
raise exception
File "C:\cache\venv\arcadedev\lib\site-packages\pyglet\event.py", line 423, in dispatch_event
if getattr(self, event_type)(*args):
File "C:\cache\repo\arcade\arcade\examples\particle_fireworks.py", line 332, in on_draw
e.draw()
File "C:\cache\repo\arcade\arcade\emitter.py", line 167, in draw
self._particles.draw()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 803, in draw
self._calculate_sprite_buffer()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 619, in _calculate_sprite_buffer
calculate_colors()
File "C:\cache\repo\arcade\arcade\sprite_list.py", line 490, in calculate_colors
self._sprite_color_data.append(sprite.alpha)
TypeError: integer argument expected, got float
Error in sys.excepthook:

Original exception was:

# Fixed code
def update(self):
    """Advance the Particle's simulation"""
    super().update()
    a = arcade.utils.lerp(
        self.start_alpha, self.end_alpha, self.lifetime_elapsed / self.lifetime_original
    )
    self.alpha = clamp(a, 0, 255)
# Buggy code
def generate_sprites(map_object, layer_name, scaling, base_directory=""):
    sprite_list = SpriteList()

    if layer_name not in map_object.layers_int_data:
        print(f"Warning, no layer named '{layer_name}'.")
        return sprite_list

    map_array = map_object.layers_int_data[layer_name]

    # Loop through the layer and add in the wall list
    for row_index, row in enumerate(map_array):
        for column_index, item in enumerate(row):
            if str(item) in map_object.global_tile_set:
                tile_info = map_object.global_tile_set[str(item)]
                filename = base_directory + tile_info.source

                my_sprite = Sprite(filename, scaling)
                my_sprite.right = column_index * (map_object.tilewidth * scaling)
                my_sprite.top = (map_object.height - row_index) * (
                    map_object.tileheight * scaling
                )

                if tile_info.points is not None:
                    my_sprite.set_points(tile_info.points)
                sprite_list.append(my_sprite)
            elif item != 0:
                print(f"Warning, could not find {item} image to load.")

    return sprite_list


# Traceback (FileNotFoundError)
Traceback (most recent call last):
File "tsx_bug.py", line 5, in <module>
my_map = arcade.read_tiled_map(MAP_NAME, 1)
File "/$DIR/lib/python3.6/site-packages/arcade/read_tiled_map.py", line 160, in read_tiled_map
tileset_tree = etree.parse(source)
File "/usr/lib/python3.6/xml/etree/ElementTree.py", line 1196, in parse
tree.parse(source, parser)
File "/usr/lib/python3.6/xml/etree/ElementTree.py", line 586, in parse
source = open(source, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'tsx_test.tsx'

# Fixed code
def generate_sprites(map_object, layer_name, scaling, base_directory=""):
    sprite_list = SpriteList()

    if layer_name not in map_object.layers_int_data:
        print(f"Warning, no layer named '{layer_name}'.")
        return sprite_list

    map_array = map_object.layers_int_data[layer_name]

    # Loop through the layer and add in the wall list
    for row_index, row in enumerate(map_array):
        for column_index, item in enumerate(row):
            if str(item) in map_object.global_tile_set:
                tile_info = map_object.global_tile_set[str(item)]
                tmx_file = base_directory + tile_info.source

                my_sprite = Sprite(tmx_file, scaling)
                my_sprite.right = column_index * (map_object.tilewidth * scaling)
                my_sprite.top = (map_object.height - row_index) * (
                    map_object.tileheight * scaling
                )

                if tile_info.points is not None:
                    my_sprite.set_points(tile_info.points)
                sprite_list.append(my_sprite)
            elif item != 0:
                print(f"Warning, could not find {item} image to load.")

    return sprite_list
# Buggy code
def __init__(self, width, height):
    super().__init__(width, height)
    arcade.set_background_color(arcade.color.AMAZON)

    self.pause = False
    self.coin_list = None
    self.button_list = None


# Traceback (FileNotFoundError)
$ python3 -m arcade.examples.gui_text_button
Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/USERNAME/.local/lib/python3.6/site-packages/arcade/examples/gui_text_button.py", line 228, in <module>
main()
File "/home/USERNAME/.local/lib/python3.6/site-packages/arcade/examples/gui_text_button.py", line 223, in main
game.setup()
File "/home/USERNAME/.local/lib/python3.6/site-packages/arcade/examples/gui_text_button.py", line 155, in setup
coin = arcade.Sprite("images/coin_01.png", 0.25)
File "/home/USERNAME/.local/lib/python3.6/site-packages/arcade/sprite.py", line 142, in __init__
image_width, image_height)
File "/home/USERNAME/.local/lib/python3.6/site-packages/arcade/draw_commands.py", line 286, in load_texture
source_image = PIL.Image.open(file_name)
File "/home/USERNAME/.local/lib/python3.6/site-packages/PIL/Image.py", line 2609, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'images/coin_01.png'

# Fixed code
def __init__(self, width, height):
    super().__init__(width, height)

    # Set the working directory (where we expect to find files) to the same
    # directory this .py file is in. You can leave this out of your own
    # code, but it is needed to easily run the examples using "python -m"
    # as mentioned at the top of this program.
    file_path = os.path.dirname(os.path.abspath(__file__))
    os.chdir(file_path)

    arcade.set_background_color(arcade.color.AMAZON)

    self.pause = False
    self.coin_list = None
    self.button_list = None
# Buggy code
def update(self):
    """
    Update the sprite.
    """
    self.position = (
        self._position[0] + self.change_x,
        self._position[1] + self.change_y,
    )
    self.angle += self.change_angle


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/examples/asteroid_smasher.py", line 394, in <module>
main()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/examples/asteroid_smasher.py", line 390, in main
arcade.run()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/window_commands.py", line 245, in run
pyglet.app.run()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/pyglet/app/__init__.py", line 142, in run
event_loop.run()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/pyglet/app/base.py", line 175, in run
self._run()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/pyglet/app/base.py", line 187, in _run
timeout = self.idle()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/pyglet/app/base.py", line 308, in idle
redraw_all = self.clock.call_scheduled_functions(dt)
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/pyglet/clock.py", line 314, in call_scheduled_functions
item.func(now - item.last_ts, *item.args, **item.kwargs)
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/examples/asteroid_smasher.py", line 355, in update
self.all_sprites_list.update()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/sprite_list.py", line 299, in update
sprite.update()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/examples/asteroid_smasher.py", line 103, in update
super().update()
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/sprite.py", line 547, in update
self.set_position(self.center_x + self.change_x, self.center_y + self.change_y)
File "/home/srw/projects/pyarcade_lab/venv/lib/python3.7/site-packages/arcade/sprite.py", line 202, in set_position
self._set_position(self, (center_x, center_y))
TypeError: _set_position() takes 2 positional arguments but 3 were given

# Fixed code
def update(self):
    """
    Update the sprite.
    """
    self.position = [
        self._position[0] + self.change_x,
        self._position[1] + self.change_y,
    ]
    self.angle += self.change_angle
# Buggy code
def set_position(self, new_position: (float, float)):
    self.clear_spatial_hashes()
    self._position[0] = new_position[0]
    self._position[1] = new_position[1]
    self._point_list_cache = None


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: set_position() takes 2 positional arguments but 3 were given

# Fixed code
def set_position(self, center_x: float, center_y: float):
    """
    Set a sprite's position

    >>> import arcade
    >>> empty_sprite = arcade.Sprite()
    >>> empty_sprite.set_position(10, 10)
    """
    self.center_x = center_x
    self.center_y = center_y
# Buggy code
def calc_stats_dt(srs: dd.Series) -> Dict[str, str]:
    """
    Calculate stats from a datetime column

    Parameters
    ----------
    srs
        a datetime column
    Returns
    -------
    Dict[str, str]
        Dictionary that contains Overview
    """
    size = len(srs)  # include nan
    count = srs.count()  # exclude nan
    uniq_count = srs.nunique()
    overview_dict = {
        "Distinct Count": uniq_count,
        "Unique (%)": uniq_count / count,
        "Missing": size - count,
        "Missing (%)": 1 - (count / size),
        "Memory Size": srs.memory_usage(),
        "Minimum": srs.min(),
        "Maximum": srs.max(),
    }

    return overview_dict


# Traceback (UnboundLocalError)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-10-c4d17e3c9e92> in <module>
----> 1 report = eda.create_report(dist_df, title="Distribution Report")

/usr/local/lib/python3.8/site-packages/dataprep/eda/create_report/__init__.py in create_report(df, title, mode, progress)
52         "resources": INLINE.render(),
53         "title": title,
---> 54         "components": format_report(df, mode, progress),
55     }
56     template_base = ENV_LOADER.get_template("base.html")

/usr/local/lib/python3.8/site-packages/dataprep/eda/create_report/formatter.py in format_report(df, mode, progress)
61         df = string_dtype_to_object(df)
62         if mode == "basic":
---> 63             comps = format_basic(df)
64         # elif mode == "full":
65         #     comps = format_full(df)

/usr/local/lib/python3.8/site-packages/dataprep/eda/create_report/formatter.py in format_basic(df)
121             )
122         figs: List[Figure] = []
--> 123         for tab in rndrd:
124             try:
125                 fig = tab.children[0]

UnboundLocalError: local variable 'rndrd' referenced before assignment

# Fixed code
def calc_stats_dt(srs: dd.Series) -> Dict[str, str]:
    """
    Calculate stats from a datetime column

    Parameters
    ----------
    srs
        a datetime column
    Returns
    -------
    Dict[str, str]
        Dictionary that contains Overview
    """
    size = srs.shape[0]  # include nan
    count = srs.count()  # exclude nan
    uniq_count = srs.nunique()
    overview_dict = {
        "Distinct Count": uniq_count,
        "Unique (%)": uniq_count / count,
        "Missing": size - count,
        "Missing (%)": 1 - (count / size),
        "Memory Size": srs.memory_usage(deep=True),
        "Minimum": srs.min(),
        "Maximum": srs.max(),
    }

    return overview_dict
# Buggy code
def __del__(self):
    assert _debug("Delete DirectSoundAudioPlayer")
    # We decrease the IDirectSound refcount
    self.driver._ds_driver._native_dsound.Release()


# Traceback (OSError)
Exception ignored in: <function DirectSoundBuffer.__del__ at 0x038B6070>
Traceback (most recent call last):
File "xxx\pyglet\media\drivers\directsound\interface.py", line 174, in __del__
self.delete()
File "xxx\pyglet\media\drivers\directsound\interface.py", line 180, in delete
self._native_buffer.Stop()
File "xxx\pyglet\com.py", line 131, in _call
ret = self.method.get_field()(self.i, self.name)(obj, *args)
OSError: exception: access violation writing 0x00000000

# Fixed code
def __del__(self):
    # We decrease the IDirectSound refcount
    self.driver._ds_driver._native_dsound.Release()
# Buggy code
def delete(self):
    assert _debug("Delete DirectSoundDriver")
    # Make sure the _ds_listener is deleted before the _ds_driver
    self._ds_listener = None


# Traceback (OSError)
Exception ignored in: <function DirectSoundBuffer.__del__ at 0x038B6070>
Traceback (most recent call last):
File "xxx\pyglet\media\drivers\directsound\interface.py", line 174, in __del__
self.delete()
File "xxx\pyglet\media\drivers\directsound\interface.py", line 180, in delete
self._native_buffer.Stop()
File "xxx\pyglet\com.py", line 131, in _call
ret = self.method.get_field()(self.i, self.name)(obj, *args)
OSError: exception: access violation writing 0x00000000

# Fixed code
def delete(self):
    # Make sure the _ds_listener is deleted before the _ds_driver
    self._ds_listener = None
# Buggy code
def __del__(self):
    assert _debug("Delete DirectSoundListener")


# Traceback (OSError)
Exception ignored in: <function DirectSoundBuffer.__del__ at 0x038B6070>
Traceback (most recent call last):
File "xxx\pyglet\media\drivers\directsound\interface.py", line 174, in __del__
self.delete()
File "xxx\pyglet\media\drivers\directsound\interface.py", line 180, in delete
self._native_buffer.Stop()
File "xxx\pyglet\com.py", line 131, in _call
ret = self.method.get_field()(self.i, self.name)(obj, *args)
OSError: exception: access violation writing 0x00000000

# Fixed code
def __del__(self):
    self.delete()
# Buggy code
def __del__(self):
    assert _debug("Delete interface.DirectSoundDriver")
    self.primary_buffer = None
    self._native_dsound.Release()


# Traceback (OSError)
Exception ignored in: <function DirectSoundBuffer.__del__ at 0x038B6070>
Traceback (most recent call last):
File "xxx\pyglet\media\drivers\directsound\interface.py", line 174, in __del__
self.delete()
File "xxx\pyglet\media\drivers\directsound\interface.py", line 180, in delete
self._native_buffer.Stop()
File "xxx\pyglet\com.py", line 131, in _call
ret = self.method.get_field()(self.i, self.name)(obj, *args)
OSError: exception: access violation writing 0x00000000

# Fixed code
def __del__(self):
    self.primary_buffer = None
    self._native_dsound.Release()
# Buggy code
def delete(self):
    assert _debug(
        "Delete interface.DirectSoundBuffer from AudioFormat {}".format(
            self.audio_format
        )
    )
    if self._native_buffer is not None:
        self._native_buffer.Stop()
        self._native_buffer.Release()
        self._native_buffer = None
        if self._native_buffer3d is not None:
            self._native_buffer3d.Release()
            self._native_buffer3d = None


# Traceback (OSError)
Exception ignored in: <function DirectSoundBuffer.__del__ at 0x038B6070>
Traceback (most recent call last):
File "xxx\pyglet\media\drivers\directsound\interface.py", line 174, in __del__
self.delete()
File "xxx\pyglet\media\drivers\directsound\interface.py", line 180, in delete
self._native_buffer.Stop()
File "xxx\pyglet\com.py", line 131, in _call
ret = self.method.get_field()(self.i, self.name)(obj, *args)
OSError: exception: access violation writing 0x00000000

# Fixed code
def delete(self):
    if self._native_buffer is not None:
        self._native_buffer.Stop()
        self._native_buffer.Release()
        self._native_buffer = None
        if self._native_buffer3d is not None:
            self._native_buffer3d.Release()
            self._native_buffer3d = None
# Buggy code
def delete(self):
    assert _debug("Delete interface.DirectSoundListener")
    if self._native_listener:
        self._native_listener.Release()
        self._native_listener = None


# Traceback (OSError)
Exception ignored in: <function DirectSoundBuffer.__del__ at 0x038B6070>
Traceback (most recent call last):
File "xxx\pyglet\media\drivers\directsound\interface.py", line 174, in __del__
self.delete()
File "xxx\pyglet\media\drivers\directsound\interface.py", line 180, in delete
self._native_buffer.Stop()
File "xxx\pyglet\com.py", line 131, in _call
ret = self.method.get_field()(self.i, self.name)(obj, *args)
OSError: exception: access violation writing 0x00000000

# Fixed code
def delete(self):
    if self._native_listener:
        self._native_listener.Release()
        self._native_listener = None
# Buggy code
def __del__(self):
    self.delete()


# Traceback (OSError)
Exception ignored in: <function DirectSoundBuffer.__del__ at 0x038B6070>
Traceback (most recent call last):
File "xxx\pyglet\media\drivers\directsound\interface.py", line 174, in __del__
self.delete()
File "xxx\pyglet\media\drivers\directsound\interface.py", line 180, in delete
self._native_buffer.Stop()
File "xxx\pyglet\com.py", line 131, in _call
ret = self.method.get_field()(self.i, self.name)(obj, *args)
OSError: exception: access violation writing 0x00000000

# Fixed code
def __del__(self):
    try:
        self.delete()
    except OSError:
        pass
# Buggy code
def send_super(receiver, selName, *args, **kwargs):
    if hasattr(receiver, "_as_parameter_"):
        receiver = receiver._as_parameter_
    superclass = get_superclass_of_object(receiver)
    superclass_ptr = c_void_p(objc.class_getSuperclass(superclass))
    if superclass_ptr.value is not None:
        superclass = superclass_ptr
    super_struct = OBJC_SUPER(receiver, superclass)
    selector = get_selector(selName)
    restype = kwargs.get("restype", c_void_p)
    argtypes = kwargs.get("argtypes", None)
    objc.objc_msgSendSuper.restype = restype
    if argtypes:
        objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes
    else:
        objc.objc_msgSendSuper.argtypes = None
    result = objc.objc_msgSendSuper(byref(super_struct), selector, *args)
    if restype == c_void_p:
        result = c_void_p(result)
    return result


# Traceback (RecursionError)
$ python3 example.py
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1120, in objc_method
args = convert_method_arguments(encoding, args)
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1000, in convert_method_arguments
new_args.append(ObjCInstance(a))
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 921, in __new__
if not isinstance(object_ptr, c_void_p):
RecursionError: maximum recursion depth exceeded while calling a Python object
Segmentation fault: 11
$

# Fixed code
def send_super(receiver, selName, *args, superclass_name=None, **kwargs):
    if hasattr(receiver, "_as_parameter_"):
        receiver = receiver._as_parameter_
    if superclass_name is None:
        superclass = get_superclass_of_object(receiver)
    else:
        superclass = get_class(superclass_name)
    super_struct = OBJC_SUPER(receiver, superclass)
    selector = get_selector(selName)
    restype = kwargs.get("restype", c_void_p)
    argtypes = kwargs.get("argtypes", None)
    objc.objc_msgSendSuper.restype = restype
    if argtypes:
        objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes
    else:
        objc.objc_msgSendSuper.argtypes = None
    result = objc.objc_msgSendSuper(byref(super_struct), selector, *args)
    if restype == c_void_p:
        result = c_void_p(result)
    return result
# Buggy code
def getMouseDelta(nsevent):
    dx = nsevent.deltaX()
    dy = -nsevent.deltaY()
    return int(round(dx)), int(round(dy))


# Traceback (RecursionError)
$ python3 example.py
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1120, in objc_method
args = convert_method_arguments(encoding, args)
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1000, in convert_method_arguments
new_args.append(ObjCInstance(a))
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 921, in __new__
if not isinstance(object_ptr, c_void_p):
RecursionError: maximum recursion depth exceeded while calling a Python object
Segmentation fault: 11
$

# Fixed code
def getMouseDelta(nsevent):
    dx = nsevent.deltaX()
    dy = -nsevent.deltaY()
    return dx, dy
# Buggy code
def setFrameSize_(self, size):
    cocoapy.send_super(self, "setFrameSize:", size, argtypes=[cocoapy.NSSize])

    # This method is called when view is first installed as the
    # contentView of window.  Don't do anything on first call.
    # This also helps ensure correct window creation event ordering.
    if not self._window.context.canvas:
        return

    width, height = int(size.width), int(size.height)
    self._window.switch_to()
    self._window.context.update_geometry()
    self._window.dispatch_event("on_resize", width, height)
    self._window.dispatch_event("on_expose")
    # Can't get app.event_loop.enter_blocking() working with Cocoa, because
    # when mouse clicks on the window's resize control, Cocoa enters into a
    # mini-event loop that only responds to mouseDragged and mouseUp events.
    # This means that using NSTimer to call idle() won't work.  Our kludge
    # is to override NSWindow's nextEventMatchingMask_etc method and call
    # idle() from there.
    if self.inLiveResize():
        from pyglet import app

        if app.event_loop is not None:
            app.event_loop.idle()


# Traceback (RecursionError)
$ python3 example.py
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1120, in objc_method
args = convert_method_arguments(encoding, args)
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1000, in convert_method_arguments
new_args.append(ObjCInstance(a))
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 921, in __new__
if not isinstance(object_ptr, c_void_p):
RecursionError: maximum recursion depth exceeded while calling a Python object
Segmentation fault: 11
$

# Fixed code
def setFrameSize_(self, size):
    cocoapy.send_super(
        self, "setFrameSize:", size, superclass_name="NSView", argtypes=[cocoapy.NSSize]
    )

    # This method is called when view is first installed as the
    # contentView of window.  Don't do anything on first call.
    # This also helps ensure correct window creation event ordering.
    if not self._window.context.canvas:
        return

    width, height = int(size.width), int(size.height)
    self._window.switch_to()
    self._window.context.update_geometry()
    self._window.dispatch_event("on_resize", width, height)
    self._window.dispatch_event("on_expose")
    # Can't get app.event_loop.enter_blocking() working with Cocoa, because
    # when mouse clicks on the window's resize control, Cocoa enters into a
    # mini-event loop that only responds to mouseDragged and mouseUp events.
    # This means that using NSTimer to call idle() won't work.  Our kludge
    # is to override NSWindow's nextEventMatchingMask_etc method and call
    # idle() from there.
    if self.inLiveResize():
        from pyglet import app

        if app.event_loop is not None:
            app.event_loop.idle()
# Buggy code
def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue):
    if self.inLiveResize():
        # Call the idle() method while we're stuck in a live resize event.
        from pyglet import app

        if app.event_loop is not None:
            app.event_loop.idle()

    event = send_super(
        self,
        "nextEventMatchingMask:untilDate:inMode:dequeue:",
        mask,
        date,
        mode,
        dequeue,
        argtypes=[NSUInteger, c_void_p, c_void_p, c_bool],
    )

    if event.value is None:
        return 0
    else:
        return event.value


# Traceback (RecursionError)
$ python3 example.py
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1120, in objc_method
args = convert_method_arguments(encoding, args)
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1000, in convert_method_arguments
new_args.append(ObjCInstance(a))
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 921, in __new__
if not isinstance(object_ptr, c_void_p):
RecursionError: maximum recursion depth exceeded while calling a Python object
Segmentation fault: 11
$

# Fixed code
def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue):
    if self.inLiveResize():
        # Call the idle() method while we're stuck in a live resize event.
        from pyglet import app

        if app.event_loop is not None:
            app.event_loop.idle()

    event = send_super(
        self,
        "nextEventMatchingMask:untilDate:inMode:dequeue:",
        mask,
        date,
        mode,
        dequeue,
        superclass_name="NSWindow",
        argtypes=[NSUInteger, c_void_p, c_void_p, c_bool],
    )

    if event.value is None:
        return 0
    else:
        return event.value
# Buggy code
def send_super(receiver, selName, *args, preventSuperclassRecursion=False, **kwargs):
    if hasattr(receiver, "_as_parameter_"):
        receiver = receiver._as_parameter_
    superclass = get_superclass_of_object(receiver)
    if preventSuperclassRecursion:
        supersuperclass = c_void_p(objc.class_getSuperclass(superclass))
        if supersuperclass.value is not None:
            superclass = supersuperclass
    super_struct = OBJC_SUPER(receiver, superclass)
    selector = get_selector(selName)
    restype = kwargs.get("restype", c_void_p)
    argtypes = kwargs.get("argtypes", None)
    objc.objc_msgSendSuper.restype = restype
    if argtypes:
        objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes
    else:
        objc.objc_msgSendSuper.argtypes = None
    result = objc.objc_msgSendSuper(byref(super_struct), selector, *args)
    if restype == c_void_p:
        result = c_void_p(result)
    return result


# Traceback (RecursionError)
$ python3 example.py
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1120, in objc_method
args = convert_method_arguments(encoding, args)
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1000, in convert_method_arguments
new_args.append(ObjCInstance(a))
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 921, in __new__
if not isinstance(object_ptr, c_void_p):
RecursionError: maximum recursion depth exceeded while calling a Python object
Segmentation fault: 11
$

# Fixed code
def send_super(receiver, selName, *args, superclass_name=None, **kwargs):
    if hasattr(receiver, "_as_parameter_"):
        receiver = receiver._as_parameter_
    if superclass_name is None:
        superclass = get_superclass_of_object(receiver)
    else:
        superclass = get_class(superclass_name)
    super_struct = OBJC_SUPER(receiver, superclass)
    selector = get_selector(selName)
    restype = kwargs.get("restype", c_void_p)
    argtypes = kwargs.get("argtypes", None)
    objc.objc_msgSendSuper.restype = restype
    if argtypes:
        objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes
    else:
        objc.objc_msgSendSuper.argtypes = None
    result = objc.objc_msgSendSuper(byref(super_struct), selector, *args)
    if restype == c_void_p:
        result = c_void_p(result)
    return result
# Buggy code
def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue):
    if self.inLiveResize():
        # Call the idle() method while we're stuck in a live resize event.
        from pyglet import app

        if app.event_loop is not None:
            app.event_loop.idle()

    event = send_super(
        self,
        "nextEventMatchingMask:untilDate:inMode:dequeue:",
        mask,
        date,
        mode,
        dequeue,
        preventSuperclassRecursion=True,
        argtypes=[NSUInteger, c_void_p, c_void_p, c_bool],
    )

    if event.value is None:
        return 0
    else:
        return event.value


# Traceback (RecursionError)
$ python3 example.py
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1120, in objc_method
args = convert_method_arguments(encoding, args)
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1000, in convert_method_arguments
new_args.append(ObjCInstance(a))
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 921, in __new__
if not isinstance(object_ptr, c_void_p):
RecursionError: maximum recursion depth exceeded while calling a Python object
Segmentation fault: 11
$

# Fixed code
def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue):
    if self.inLiveResize():
        # Call the idle() method while we're stuck in a live resize event.
        from pyglet import app

        if app.event_loop is not None:
            app.event_loop.idle()

    event = send_super(
        self,
        "nextEventMatchingMask:untilDate:inMode:dequeue:",
        mask,
        date,
        mode,
        dequeue,
        superclass_name="NSWindow",
        argtypes=[NSUInteger, c_void_p, c_void_p, c_bool],
    )

    if event.value is None:
        return 0
    else:
        return event.value
# Buggy code
def send_super(receiver, selName, *args, **kwargs):
    # print 'send_super', receiver, selName, args
    if hasattr(receiver, "_as_parameter_"):
        receiver = receiver._as_parameter_
    superclass = get_superclass_of_object(receiver)
    super_struct = OBJC_SUPER(receiver, superclass)
    selector = get_selector(selName)
    restype = kwargs.get("restype", c_void_p)
    argtypes = kwargs.get("argtypes", None)
    objc.objc_msgSendSuper.restype = restype
    if argtypes:
        objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes
    else:
        objc.objc_msgSendSuper.argtypes = None
    result = objc.objc_msgSendSuper(byref(super_struct), selector, *args)
    if restype == c_void_p:
        result = c_void_p(result)
    return result


# Traceback (RecursionError)
$ python3 example.py
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 232, in 'calling callback function'
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1120, in objc_method
args = convert_method_arguments(encoding, args)
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 1000, in convert_method_arguments
new_args.append(ObjCInstance(a))
File "/usr/local/lib/python3.7/site-packages/pyglet/libs/darwin/cocoapy/runtime.py", line 921, in __new__
if not isinstance(object_ptr, c_void_p):
RecursionError: maximum recursion depth exceeded while calling a Python object
Segmentation fault: 11
$

# Fixed code
def send_super(receiver, selName, *args, **kwargs):
    if hasattr(receiver, "_as_parameter_"):
        receiver = receiver._as_parameter_
    superclass = get_superclass_of_object(receiver)
    superclass_ptr = c_void_p(objc.class_getSuperclass(superclass))
    if superclass_ptr.value is not None:
        superclass = superclass_ptr
    super_struct = OBJC_SUPER(receiver, superclass)
    selector = get_selector(selName)
    restype = kwargs.get("restype", c_void_p)
    argtypes = kwargs.get("argtypes", None)
    objc.objc_msgSendSuper.restype = restype
    if argtypes:
        objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes
    else:
        objc.objc_msgSendSuper.argtypes = None
    result = objc.objc_msgSendSuper(byref(super_struct), selector, *args)
    if restype == c_void_p:
        result = c_void_p(result)
    return result
# Buggy code
def __getitem__(self, key):
    try:
        return super(LocalWeakReferencedCache, self).__getitem__(key)
    except TypeError:
        return None  # key is not weak-referenceable, it's not cached


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks
result = g.send(result)
File "/app/python/lib/python3.8/site-packages/scrapy/core/downloader/middleware.py", line 42, in process_request
defer.returnValue((yield download_func(request=request, spider=spider)))
File "/usr/local/lib/python3.8/site-packages/twisted/internet/defer.py", line 1362, in returnValue
raise _DefGen_Return(val)
twisted.internet.defer._DefGen_Return: <200 https://www.example.com>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/app/python/lib/python3.8/site-packages/scrapy/utils/defer.py", line 55, in mustbe_deferred
result = f(*args, **kw)
File "/app/python/lib/python3.8/site-packages/scrapy/core/spidermw.py", line 60, in process_spider_input
return scrape_func(response, request, spider)
File "/app/python/lib/python3.8/site-packages/scrapy/core/scraper.py", line 148, in call_spider
warn_on_generator_with_return_value(spider, callback)
File "/app/python/lib/python3.8/site-packages/scrapy/utils/misc.py", line 202, in warn_on_generator_with_return_value
if is_generator_with_return_value(callable):
File "/app/python/lib/python3.8/site-packages/scrapy/utils/misc.py", line 180, in is_generator_with_return_value
return _generator_callbacks_cache[callable]
File "/app/python/lib/python3.8/site-packages/scrapy/utils/datatypes.py", line 281, in __getitem__
return super(LocalWeakReferencedCache, self).__getitem__(key)
File "/usr/local/lib/python3.8/weakref.py", line 383, in __getitem__
return self.data[ref(key)]
KeyError: <weakref at 0x7f06ff011720; to 'method' at 0x7f07042b5e00 (parse_foo)>

# Fixed code
def __getitem__(self, key):
    try:
        return super(LocalWeakReferencedCache, self).__getitem__(key)
    except (TypeError, KeyError):
        return None  # key is either not weak-referenceable or not cached
# Buggy code
def __init__(self, stats):
    self.stats = stats


# Traceback (TypeError)
2019-09-09 13:51:23 [scrapy.utils.signal] ERROR: Error caught on signal handler: <bound method CoreStats.spider_closed of <scrapy.extensions.corestats.CoreStats object at 0x7f86269cac18>>
Traceback (most recent call last):
File ".../lib/python3.6/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File ".../lib/python3.6/site-packages/pydispatch/robustapply.py", line 55, in robustApply
return receiver(*arguments, **named)
File ".../lib/python3.6/site-packages/scrapy/extensions/corestats.py", line 28, in spider_closed
elapsed_time = finish_time - self.stats.get_value('start_time')
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'

# Fixed code
def __init__(self, stats):
    self.stats = stats
    self.start_time = None
# Buggy code
def spider_opened(self, spider):
    self.stats.set_value("start_time", datetime.datetime.utcnow(), spider=spider)


# Traceback (TypeError)
2019-09-09 13:51:23 [scrapy.utils.signal] ERROR: Error caught on signal handler: <bound method CoreStats.spider_closed of <scrapy.extensions.corestats.CoreStats object at 0x7f86269cac18>>
Traceback (most recent call last):
File ".../lib/python3.6/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File ".../lib/python3.6/site-packages/pydispatch/robustapply.py", line 55, in robustApply
return receiver(*arguments, **named)
File ".../lib/python3.6/site-packages/scrapy/extensions/corestats.py", line 28, in spider_closed
elapsed_time = finish_time - self.stats.get_value('start_time')
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'

# Fixed code
def spider_opened(self, spider):
    self.start_time = datetime.utcnow()
    self.stats.set_value("start_time", self.start_time, spider=spider)
# Buggy code
def spider_closed(self, spider, reason):
    finish_time = datetime.datetime.utcnow()
    elapsed_time = finish_time - self.stats.get_value("start_time")
    elapsed_time_seconds = elapsed_time.total_seconds()
    self.stats.set_value("elapsed_time_seconds", elapsed_time_seconds, spider=spider)
    self.stats.set_value("finish_time", finish_time, spider=spider)
    self.stats.set_value("finish_reason", reason, spider=spider)


# Traceback (TypeError)
2019-09-09 13:51:23 [scrapy.utils.signal] ERROR: Error caught on signal handler: <bound method CoreStats.spider_closed of <scrapy.extensions.corestats.CoreStats object at 0x7f86269cac18>>
Traceback (most recent call last):
File ".../lib/python3.6/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred
result = f(*args, **kw)
File ".../lib/python3.6/site-packages/pydispatch/robustapply.py", line 55, in robustApply
return receiver(*arguments, **named)
File ".../lib/python3.6/site-packages/scrapy/extensions/corestats.py", line 28, in spider_closed
elapsed_time = finish_time - self.stats.get_value('start_time')
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'

# Fixed code
def spider_closed(self, spider, reason):
    finish_time = datetime.utcnow()
    elapsed_time = finish_time - self.start_time
    elapsed_time_seconds = elapsed_time.total_seconds()
    self.stats.set_value("elapsed_time_seconds", elapsed_time_seconds, spider=spider)
    self.stats.set_value("finish_time", finish_time, spider=spider)
    self.stats.set_value("finish_reason", reason, spider=spider)