gurudesh/pytracebugs huggingface dataset:
# Buggy code
def on_double_click(self, event):
    """Handle double click event"""
    idx = self.get_mouse_idx(event)
    if idx == -1:
        return
    item, path_idx = self[idx]
    if item is None:
        return
    treeitem_x = self.get_treeitem_x()
    if path_idx is None:
        if event.GetX() < treeitem_x:
            # Handle second click on tree expand/contract as
            # if the user clicked slowly
            #
            self.selections = set()
            item.opened = not item.opened
            self.schmutzy = True
            self.notify_selection_changed()
            self.Refresh(eraseBackground=False)
        return
    if self.fn_do_menu_command is not None:
        self.fn_do_menu_command([item.get_full_path(path_idx)], None)


# Traceback (IndexError)
Traceback (most recent call last):
File "cellprofiler\gui\pathlist.pyc", line 757, in on_double_click
File "cellprofiler\gui\pathlist.pyc", line 227, in __getitem__
IndexError: index out of bounds

# Fixed code
def on_double_click(self, event):
    """Handle double click event"""
    idx = self.get_mouse_idx(event)
    if idx == -1:
        self.fn_do_menu_command([], None)
        return
    item, path_idx = self[idx]
    if item is None:
        self.fn_do_menu_command([], None)
        return
    treeitem_x = self.get_treeitem_x()
    if path_idx is None:
        if event.GetX() < treeitem_x:
            # Handle second click on tree expand/contract as
            # if the user clicked slowly
            #
            self.selections = set()
            item.opened = not item.opened
            self.schmutzy = True
            self.notify_selection_changed()
            self.Refresh(eraseBackground=False)
        return
    if self.fn_do_menu_command is not None:
        self.fn_do_menu_command([item.get_full_path(path_idx)], None)
# Buggy code
def validate_module(self, pipeline):
    """Produce error if 'All:First' is selected and input image is not provided by the file image provider."""
    if (
        not pipeline.is_image_from_file(self.image_name.value)
        and self.each_or_all == EA_ALL_FIRST
    ):
        raise cps.ValidationError(
            "All: First cycle requires that the input image be provided by LoadImages or LoadData.",
            self.each_or_all,
        )

    """Modify the image provider attributes based on other setttings"""
    d = self.illumination_image_name.provided_attributes
    if self.each_or_all == EA_ALL_ACROSS:
        d[cps.AVAILABLE_ON_LAST_ATTRIBUTE] = True
    elif d.has_key(cps.AVAILABLE_ON_LAST_ATTRIBUTE):
        del d[cps.AVAILABLE_ON_LAST_ATTRIBUTE]


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Applications/CellProfiler2.1.1_rc.app/Contents/Resources/lib/python2.7/cellprofiler/pipeline.py", line 2287, in prepare_group
File "/Applications/CellProfiler2.1.1_rc.app/Contents/Resources/lib/python2.7/cellprofiler/modules/correctilluminationcalculate.py", line 497, in prepare_group
File "/Applications/CellProfiler2.1.1_rc.app/Contents/Resources/lib/python2.7/cellprofiler/pipeline.py", line 2010, in run_group_with_yield
File "/Applications/CellProfiler2.1.1_rc.app/Contents/Resources/lib/python2.7/cellprofiler/modules/namesandtypes.py", line 1291, in run
File "/Applications/CellProfiler2.1.1_rc.app/Contents/Resources/lib/python2.7/cellprofiler/modules/namesandtypes.py", line 1328, in add_image_provider
File "/Applications/CellProfiler2.1.1_rc.app/Contents/Resources/lib/python2.7/cellprofiler/modules/namesandtypes.py", line 1361, in add_simple_image
File "/Applications/CellProfiler2.1.1_rc.app/Contents/Resources/lib/python2.7/cellprofiler/modules/namesandtypes.py", line 1388, in add_provider_measurements
AttributeError: 'MonochromeImageProvider' object has no attribute 'scale'

# Fixed code
def validate_module(self, pipeline):
    """Produce error if 'All:First' is selected and input image is not provided by the file image provider."""
    if (
        not pipeline.is_image_from_file(self.image_name.value)
        and self.each_or_all == EA_ALL_FIRST
    ):
        raise cps.ValidationError(
            "All: First cycle requires that the input image be provided by the Input modules, or LoadImages/LoadData.",
            self.each_or_all,
        )

    """Modify the image provider attributes based on other setttings"""
    d = self.illumination_image_name.provided_attributes
    if self.each_or_all == EA_ALL_ACROSS:
        d[cps.AVAILABLE_ON_LAST_ATTRIBUTE] = True
    elif d.has_key(cps.AVAILABLE_ON_LAST_ATTRIBUTE):
        del d[cps.AVAILABLE_ON_LAST_ATTRIBUTE]
# Buggy code
def hide(self):
    J.execute_runnable_in_main_thread(
        J.run_script(
            """
            new java.lang.Runnable() {
            run: function() { o.hide(); }}""",
            dict(o, self.o),
        ),
        synchronous=True,
    )


# Traceback (AssertionError)
Failed to complete post_run processing for module ExportToDatabase.
Traceback (most recent call last):
File "C:\Trunk\CellProfiler\cellprofiler\pipeline.py", line 2165, in post_run
module.post_run(workspace)
File "C:\Trunk\CellProfiler\cellprofiler\modules\exporttodatabase.py", line 1940, in post_run
self.write_csv_data(workspace)
File "C:\Trunk\CellProfiler\cellprofiler\modules\exporttodatabase.py", line 2708, in write_csv_data
cpmeas.IMAGE, feature, image_number)
File "C:\Trunk\CellProfiler\cellprofiler\measurements.py", line 913, in get_measurement
vals = self.hdf5_dict[object_name, feature_name, image_set_number]
File "C:\Trunk\CellProfiler\cellprofiler\utilities\hdf5_dict.py", line 347, in __getitem__
result = self[object_name, feature_name, [num_idx]]
File "C:\Trunk\CellProfiler\cellprofiler\utilities\hdf5_dict.py", line 351, in __getitem__
assert feature_exists
AssertionError
c:\trunk\cellprofiler\cellprofiler\utilities\hdf5_dict.py(351)__getitem__()
-> assert feature_exists

# Fixed code
def hide(self):
    J.execute_runnable_in_main_thread(
        J.run_script(
            """
            new java.lang.Runnable() {
            run: function() { o.hide(); }}""",
            dict(o=self.o),
        ),
        synchronous=True,
    )
# Buggy code
def is_aggregation_module(self):
    return self.tile_method == T_ACROSS_CYCLES


# Traceback (AttributeError)
Failed during post-group processing for module Tile
Traceback (most recent call last):
File "c:\Trunk\CellProfiler\cellprofiler\pipeline.py", line 2307, in post_grou
p
module.post_group(workspace, grouping)
File "c:\Trunk\CellProfiler\cellprofiler\modules\tile.py", line 271, in post_g
roup
if self.output_image.value not in image_set.get_names():
AttributeError: 'NoneType' object has no attribute 'get_names'
c:\trunk\cellprofiler\cellprofiler\modules\tile.py(271)post_group()
-> if self.output_image.value not in image_set.get_names():
(Pdb)

# Fixed code
def is_aggregation_module(self):
    """Need to run all cycles in same worker if across cycles"""
    return self.tile_method == T_ACROSS_CYCLES
# Buggy code
def post_group(self, workspace, grouping):
    image_set = workspace.image_set
    if self.output_image.value not in image_set.get_names():
        d = self.get_dictionary(workspace.image_set_list)
        image_set.add(self.output_image.value, cpi.Image(d[TILED_IMAGE]))


# Traceback (AttributeError)
Failed during post-group processing for module Tile
Traceback (most recent call last):
File "c:\Trunk\CellProfiler\cellprofiler\pipeline.py", line 2307, in post_grou
p
module.post_group(workspace, grouping)
File "c:\Trunk\CellProfiler\cellprofiler\modules\tile.py", line 271, in post_g
roup
if self.output_image.value not in image_set.get_names():
AttributeError: 'NoneType' object has no attribute 'get_names'
c:\trunk\cellprofiler\cellprofiler\modules\tile.py(271)post_group()
-> if self.output_image.value not in image_set.get_names():
(Pdb)

# Fixed code
def post_group(self, workspace, grouping):
    if self.tile_method == T_ACROSS_CYCLES:
        image_set = workspace.image_set
        if self.output_image.value not in image_set.get_names():
            d = self.get_dictionary(workspace.image_set_list)
            image_set.add(self.output_image.value, cpi.Image(d[TILED_IMAGE]))
# Buggy code
def validate_module(self, pipeline):
    if self.mode == MODE_UNTANGLE:
        path = os.path.join(
            self.training_set_directory.get_absolute_path(),
            self.training_set_file_name.value,
        )
        if not os.path.exists(path):
            raise cps.ValidationError(
                "Can't find file %s" % self.training_set_file_name.value,
                self.training_set_file_name,
            )


# Traceback (ValueError)
Failed to get # of control points from training file. Unknown number of control
point features
Traceback (most recent call last):
File "D:\Trunk\CellProfiler\cellprofiler\modules\untangleworms.py", line 2372, in control_point_features
for n in range(1, self.ncontrol_points()+1)]
File "D:\Trunk\CellProfiler\cellprofiler\modules\untangleworms.py", line 585, in ncontrol_points
params = self.read_params()
File "D:\Trunk\CellProfiler\cellprofiler\modules\untangleworms.py", line 2321, in read_params
self.training_params)
File "D:\Trunk\CellProfiler\cellprofiler\modules\untangleworms.py", line 2517, in read_params
fd_or_file = urllib2.urlopen(url)
File "C:\Python27\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 396, in open
protocol = req.get_type()
File "C:\Python27\lib\urllib2.py", line 258, in get_type
raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: /https://svn.broadinstitute.org/CellProfiler/trunk/ExampleImages/ExampleAllModulesPipeline/TrainingSet.xml

# Fixed code
def validate_module(self, pipeline):
    if self.mode == MODE_UNTANGLE:
        if self.training_set_directory.dir_choice != cpprefs.URL_FOLDER_NAME:
            path = os.path.join(
                self.training_set_directory.get_absolute_path(),
                self.training_set_file_name.value,
            )
            if not os.path.exists(path):
                raise cps.ValidationError(
                    "Can't find file %s" % self.training_set_file_name.value,
                    self.training_set_file_name,
                )
# Buggy code
def fn():
    cellprofiler.utilities.jutil.attach()
    with self.image_dict_lock:
        generation = self.image_dict_generation

    for k, v in well.iteritems():
        sd = {}
        with self.image_dict_lock:
            if self.image_dict_generation > generation:
                return
            self.image_dict[k] = sd
        for c, fd in enumerate(v):
            if PlateData.D_CHANNEL in fd:
                channel = fd[PlateData.D_CHANNEL]
            else:
                channel = str(c + 1)
            img = load_using_bioformats_url(fd[PlateData.D_FILENAME])
            with self.image_dict_lock:
                if self.image_dict_generation > generation:
                    return
                sd[channel] = img
    wx.CallAfter(self.update_figure)
    cellprofiler.utilities.jutil.detach()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Applications/CellProfiler_2.1_r20131015204003.app/Contents/Resources/lib/python2.7/cellprofiler/gui/cpframe.py", line 781, in on_data_tool
File "/Applications/CellProfiler_2.1_r20131015204003.app/Contents/Resources/lib/python2.7/cellprofiler/gui/cpframe.py", line 1327, in __on_data_tool
File "/Applications/CellProfiler_2.1_r20131015204003.app/Contents/Resources/lib/python2.7/cellprofiler/gui/datatoolframe.py", line 79, in __init__
File "/Applications/CellProfiler_2.1_r20131015204003.app/Contents/Resources/lib/python2.7/cellprofiler/gui/moduleview.py", line 392, in set_selection
AttributeError: 'NoneType' object has no attribute 'Show'

# Fixed code
def fn():
    cellprofiler.utilities.jutil.attach()
    with self.image_dict_lock:
        generation = self.image_dict_generation

    for k, v in well.iteritems():
        sd = {}
        with self.image_dict_lock:
            if self.image_dict_generation > generation:
                return
            self.image_dict[k] = sd
        for c, fd in enumerate(v):
            if PlateData.D_CHANNEL in fd:
                channel = fd[PlateData.D_CHANNEL]
            else:
                channel = str(c + 1)
            try:
                img = load_using_bioformats_url(fd[PlateData.D_FILENAME])
                with self.image_dict_lock:
                    if self.image_dict_generation > generation:
                        return
                    sd[channel] = img
            except:
                traceback.print_exc()
                pass
    wx.CallAfter(self.update_figure)
    cellprofiler.utilities.jutil.detach()
# Buggy code
def validate_module(self, pipeline):
    """Keep users from using LoadSingleImage to define image sets"""
    if not any([x.is_load_module() for x in pipeline.modules()]):
        raise cps.ValidationError(
            "LoadSingleImage cannot be used to run a pipeline on one "
            "image file. Please use LoadImages or LoadData instead.",
            self.directory,
        )

    """Make sure metadata tags exist"""
    for group in self.file_settings:
        text_str = group.file_name.value
        undefined_tags = pipeline.get_undefined_metadata_tags(text_str)
        if len(undefined_tags) > 0:
            raise cps.ValidationError(
                "%s is not a defined metadata tag. Check the metadata specifications in your load modules"
                % undefined_tags[0],
                group.file_name,
            )


# Traceback (AttributeError)
Traceback (most recent call last):
File "F:\CellProfiler\cellprofiler\pipeline.py", line 1699, in run_with_yield
module.run(workspace)
File "F:\CellProfiler\cellprofiler\modules\loadsingleimage.py", line 385, in run
image_name, pathname, filename, rescale)
File "F:\CellProfiler\cellprofiler\modules\loadimages.py", line 3116, in __init__
super(LoadImagesImageProvider, self).__init__(name, pathname, filename)
File "F:\CellProfiler\cellprofiler\modules\loadimages.py", line 3002, in __init__
if pathname.startswith(FILE_SCHEME):
AttributeError: 'NoneType' object has no attribute 'startswith'

# Fixed code
def validate_module(self, pipeline):
    # Keep users from using LoadSingleImage to define image sets
    if not any([x.is_load_module() for x in pipeline.modules()]):
        raise cps.ValidationError(
            "LoadSingleImage cannot be used to run a pipeline on one "
            "image file. Please use LoadImages or LoadData instead.",
            self.directory,
        )

    # Make sure LoadSingleImage appears after all other load modules
    after = False
    for module in pipeline.modules():
        if module is self:
            after = True
        elif after and module.is_load_module():
            raise cps.ValidationError(
                "LoadSingleImage must appear after all other Load modules in your pipeline\n"
                "Please move %s before LoadSingleImage" % module.module_name,
                self.directory,
            )

    # Make sure metadata tags exist
    for group in self.file_settings:
        text_str = group.file_name.value
        undefined_tags = pipeline.get_undefined_metadata_tags(text_str)
        if len(undefined_tags) > 0:
            raise cps.ValidationError(
                "%s is not a defined metadata tag. Check the metadata specifications in your load modules"
                % undefined_tags[0],
                group.file_name,
            )
# Buggy code
def get_measurement_columns(self, pipeline):
    all_object_names = list(
        set(
            [
                operand.operand_objects.value
                for operand in self.operands
                if operand.object != cpmeas.IMAGE
            ]
        )
    )
    if len(all_object_names):
        return [
            (name, self.measurement_name(), cpmeas.COLTYPE_FLOAT)
            for name in all_object_names
        ]
    else:
        return [(cpmeas.IMAGE, self.measurement_name(), cpmeas.COLTYPE_FLOAT)]


# Traceback (AssertionError)
Traceback (most recent call last):
File "D:\CellProfiler\Program\cellprofiler\pipeline.py", line 329, in run
self.module.run(self.workspace)
File "D:\CellProfiler\Program\cellprofiler\modules\calculatemath.py", line 293, in run
value = m.get_current_measurement(operand.object,operand.operand_measurement.value)
File "D:\CellProfiler\Program\cellprofiler\measurements.py", line 531, in get_current_measurement
return self.get_measurement(object_name, feature_name, self.image_set_number)
File "D:\CellProfiler\Program\cellprofiler\measurements.py", line 556, in get_measurement
vals = self.hdf5_dict[object_name, feature_name, image_set_number]
File "D:\CellProfiler\Program\cellprofiler\utilities\hdf5_dict.py", line 269, in __getitem__
assert feature_exists
AssertionError

# Fixed code
def get_measurement_columns(self, pipeline):
    all_object_names = list(
        set(
            [
                operand.operand_objects.value
                for operand in self.get_operands()
                if operand.object != cpmeas.IMAGE
            ]
        )
    )
    if len(all_object_names):
        return [
            (name, self.measurement_name(), cpmeas.COLTYPE_FLOAT)
            for name in all_object_names
        ]
    else:
        return [(cpmeas.IMAGE, self.measurement_name(), cpmeas.COLTYPE_FLOAT)]
# Buggy code
def get_categories(self, pipeline, object_name):
    all_object_names = [
        operand.operand_objects.value
        for operand in self.operands
        if operand.object != cpmeas.IMAGE
    ]
    if len(all_object_names):
        if object_name in all_object_names:
            return [C_MATH]
    elif object_name == cpmeas.IMAGE:
        return [C_MATH]
    return []


# Traceback (AssertionError)
Traceback (most recent call last):
File "D:\CellProfiler\Program\cellprofiler\pipeline.py", line 329, in run
self.module.run(self.workspace)
File "D:\CellProfiler\Program\cellprofiler\modules\calculatemath.py", line 293, in run
value = m.get_current_measurement(operand.object,operand.operand_measurement.value)
File "D:\CellProfiler\Program\cellprofiler\measurements.py", line 531, in get_current_measurement
return self.get_measurement(object_name, feature_name, self.image_set_number)
File "D:\CellProfiler\Program\cellprofiler\measurements.py", line 556, in get_measurement
vals = self.hdf5_dict[object_name, feature_name, image_set_number]
File "D:\CellProfiler\Program\cellprofiler\utilities\hdf5_dict.py", line 269, in __getitem__
assert feature_exists
AssertionError

# Fixed code
def get_categories(self, pipeline, object_name):
    all_object_names = [
        operand.operand_objects.value
        for operand in self.get_operands()
        if operand.object != cpmeas.IMAGE
    ]
    if len(all_object_names):
        if object_name in all_object_names:
            return [C_MATH]
    elif object_name == cpmeas.IMAGE:
        return [C_MATH]
    return []
# Buggy code
async def async_set_shuffle(self, shuffle):
    """Enable/disable shuffle mode."""
    await self.alexa_api.shuffle(shuffle)
    self._shuffle = shuffle


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_set_shuffle(self, shuffle):
    """Enable/disable shuffle mode."""
    self.check_login_changes()
    await self.alexa_api.shuffle(shuffle)
    self._shuffle = shuffle
# Buggy code
async def async_set_volume_level(self, volume):
    """Set volume level, range 0..1."""
    if not self.available:
        return
    await self.alexa_api.set_volume(volume)
    self._media_vol_level = volume
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_set_volume_level(self, volume):
    """Set volume level, range 0..1."""
    self.check_login_changes()
    if not self.available:
        return
    await self.alexa_api.set_volume(volume)
    self._media_vol_level = volume
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()
# Buggy code
async def async_media_play(self):
    """Send play command."""
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_play()
    else:
        await self.alexa_api.play()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_media_play(self):
    """Send play command."""
    self.check_login_changes()
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_play()
    else:
        await self.alexa_api.play()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()
# Buggy code
async def async_media_pause(self):
    """Send pause command."""
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_pause()
    else:
        await self.alexa_api.pause()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_media_pause(self):
    """Send pause command."""
    self.check_login_changes()
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_pause()
    else:
        await self.alexa_api.pause()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()
# Buggy code
async def async_turn_off(self):
    """Turn the client off.

    While Alexa's do not have on/off capability, we can use this as another
    trigger to do updates. For turning off, we can clear media_details.
    """
    self._should_poll = False
    await self.async_media_pause()
    self._clear_media_details()


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_turn_off(self):
    """Turn the client off.

    While Alexa's do not have on/off capability, we can use this as another
    trigger to do updates. For turning off, we can clear media_details.
    """
    self.check_login_changes()
    self._should_poll = False
    await self.async_media_pause()
    self._clear_media_details()
# Buggy code
async def async_turn_on(self):
    """Turn the client on.

    While Alexa's do not have on/off capability, we can use this as another
    trigger to do updates.
    """
    self._should_poll = True
    await self.async_media_pause()


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_turn_on(self):
    """Turn the client on.

    While Alexa's do not have on/off capability, we can use this as another
    trigger to do updates.
    """
    self.check_login_changes()
    self._should_poll = True
    await self.async_media_pause()
# Buggy code
async def async_media_next_track(self):
    """Send next track command."""
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_next_track()
    else:
        await self.alexa_api.next()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_media_next_track(self):
    """Send next track command."""
    self.check_login_changes()
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_next_track()
    else:
        await self.alexa_api.next()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()
# Buggy code
async def async_media_previous_track(self):
    """Send previous track command."""
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_previous_track()
    else:
        await self.alexa_api.previous()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_media_previous_track(self):
    """Send previous track command."""
    self.check_login_changes()
    if not (self.state in [STATE_PLAYING, STATE_PAUSED] and self.available):
        return
    if self._playing_parent:
        await self._playing_parent.async_media_previous_track()
    else:
        await self.alexa_api.previous()
    if not (
        self.hass.data[DATA_ALEXAMEDIA]["accounts"][self._login.email]["websocket"]
    ):
        await self.async_update()
# Buggy code
async def async_send_tts(self, message, **kwargs):
    """Send TTS to Device.

    NOTE: Does not work on WHA Groups.
    """
    await self.alexa_api.send_tts(message, customer_id=self._customer_id, **kwargs)


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_send_tts(self, message, **kwargs):
    """Send TTS to Device.

    NOTE: Does not work on WHA Groups.
    """
    self.check_login_changes()
    await self.alexa_api.send_tts(message, customer_id=self._customer_id, **kwargs)
# Buggy code
async def async_send_announcement(self, message, **kwargs):
    """Send announcement to the media player."""
    await self.alexa_api.send_announcement(
        message, customer_id=self._customer_id, **kwargs
    )


# Traceback (RuntimeError)
2020-06-21 12:36:29 ERROR (MainThread) [alexapy.helpers] alexaapi.get_state((<alexapy.alexaapi.AlexaAPI object at 0xa8cddbd0>,), {}): An error occured accessing AlexaAPI: An exception of type RuntimeError occurred. Arguments:
('Session is closed',)
2020-06-21 12:36:29 ERROR (MainThread) [homeassistant.util.logging] Exception in _handle_event when dispatching 'alexa_media_a******e@g*******m': ({'player_state': {'destinationUserId': 'XXX', 'dopplerId': {'deviceType': 'AB72C64C86AW2', 'deviceSerialNumber': 'XXX'}, 'audioPlayerState': 'PLAYING', 'quality': None, 'error': False, 'errorMessage': None, 'mediaReferenceId': '78e56ac3-4ab4-4c85-86b4-3d9bb3f5ae60:6'}},)
Traceback (most recent call last):
File "/config/custom_components/alexa_media/media_player.py", line 369, in _handle_event
await self.async_update()
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 802, in async_update
device, no_throttle=True
File "/config/custom_components/alexa_media/helpers.py", line 148, in wrapper
result = await func(*args, **kwargs)
File "/config/custom_components/alexa_media/media_player.py", line 545, in refresh
session = await self.alexa_api.get_state()
File "/usr/local/lib/python3.7/site-packages/alexapy/helpers.py", line 69, in wrapper
return await func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 761, in get_state
+ "&amp;screenWidth=2560"
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 122, in _get_request
return await self._request("get", uri, data)
File "/usr/local/lib/python3.7/site-packages/backoff/_async.py", line 133, in retry
ret = await target(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/alexapy/alexaapi.py", line 93, in _request
ssl=self._login._ssl,
File "/usr/local/lib/python3.7/site-packages/alexapy/aiohttp/client.py", line 377, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed

# Fixed code
async def async_send_announcement(self, message, **kwargs):
    """Send announcement to the media player."""
    self.check_login_changes()
    await self.alexa_api.send_announcement(
        message, customer_id=self._customer_id, **kwargs
    )