gurudesh/pytracebugs huggingface dataset:
# Buggy code
def async_call(self, name, *args, **kwargs):
    """Call the actual HTTP method, if available."""
    try:
        method = getattr(self, "http_" + name)
    except AttributeError:
        raise HTTPError(405, "{name} method is not allowed".format(name=name.upper()))

    def blocking_call():
        try:
            return method(*args, **kwargs)
        except Exception as error:
            self._handle_request_exception(error)

    return IOLoop.current().run_in_executor(executor, blocking_call)


# Traceback (BadYieldError)
Traceback (most recent call last):
File "/Users/xo/code/Medusa/ext/tornado/web.py", line 1571, in _execute
result = yield result
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1133, in run
value = future.result()
File "/Users/xo/code/Medusa/ext/tornado/concurrent.py", line 261, in result
raise_exc_info(self._exc_info)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1221, in handle_yield
self.future = convert_yielded(yielded)
File "/Users/xo/code/Medusa/ext/singledispatch.py", line 210, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1357, in convert_yielded
return multi(yielded)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 773, in multi
return multi_future(children, quiet_exceptions=quiet_exceptions)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 868, in multi_future
children = list(map(convert_yielded, children))
File "/Users/xo/code/Medusa/ext/singledispatch.py", line 210, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1363, in convert_yielded
raise BadYieldError("yielded unknown object %r" % (yielded,))
BadYieldError: yielded unknown object u'No authorization token.'

# Fixed code
def async_call(self, name, *args, **kwargs):
    """Call the actual HTTP method, if available."""
    try:
        method = getattr(self, "http_" + name)
    except AttributeError:
        raise HTTPError(405)

    def blocking_call():
        result = self._check_authentication()
        return method(*args, **kwargs) if result is None else result

    return IOLoop.current().run_in_executor(executor, blocking_call)
# Buggy code
def blocking_call():
    try:
        return method(*args, **kwargs)
    except Exception as error:
        self._handle_request_exception(error)


# Traceback (BadYieldError)
Traceback (most recent call last):
File "/Users/xo/code/Medusa/ext/tornado/web.py", line 1571, in _execute
result = yield result
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1133, in run
value = future.result()
File "/Users/xo/code/Medusa/ext/tornado/concurrent.py", line 261, in result
raise_exc_info(self._exc_info)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1221, in handle_yield
self.future = convert_yielded(yielded)
File "/Users/xo/code/Medusa/ext/singledispatch.py", line 210, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1357, in convert_yielded
return multi(yielded)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 773, in multi
return multi_future(children, quiet_exceptions=quiet_exceptions)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 868, in multi_future
children = list(map(convert_yielded, children))
File "/Users/xo/code/Medusa/ext/singledispatch.py", line 210, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1363, in convert_yielded
raise BadYieldError("yielded unknown object %r" % (yielded,))
BadYieldError: yielded unknown object u'No authorization token.'

# Fixed code
def blocking_call():
    result = self._check_authentication()
    return method(*args, **kwargs) if result is None else result
# Buggy code
def write_error(self, *args, **kwargs):
    """Only send traceback if app.DEVELOPER is true."""
    if app.DEVELOPER and "exc_info" in kwargs:
        self.set_header("content-type", "text/plain")
        self.set_status(500)
        for line in traceback.format_exception(*kwargs["exc_info"]):
            self.write(line)
        self.finish()
    else:
        response = self._internal_server_error()
        self.finish(response)


# Traceback (BadYieldError)
Traceback (most recent call last):
File "/Users/xo/code/Medusa/ext/tornado/web.py", line 1571, in _execute
result = yield result
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1133, in run
value = future.result()
File "/Users/xo/code/Medusa/ext/tornado/concurrent.py", line 261, in result
raise_exc_info(self._exc_info)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1221, in handle_yield
self.future = convert_yielded(yielded)
File "/Users/xo/code/Medusa/ext/singledispatch.py", line 210, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1357, in convert_yielded
return multi(yielded)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 773, in multi
return multi_future(children, quiet_exceptions=quiet_exceptions)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 868, in multi_future
children = list(map(convert_yielded, children))
File "/Users/xo/code/Medusa/ext/singledispatch.py", line 210, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "/Users/xo/code/Medusa/ext/tornado/gen.py", line 1363, in convert_yielded
raise BadYieldError("yielded unknown object %r" % (yielded,))
BadYieldError: yielded unknown object u'No authorization token.'

# Fixed code
def write_error(self, status_code, *args, **kwargs):
    """Only send traceback if app.DEVELOPER is true."""
    response = None
    exc_info = kwargs.get("exc_info", None)

    if exc_info and isinstance(exc_info[1], HTTPError):
        error = exc_info[1].log_message or exc_info[1].reason
        response = self.api_response(status=status_code, error=error)
    elif app.DEVELOPER and exc_info:
        self.set_header("content-type", "text/plain")
        self.set_status(500)
        for line in traceback.format_exception(*exc_info):
            self.write(line)
    else:
        response = self._internal_server_error()

    self.finish(response)
# Buggy code
def set_caps(self, data):
    """Set caps."""
    if not data:
        return

    def _parse_cap(tag):
        elm = data.find(tag)
        return (
            elm.get("supportedparams").split(",")
            if elm and elm.get("available") == "yes"
            else []
        )

    self.cap_tv_search = _parse_cap("tv-search")
    # self.cap_search = _parse_cap('search')
    # self.cap_movie_search = _parse_cap('movie-search')
    # self.cap_audio_search = _parse_cap('audio-search')

    # self.params = any([self.cap_tv_search, self.cap_search, self.cap_movie_search, self.cap_audio_search])
    self.params = any([self.cap_tv_search])


# Traceback (AttributeError)
2016-12-02 19:05:00 INFO     FINDPROPERS :: [Rarbg] :: [1d6c65b] Searching for any new PROPER releases from Rarbg
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] GET URL: http://torrentapi.org/pubapi_v2.php?get_token=get_token&amp;app_id=medusa&amp;format=json [Status: 200]
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Search mode: Episode
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Unknown exception while searching for propers in Rarbg, skipping: 'NoneType' object has no attribute 'indexer'
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Traceback (most recent call last):
File "C:/Users/Fernando/Documents/Medusa\medusa\search\proper.py", line 137, in _get_proper_results
cur_propers = cur_provider.find_propers(recently_aired)
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\generic_provider.py", line 148, in find_propers
for item in self.search(search_strings[0], ep_obj=episode_obj):
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\torrent\json\rarbg.py", line 99, in search
search_params['search_tvdb'] = self._get_tvdb_id()
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\generic_provider.py", line 486, in _get_tvdb_id
return self.show.indexerid if self.show.indexer == INDEXER_TVDBV2 else self.show.externals.get('tvdb_id')
AttributeError: 'NoneType' object has no attribute 'indexer'

# Fixed code
def set_caps(self, data):
    """Set caps."""
    if not data:
        return

    def _parse_cap(tag):
        elm = data.find(tag)
        is_supported = elm and all(
            [elm.get("supportedparams"), elm.get("available") == "yes"]
        )
        return elm["supportedparams"].split(",") if is_supported else []

    self.cap_tv_search = _parse_cap("tv-search")
    # self.cap_search = _parse_cap('search')

    self.params = any(self.cap_tv_search)
# Buggy code
def _parse_cap(tag):
    elm = data.find(tag)
    return (
        elm.get("supportedparams").split(",")
        if elm and elm.get("available") == "yes"
        else []
    )


# Traceback (AttributeError)
2016-12-02 19:05:00 INFO     FINDPROPERS :: [Rarbg] :: [1d6c65b] Searching for any new PROPER releases from Rarbg
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] GET URL: http://torrentapi.org/pubapi_v2.php?get_token=get_token&amp;app_id=medusa&amp;format=json [Status: 200]
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Search mode: Episode
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Unknown exception while searching for propers in Rarbg, skipping: 'NoneType' object has no attribute 'indexer'
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Traceback (most recent call last):
File "C:/Users/Fernando/Documents/Medusa\medusa\search\proper.py", line 137, in _get_proper_results
cur_propers = cur_provider.find_propers(recently_aired)
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\generic_provider.py", line 148, in find_propers
for item in self.search(search_strings[0], ep_obj=episode_obj):
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\torrent\json\rarbg.py", line 99, in search
search_params['search_tvdb'] = self._get_tvdb_id()
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\generic_provider.py", line 486, in _get_tvdb_id
return self.show.indexerid if self.show.indexer == INDEXER_TVDBV2 else self.show.externals.get('tvdb_id')
AttributeError: 'NoneType' object has no attribute 'indexer'

# Fixed code
def _parse_cap(tag):
    elm = data.find(tag)
    is_supported = elm and all(
        [elm.get("supportedparams"), elm.get("available") == "yes"]
    )
    return elm["supportedparams"].split(",") if is_supported else []
# Buggy code
def set_caps(self, data):
    """Set caps."""
    if not data:
        return

    def _parse_cap(tag):
        elm = data.find(tag)
        return (
            elm.get("supportedparams").split(",")
            if elm and elm.get("available") == "yes"
            else []
        )

    self.cap_tv_search = _parse_cap("tv-search")


# Traceback (AttributeError)
2016-12-02 19:05:00 INFO     FINDPROPERS :: [Rarbg] :: [1d6c65b] Searching for any new PROPER releases from Rarbg
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] GET URL: http://torrentapi.org/pubapi_v2.php?get_token=get_token&amp;app_id=medusa&amp;format=json [Status: 200]
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Search mode: Episode
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Unknown exception while searching for propers in Rarbg, skipping: 'NoneType' object has no attribute 'indexer'
2016-12-02 19:05:01 DEBUG    FINDPROPERS :: [Rarbg] :: [1d6c65b] Traceback (most recent call last):
File "C:/Users/Fernando/Documents/Medusa\medusa\search\proper.py", line 137, in _get_proper_results
cur_propers = cur_provider.find_propers(recently_aired)
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\generic_provider.py", line 148, in find_propers
for item in self.search(search_strings[0], ep_obj=episode_obj):
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\torrent\json\rarbg.py", line 99, in search
search_params['search_tvdb'] = self._get_tvdb_id()
File "C:/Users/Fernando/Documents/Medusa\medusa\providers\generic_provider.py", line 486, in _get_tvdb_id
return self.show.indexerid if self.show.indexer == INDEXER_TVDBV2 else self.show.externals.get('tvdb_id')
AttributeError: 'NoneType' object has no attribute 'indexer'

# Fixed code
def set_caps(self, data):
    """Set caps."""
    if not data:
        return

    def _parse_cap(tag):
        elm = data.find(tag)
        is_supported = elm and all(
            [elm.get("supportedparams"), elm.get("available") == "yes"]
        )
        return elm["supportedparams"].split(",") if is_supported else []

    self.cap_tv_search = _parse_cap("tv-search")
# Buggy code
def _create_recommended_show(self, series, storage_key=None):
    """Create the RecommendedShow object from the returned showobj."""
    try:
        tvdb_id = cached_aid_to_tvdb(series.aid)
    except Exception:
        log.warning("Couldn't map AniDB id {0} to a TVDB id", series.aids)
        return None

    # If the anime can't be mapped to a tvdb_id, return none, and move on to the next.
    if not tvdb_id:
        return tvdb_id

    rec_show = RecommendedShow(
        self,
        series.aid,
        series.title,
        INDEXER_TVDBV2,
        tvdb_id,
        **{
            "rating": series.rating_permanent,
            "votes": series.count_permanent,
            "image_href": self.base_url.format(aid=series.aid),
            "ids": {"tvdb": tvdb_id, "aid": series.aid},
        },
    )

    # Check cache or get and save image
    use_default = self.default_img_src if not series.picture.url else None
    rec_show.cache_image(series.picture.url, default=use_default)

    # By default pre-configure the show option anime = True
    rec_show.is_anime = True

    return rec_show


# Traceback (KeyError)
2019-01-06 09:32:34 ERROR    Thread_0 :: [b15af93] Make sure you pass kwargs parameter `storage_key` to configure the key, that is used in the dogpile cache.
Traceback (most recent call last):
File "/home/**********/.medusa/medusa/show/recommendations/recommended.py", line 234, in generate_key
return kwargs['storage_key'].encode('utf-8')
KeyError: u'storage_key'

# Fixed code
def _create_recommended_show(self, storage_key, series):
    """Create the RecommendedShow object from the returned showobj."""
    try:
        tvdb_id = cached_aid_to_tvdb(series.aid)
    except Exception:
        log.warning("Couldn't map AniDB id {0} to a TVDB id", series.aids)
        return None

    # If the anime can't be mapped to a tvdb_id, return none, and move on to the next.
    if not tvdb_id:
        return tvdb_id

    rec_show = RecommendedShow(
        self,
        series.aid,
        series.title,
        INDEXER_TVDBV2,
        tvdb_id,
        **{
            "rating": series.rating_permanent,
            "votes": series.count_permanent,
            "image_href": self.base_url.format(aid=series.aid),
            "ids": {"tvdb": tvdb_id, "aid": series.aid},
        },
    )

    # Check cache or get and save image
    use_default = self.default_img_src if not series.picture.url else None
    rec_show.cache_image(series.picture.url, default=use_default)

    # By default pre-configure the show option anime = True
    rec_show.is_anime = True

    return rec_show
# Buggy code
def fetch_popular_shows(self, list_type=REQUEST_HOT):
    """Get popular show information from IMDB."""
    series = []
    result = []

    try:
        series = Anidb(cache_dir=join(app.CACHE_DIR, "simpleanidb")).get_list(list_type)
    except GeneralError as error:
        log.warning("Could not connect to AniDB service: {0}", error)

    for show in series:
        try:
            recommended_show = self._create_recommended_show(
                show, storage_key="anidb_{0}".format(show.aid)
            )
            if recommended_show:
                result.append(recommended_show)
        except MissingTvdbMapping:
            log.info("Could not parse AniDB show {0}, missing tvdb mapping", show.title)
        except Exception:
            log.warning(
                "Could not parse AniDB show, with exception: {0}",
                traceback.format_exc(),
            )

    return result


# Traceback (KeyError)
2019-01-06 09:32:34 ERROR    Thread_0 :: [b15af93] Make sure you pass kwargs parameter `storage_key` to configure the key, that is used in the dogpile cache.
Traceback (most recent call last):
File "/home/**********/.medusa/medusa/show/recommendations/recommended.py", line 234, in generate_key
return kwargs['storage_key'].encode('utf-8')
KeyError: u'storage_key'

# Fixed code
def fetch_popular_shows(self, list_type=REQUEST_HOT):
    """Get popular show information from IMDB."""
    series = []
    result = []

    try:
        series = Anidb(cache_dir=join(app.CACHE_DIR, "simpleanidb")).get_list(list_type)
    except GeneralError as error:
        log.warning("Could not connect to AniDB service: {0}", error)

    for show in series:
        try:
            recommended_show = self._create_recommended_show(
                storage_key=show.aid, series=show
            )
            if recommended_show:
                result.append(recommended_show)
        except MissingTvdbMapping:
            log.info("Could not parse AniDB show {0}, missing tvdb mapping", show.title)
        except Exception:
            log.warning(
                "Could not parse AniDB show, with exception: {0}",
                traceback.format_exc(),
            )

    return result
# Buggy code
def _create_recommended_show(self, series, storage_key=None):
    """Create the RecommendedShow object from the returned showobj."""
    tvdb_id = helpers.get_tvdb_from_id(series.get("imdb_tt"), "IMDB")

    if not tvdb_id:
        return None

    rec_show = RecommendedShow(
        self,
        series.get("imdb_tt"),
        series.get("name"),
        INDEXER_TVDBV2,
        int(tvdb_id),
        **{
            "rating": series.get("rating"),
            "votes": series.get("votes"),
            "image_href": series.get("imdb_url"),
        },
    )

    if series.get("image_url"):
        rec_show.cache_image(series.get("image_url"))

    return rec_show


# Traceback (KeyError)
2019-01-06 09:32:34 ERROR    Thread_0 :: [b15af93] Make sure you pass kwargs parameter `storage_key` to configure the key, that is used in the dogpile cache.
Traceback (most recent call last):
File "/home/**********/.medusa/medusa/show/recommendations/recommended.py", line 234, in generate_key
return kwargs['storage_key'].encode('utf-8')
KeyError: u'storage_key'

# Fixed code
def _create_recommended_show(self, storage_key, series):
    """Create the RecommendedShow object from the returned showobj."""
    tvdb_id = helpers.get_tvdb_from_id(series.get("imdb_tt"), "IMDB")

    if not tvdb_id:
        return None

    rec_show = RecommendedShow(
        self,
        series.get("imdb_tt"),
        series.get("name"),
        INDEXER_TVDBV2,
        int(tvdb_id),
        **{
            "rating": series.get("rating"),
            "votes": series.get("votes"),
            "image_href": series.get("imdb_url"),
        },
    )

    if series.get("image_url"):
        rec_show.cache_image(series.get("image_url"))

    return rec_show
# Buggy code
def create_key_from_series(namespace, fn, **kw):
    """Generate a key limiting the amount of dictionaries keys that are allowed to be used."""

    def generate_key(*arg, **kwargs):
        """
        Generate the key.

        The key is passed to the decorated function using the kwargs `storage_key`.
        Following this standard we can cache every object, using this key_generator.
        """
        try:
            if PY2:
                return kwargs["storage_key"].encode("utf-8")
            return kwargs["storage_key"]
        except KeyError:
            log.exception(
                "Make sure you pass kwargs parameter `storage_key` to configure the key,"
                " that is used in the dogpile cache."
            )

    return generate_key


# Traceback (KeyError)
2019-01-06 09:32:34 ERROR    Thread_0 :: [b15af93] Make sure you pass kwargs parameter `storage_key` to configure the key, that is used in the dogpile cache.
Traceback (most recent call last):
File "/home/**********/.medusa/medusa/show/recommendations/recommended.py", line 234, in generate_key
return kwargs['storage_key'].encode('utf-8')
KeyError: u'storage_key'

# Fixed code
def create_key_from_series(namespace, fn, **kw):
    """Create a key made of indexer name and show ID."""

    def generate_key(*args, **kw):
        show_key = namespace + "_" + text_type(args[1])
        if PY2:
            return show_key.encode("utf-8")
        return show_key

    return generate_key
# Buggy code
def generate_key(*arg, **kwargs):
    """
    Generate the key.

    The key is passed to the decorated function using the kwargs `storage_key`.
    Following this standard we can cache every object, using this key_generator.
    """
    try:
        if PY2:
            return kwargs["storage_key"].encode("utf-8")
        return kwargs["storage_key"]
    except KeyError:
        log.exception(
            "Make sure you pass kwargs parameter `storage_key` to configure the key,"
            " that is used in the dogpile cache."
        )


# Traceback (KeyError)
2019-01-06 09:32:34 ERROR    Thread_0 :: [b15af93] Make sure you pass kwargs parameter `storage_key` to configure the key, that is used in the dogpile cache.
Traceback (most recent call last):
File "/home/**********/.medusa/medusa/show/recommendations/recommended.py", line 234, in generate_key
return kwargs['storage_key'].encode('utf-8')
KeyError: u'storage_key'

# Fixed code
def generate_key(*args, **kw):
    show_key = namespace + "_" + text_type(args[1])
    if PY2:
        return show_key.encode("utf-8")
    return show_key
# Buggy code
def get_all_recommended_series_from_cache(indexers):
    """
    Retrieve all recommended show objects from the dogpile cache for a specific indexer or a number of indexers.

    For example: `get_all_recommended_series_from_cache(['imdb', 'anidb'])` will return all recommended show objects, for the
    indexers imdb and anidb.

    :param indexers: indexer or list of indexers. Indexers need to be passed as a string. For example: 'imdb', 'anidb' or 'trakt'.
    :return: List of recommended show objects.
    """
    indexers = ensure_list(indexers)
    all_series = []
    for indexer in indexers:
        index = recommended_series_cache.get(binary_type(indexer))
        if not index:
            continue

        for index_item in index:
            key = "{indexer}_{series_id}".format(indexer=indexer, series_id=index_item)
            series = recommended_series_cache.get(binary_type(key))
            if series:
                all_series.append(series)

    return all_series


# Traceback (KeyError)
2019-01-06 09:32:34 ERROR    Thread_0 :: [b15af93] Make sure you pass kwargs parameter `storage_key` to configure the key, that is used in the dogpile cache.
Traceback (most recent call last):
File "/home/**********/.medusa/medusa/show/recommendations/recommended.py", line 234, in generate_key
return kwargs['storage_key'].encode('utf-8')
KeyError: u'storage_key'

# Fixed code
def get_all_recommended_series_from_cache(indexers):
    """
    Retrieve all recommended show objects from the dogpile cache for a specific indexer or a number of indexers.

    For example: `get_all_recommended_series_from_cache(['imdb', 'anidb'])` will return all recommended show objects, for the
    indexers imdb and anidb.

    :param indexers: indexer or list of indexers. Indexers need to be passed as a string. For example: 'imdb', 'anidb' or 'trakt'.
    :return: List of recommended show objects.
    """
    indexers = ensure_list(indexers)
    all_series = []
    for indexer in indexers:
        index = recommended_series_cache.get(ensure_str(indexer))
        if not index:
            continue

        for index_item in index:
            key = "{indexer}_{series_id}".format(indexer=indexer, series_id=index_item)
            series = recommended_series_cache.get(key)
            if series:
                all_series.append(series)

    return all_series
# Buggy code
def encrypt(data, encryption_version=0, _decrypt=False):
    # Version 1: Simple XOR encryption (this is not very secure, but works)
    if encryption_version == 1:
        if _decrypt:
            return "".join(
                chr(ord(x) ^ ord(y))
                for (x, y) in zip(base64.decodestring(data), cycle(unique_key1))
            )
        else:
            return base64.encodestring(
                "".join(
                    chr(ord(x) ^ ord(y)) for (x, y) in zip(data, cycle(unique_key1))
                )
            ).strip()
    # Version 2: Simple XOR encryption (this is not very secure, but works)
    elif encryption_version == 2:
        if _decrypt:
            return "".join(
                chr(ord(x) ^ ord(y))
                for (x, y) in zip(
                    base64.decodestring(data), cycle(app.ENCRYPTION_SECRET)
                )
            )
        else:
            return base64.encodestring(
                "".join(
                    chr(ord(x) ^ ord(y))
                    for (x, y) in zip(data, cycle(app.ENCRYPTION_SECRET))
                )
            ).strip()
    # Version 0: Plain text
    else:
        return data


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Python37\lib\base64.py", line 517, in _input_type_check
m = memoryview(s)
TypeError: memoryview: a bytes-like object is required, not 'str'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Medusa\medusa\config.py", line 729, in check_setting_str
my_val = helpers.decrypt(config[cfg_name][item_name], encryption_version)
File "C:\Medusa\medusa\helpers\__init__.py", line 977, in decrypt
return encrypt(data, encryption_version, _decrypt=True)
File "C:\Medusa\medusa\helpers\__init__.py", line 966, in encrypt
return ''.join(chr(ord(x) ^ ord(y)) for (x, y) in zip(base64.decodestring(data),
File "C:\Python37\lib\base64.py", line 561, in decodestring
return decodebytes(s)
File "C:\Python37\lib\base64.py", line 552, in decodebytes
_input_type_check(s)
File "C:\Python37\lib\base64.py", line 520, in _input_type_check
raise TypeError(msg) from err
TypeError: expected bytes-like object, not str

# Fixed code
def encrypt(data, encryption_version=0, _decrypt=False):
    # Version 0: Plain text
    if encryption_version == 0:
        return data
    else:
        # Simple XOR encryption, Base64 encoded
        # Version 1: unique_key1; Version 2: app.ENCRYPTION_SECRET
        key = unique_key1 if encryption_version == 1 else app.ENCRYPTION_SECRET
        if _decrypt:
            data = ensure_text(base64.decodestring(ensure_binary(data)))
            return "".join(chr(ord(x) ^ ord(y)) for (x, y) in zip(data, cycle(key)))
        else:
            data = "".join(chr(ord(x) ^ ord(y)) for (x, y) in zip(data, cycle(key)))
            return ensure_text(base64.encodestring(ensure_binary(data))).strip()
# Buggy code
def list_remote_branches():
    gh = get_github_repo(app.GIT_ORG, app.GIT_REPO)
    return [x.name for x in gh.get_branches() if x]


# Traceback (GithubException)
2018-07-17 03:46:37 DEBUG    CHECKVERSION :: [1a8dc66] Starting new thread: CHECKVERSION
2018-07-17 03:46:39 DEBUG    CHECKVERSION :: [1a8dc66] Unable to contact Github: GithubException(500, None)
2018-07-17 03:46:39 ERROR    CHECKVERSION :: [1a8dc66] Exception generated: 500 None
Traceback (most recent call last):
  File "/app/medusa/medusa/scheduler.py", line 93, in run
    self.action.run(self.force)
  File "/app/medusa/medusa/version_checker.py", line 67, in run
    self.list_remote_branches()
  File "/app/medusa/medusa/version_checker.py", line 357, in list_remote_branches
    app.GIT_REMOTE_BRANCHES = self.updater.list_remote_branches()
  File "/app/medusa/medusa/version_checker.py", line 981, in list_remote_branches
    gh = get_github_repo(app.GIT_ORG, app.GIT_REPO)
  File "/app/medusa/medusa/github_client.py", line 101, in get_github_repo
    return gh.get_organization(organization).get_repo(repo)
  File "/app/medusa/ext/github/Organization.py", line 652, in get_repo
    "/repos/" + self.login + "/" + name
  File "/app/medusa/ext/github/Requester.py", line 185, in requestJsonAndCheck
    return self.__check(*self.requestJson(verb, url, parameters, headers, input, cnx))
  File "/app/medusa/ext/github/Requester.py", line 198, in __check
    raise self.__createException(status, responseHeaders, output)
GithubException: 500 None

# Fixed code
def list_remote_branches():
    try:
        gh = get_github_repo(app.GIT_ORG, app.GIT_REPO)
        return [x.name for x in gh.get_branches() if x]
    except GithubException as error:
        log.warning("Unable to contact github, can't check for update: {0!r}", error)
        return []
# Buggy code
def copyfile_custom(src, dst):
    """Copy data from src to dst"""
    if _samefile(src, dst):
        raise Error("`%s` and `%s` are the same file" % (src, dst))

    for fn in [src, dst]:
        try:
            st = os.stat(fn)
        except OSError:
            # File most likely does not exist
            pass
        else:
            # XXX What about other special files? (sockets, devices...)
            if stat.S_ISFIFO(st.st_mode):
                try:
                    raise SpecialFileError("`%s` is a named pipe" % fn)
                except NameError:
                    raise Error("`%s` is a named pipe" % fn)

    try:
        # Windows
        O_BINARY = os.O_BINARY
    except:
        O_BINARY = 0

    READ_FLAGS = os.O_RDONLY | O_BINARY
    WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | O_BINARY
    BUFFER_SIZE = 128 * 1024

    try:
        fin = os.open(src, READ_FLAGS)
        fout = os.open(dst, WRITE_FLAGS)
        for x in iter(lambda: os.read(fin, BUFFER_SIZE), ""):
            os.write(fout, x)
    except Exception as e:
        raise
    finally:
        try:
            os.close(fin)
            os.close(fout)
        except:
            pass


# Traceback (OSError)
the.bold.type.s02e02.720p.web.x264-tbs.mkv to /mnt/Resources/TV/The xxx xxx/Season.02/The.xxx.xxx.S02E02.xxx yyy zzz.720p WEB-DL.mkv
2018-06-13 03:38:44 ERROR    Thread_16 :: [c65ca26] OSError:
Traceback (most recent call last):
File "/app/medusa/medusa/helpers/__init__.py", line 286, in copy_file
shutil.copyfile(src_file, dest_file)
File "/app/medusa/lib/shutil_custom/__init__.py", line 44, in copyfile_custom
os.write(fout, x)
OSError: [Errno 9] Bad file descriptor
2018-06-13 03:38:44 DEBUG    Thread_16 :: [c65ca26] Setting permissions for /mnt/Resources/TV/The xxx xxx/Season.02/The.xxx.xxx.S02E02.xxx yyy zzz.720p WEB-DL.mkv to 438 as parent directory has 511

# Fixed code
def copyfile_custom(src, dst):
    """Copy data from src to dst."""

    def special_file(fn):
        try:
            st = os.stat(fn)
        except OSError:
            # File most likely does not exist
            pass
        else:
            if stat.S_ISFIFO(st.st_mode):
                raise SpecialFileError("{!r} is a named pipe".format(fn))

    if _samefile(src, dst):
        raise SameFileError("{!r} and {!r} are the same file".format(src, dst))

    special_file(src)
    special_file(dst)

    with open(src, "rb") as fsrc, open(dst, "wb") as fdst:
        while True:
            buf = fsrc.read(BUFFER_SIZE)
            if not buf:
                break
            fdst.write(buf)
# Buggy code
def sanitize_filename(filename):
    """
    Remove specific characters from the provided ``filename``.
    :param filename: The filename to clean
    :return: The ``filename``cleaned
    """

    if isinstance(filename, (str, text_type)):
        filename = re.sub(r"[\\/\*]", "-", filename)
        filename = re.sub(r'[:"<>|?]', "", filename)
        filename = re.sub(r"™", "", filename)  # Trade Mark Sign unicode: \u2122
        filename = filename.strip(" .")

        return filename

    return ""


# Traceback (OSError)
2018-03-07 20:42:22 ERROR    Thread-34 :: [d6eb72d] OSError:
Traceback (most recent call last):
File "C:\PythonPrograms\Medusa\medusa\helpers\__init__.py", line 285, in copy_file
shutil.copyfile(src_file, dest_file)
File "C:\PythonPrograms\Medusa\lib\shutil_custom\__init__.py", line 42, in copyfile_custom
fout = os.open(dst, WRITE_FLAGS)
OSError: [Errno 22] Invalid argument
2018-03-07 20:42:22 ERROR    Thread-34 :: [d6eb72d] Unable to write file to D:\media\Videos\TV Shows\Ask Us Anything\Season 01\Ask Us Anything - S01E98 - Episode 98 with Jung-soo &amp; Ha Yeon-soo	.nfo: Environment error: [Errno 22] Invalid argument: u'D:\\media\\Videos\\TV Shows\\Ask Us Anything\\Season 01\\Ask Us Anything - S01E98 - Episode 98 with Jung-soo &amp; Ha Yeon-soo\t.nfo'

# Fixed code
def sanitize_filename(filename):
    """
    Remove specific characters from the provided ``filename``.
    :param filename: The filename to clean
    :return: The cleaned ``filename``
    """

    if isinstance(filename, (str, text_type)):
        # https://stackoverflow.com/a/31976060/7597273
        remove = r"".join(
            (
                r':"<>|?',
                r"™",  # Trade Mark Sign [unicode: \u2122]
                r"\t",  # Tab
                r"\x00-\x1f",  # Null & Control characters
            )
        )
        remove = r"[" + remove + r"]"

        filename = re.sub(r"[\\/\*]", "-", filename)
        filename = re.sub(remove, "", filename)
        # Filenames cannot end in a space or dot on Windows systems
        filename = filename.strip(" .")

        return filename

    return ""
# Buggy code
def index(self, path="", includeFiles=False, *args, **kwargs):
    # @TODO: Move all cache control headers to the whole API end point so nothing's cached
    self.set_header("Cache-Control", "max-age=0,no-cache,no-store")
    self.set_header("Content-Type", "application/json")
    return json.dumps(list_folders(path, True, bool(int(includeFiles))))


# Traceback (ValueError)
2018-03-18 12:11:29 ERROR    Thread-17 :: [e11c71e] Exception generated: invalid literal for int() with base 10: 'false'
Traceback (most recent call last):
File "/Users/xo/code/Medusa/medusa/server/web/core/base.py", line 281, in async_call
result = function(**kwargs)
File "/Users/xo/code/Medusa/medusa/server/web/core/file_browser.py", line 23, in index
return json.dumps(list_folders(path, True, bool(int(includeFiles))))
ValueError: invalid literal for int() with base 10: 'false'

# Fixed code
def index(self, path="", includeFiles=False, *args, **kwargs):
    # @TODO: Move all cache control headers to the whole API end point so nothing's cached
    self.set_header("Cache-Control", "max-age=0,no-cache,no-store")
    self.set_header("Content-Type", "application/json")
    return json.dumps(list_folders(path, True, truth_to_bool(includeFiles)))
# Buggy code
def complete(self, term, includeFiles=0, *args, **kwargs):
    self.set_header("Cache-Control", "max-age=0,no-cache,no-store")
    self.set_header("Content-Type", "application/json")
    paths = [
        entry["path"]
        for entry in list_folders(
            os.path.dirname(term), include_files=bool(int(includeFiles))
        )
        if "path" in entry
    ]

    return json.dumps(paths)


# Traceback (ValueError)
2018-03-18 12:11:29 ERROR    Thread-17 :: [e11c71e] Exception generated: invalid literal for int() with base 10: 'false'
Traceback (most recent call last):
File "/Users/xo/code/Medusa/medusa/server/web/core/base.py", line 281, in async_call
result = function(**kwargs)
File "/Users/xo/code/Medusa/medusa/server/web/core/file_browser.py", line 23, in index
return json.dumps(list_folders(path, True, bool(int(includeFiles))))
ValueError: invalid literal for int() with base 10: 'false'

# Fixed code
def complete(self, term, includeFiles=False, *args, **kwargs):
    self.set_header("Cache-Control", "max-age=0,no-cache,no-store")
    self.set_header("Content-Type", "application/json")
    paths = [
        entry["path"]
        for entry in list_folders(
            os.path.dirname(term), include_files=truth_to_bool(includeFiles)
        )
        if "path" in entry
    ]

    return json.dumps(paths)
# Buggy code
def poster(self):
    """Return poster path."""
    img_type = image_cache.POSTER
    return image_cache.get_artwork(img_type, self.series_id)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/xo/code/Medusa/ext/tornado/web.py", line 1510, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/Users/xo/code/Medusa/medusa/server/api/v2/series.py", line 43, in get
data = [s.to_json(detailed=detailed) for s in Series.find_series(predicate=filter_series)]
File "/Users/xo/code/Medusa/medusa/tv/series.py", line 2020, in to_json
data['cache']['poster'] = self.poster
File "/Users/xo/code/Medusa/medusa/tv/series.py", line 527, in poster
return image_cache.get_artwork(img_type, self.series_id)
File "/Users/xo/code/Medusa/medusa/image_cache.py", line 111, in get_artwork
location = get_path(img_type, series_obj)
File "/Users/xo/code/Medusa/medusa/image_cache.py", line 94, in get_path
location = _cache_dir(series_obj)
File "/Users/xo/code/Medusa/medusa/image_cache.py", line 71, in _cache_dir
return os.path.abspath(os.path.join(app.CACHE_DIR, 'images', series_obj.indexer_name))
AttributeError: 'int' object has no attribute 'indexer_name'

# Fixed code
def poster(self):
    """Return poster path."""
    img_type = image_cache.POSTER
    return image_cache.get_artwork(img_type, self)
# Buggy code
def banner(self):
    """Return banner path."""
    img_type = image_cache.POSTER
    return image_cache.get_artwork(img_type, self.series_id)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/xo/code/Medusa/ext/tornado/web.py", line 1510, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/Users/xo/code/Medusa/medusa/server/api/v2/series.py", line 43, in get
data = [s.to_json(detailed=detailed) for s in Series.find_series(predicate=filter_series)]
File "/Users/xo/code/Medusa/medusa/tv/series.py", line 2020, in to_json
data['cache']['poster'] = self.poster
File "/Users/xo/code/Medusa/medusa/tv/series.py", line 527, in poster
return image_cache.get_artwork(img_type, self.series_id)
File "/Users/xo/code/Medusa/medusa/image_cache.py", line 111, in get_artwork
location = get_path(img_type, series_obj)
File "/Users/xo/code/Medusa/medusa/image_cache.py", line 94, in get_path
location = _cache_dir(series_obj)
File "/Users/xo/code/Medusa/medusa/image_cache.py", line 71, in _cache_dir
return os.path.abspath(os.path.join(app.CACHE_DIR, 'images', series_obj.indexer_name))
AttributeError: 'int' object has no attribute 'indexer_name'

# Fixed code
def banner(self):
    """Return banner path."""
    img_type = image_cache.POSTER
    return image_cache.get_artwork(img_type, self)
# Buggy code
def unpack_rar_files(dirpath):
    """Unpack any existing rar files present in the specified dirpath.

    :param dirpath: the directory path to be used
    :type dirpath: str
    """
    from . import process_tv

    for root, _, files in os.walk(dirpath, topdown=False):
        rar_files = [rar_file for rar_file in files if is_rar_file(rar_file)]
        if rar_files and app.UNPACK:
            video_files = [
                video_file for video_file in files if is_media_file(video_file)
            ]
            if "_UNPACK" not in root and (
                not video_files or root == app.TV_DOWNLOAD_DIR
            ):
                logger.debug("Found rar files in post-process folder: %s", rar_files)
                process_tv.ProcessResult(app.TV_DOWNLOAD_DIR).unrar(
                    root, rar_files, False
                )
        elif rar_files and not app.UNPACK:
            logger.warning("Unpack is disabled. Skipping: %s", rar_files)


# Traceback (MalformedMKVError)
2017-05-05 02:12:38 DEBUG    FINDSUBTITLES :: [36052ba] Scanning video u'eac78f3f87564f4a8069530a8c22824a.mkv' in u'/media/SAMSUNG/media/downloaded/series/Show.S01E20.1080p.AMZN.WEBRip.DD.5.1.x264-RTN-Scrambled/_unpack'
2017-05-05 02:12:41 DEBUG    FINDSUBTITLES :: [36052ba] Refining video with metadata
2017-05-05 02:12:41 WARNING  FINDSUBTITLES :: [36052ba] Failed to refine video
Traceback (most recent call last):
File "/home/osmc/Medusa/lib/subliminal/core.py", line 543, in refine
refiner_manager[refiner].plugin(video, **kwargs)
File "/home/osmc/Medusa/lib/subliminal/refiners/metadata.py", line 32, in refine
mkv = MKV(f)
File "/home/osmc/Medusa/lib/enzyme/mkv.py", line 56, in __init__
raise MalformedMKVError('Parsing error: %s' % e)
MalformedMKVError: Parsing error: Less than 1 bytes read (0)

# Fixed code
def unpack_rar_files(dirpath):
    """Unpack any existing rar files present in the specified dirpath.

    :param dirpath: the directory path to be used
    :type dirpath: str
    """
    from . import process_tv

    for root, _, files in os.walk(dirpath, topdown=False):
        rar_files = [rar_file for rar_file in files if is_rar_file(rar_file)]
        if rar_files and app.UNPACK:
            video_files = [
                video_file for video_file in files if is_media_file(video_file)
            ]
            if "_UNPACK" not in root.upper() and (
                not video_files or root == app.TV_DOWNLOAD_DIR
            ):
                logger.debug("Found rar files in post-process folder: %s", rar_files)
                process_tv.ProcessResult(app.TV_DOWNLOAD_DIR).unrar(
                    root, rar_files, False
                )
        elif rar_files and not app.UNPACK:
            logger.warning("Unpack is disabled. Skipping: %s", rar_files)
# Buggy code
def _get_show_by_id(self, tvmaze_id, request_language="en"):  # pylint: disable=unused-argument
    """
    Retrieve tvmaze show information by tvmaze id, or if no tvmaze id provided by passed external id.

    :param tvmaze_id: The shows tvmaze id
    :return: An ordered dict with the show searched for.
    """
    results = None
    if tvmaze_id:
        logger.debug("Getting all show data for %s", [tvmaze_id])
        results = self.tvmaze_api.get_show(maze_id=tvmaze_id)

    if not results:
        return

    mapped_results = self._map_results(results, self.series_map)

    return OrderedDict({"series": mapped_results})


# Traceback (KeyError)
2017-03-24 13:09:12 DEBUG    SHOWQUEUE-UPDATE :: [b4a8a54] Using DVD ordering.
Exception in thread SHOWQUEUE-UPDATE:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:/Users/fernando/Documents/Medusa\medusa\show_queue.py", line 722, in run
self.show.load_from_indexer()
File "C:/Users/fernando/Documents/Medusa\medusa\tv\series.py", line 1211, in load_from_indexer
indexed_show = self.indexer_api[self.indexerid]
File "C:/Users/fernando/Documents/Medusa\medusa\indexers\indexer_base.py", line 254, in __getitem__
self._get_show_data(key, self.config['language'])
File "C:/Users/fernando/Documents/Medusa\medusa\indexers\tvmaze\tvmaze_api.py", line 432, in _get_show_data
self._get_episodes(tvmaze_id, specials=False, aired_season=None)
File "C:/Users/fernando/Documents/Medusa\medusa\indexers\tvmaze\tvmaze_api.py", line 255, in _get_episodes
use_dvd = cur_ep['dvd_season'] is not None and cur_ep['dvd_episodenumber'] is not None
KeyError: u'dvd_season'

# Fixed code
def _get_show_by_id(self, tvmaze_id, request_language="en"):  # pylint: disable=unused-argument
    """
    Retrieve tvmaze show information by tvmaze id, or if no tvmaze id provided by passed external id.

    :param tvmaze_id: The shows tvmaze id
    :return: An ordered dict with the show searched for.
    """
    results = None
    if tvmaze_id:
        logger.debug("Getting all show data for %s", tvmaze_id)
        results = self.tvmaze_api.get_show(maze_id=tvmaze_id)

    if not results:
        return

    mapped_results = self._map_results(results, self.series_map)

    return OrderedDict({"series": mapped_results})
# Buggy code
def _parse_season_images(self, tvmaze_id):
    """Parse Show and Season posters."""
    seasons = {}
    if tvmaze_id:
        logger.debug("Getting all show data for %s", [tvmaze_id])
        try:
            seasons = self.tvmaze_api.show_seasons(maze_id=tvmaze_id)
        except BaseError as e:
            logger.warning(
                "Getting show seasons for the season images failed. Cause: %s", e
            )

    _images = {"season": {"original": {}}}
    # Get the season posters
    for season in seasons.keys():
        if not getattr(seasons[season], "image", None):
            continue
        if season not in _images["season"]["original"]:
            _images["season"]["original"][season] = {seasons[season].id: {}}
        _images["season"]["original"][season][seasons[season].id]["_bannerpath"] = (
            seasons[season].image["original"]
        )
        _images["season"]["original"][season][seasons[season].id]["rating"] = 1

    return _images


# Traceback (KeyError)
2017-03-24 13:09:12 DEBUG    SHOWQUEUE-UPDATE :: [b4a8a54] Using DVD ordering.
Exception in thread SHOWQUEUE-UPDATE:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:/Users/fernando/Documents/Medusa\medusa\show_queue.py", line 722, in run
self.show.load_from_indexer()
File "C:/Users/fernando/Documents/Medusa\medusa\tv\series.py", line 1211, in load_from_indexer
indexed_show = self.indexer_api[self.indexerid]
File "C:/Users/fernando/Documents/Medusa\medusa\indexers\indexer_base.py", line 254, in __getitem__
self._get_show_data(key, self.config['language'])
File "C:/Users/fernando/Documents/Medusa\medusa\indexers\tvmaze\tvmaze_api.py", line 432, in _get_show_data
self._get_episodes(tvmaze_id, specials=False, aired_season=None)
File "C:/Users/fernando/Documents/Medusa\medusa\indexers\tvmaze\tvmaze_api.py", line 255, in _get_episodes
use_dvd = cur_ep['dvd_season'] is not None and cur_ep['dvd_episodenumber'] is not None
KeyError: u'dvd_season'

# Fixed code
def _parse_season_images(self, tvmaze_id):
    """Parse Show and Season posters."""
    seasons = {}
    if tvmaze_id:
        logger.debug("Getting all show data for %s", tvmaze_id)
        try:
            seasons = self.tvmaze_api.show_seasons(maze_id=tvmaze_id)
        except BaseError as e:
            logger.warning(
                "Getting show seasons for the season images failed. Cause: %s", e
            )

    _images = {"season": {"original": {}}}
    # Get the season posters
    for season in seasons.keys():
        if not getattr(seasons[season], "image", None):
            continue
        if season not in _images["season"]["original"]:
            _images["season"]["original"][season] = {seasons[season].id: {}}
        _images["season"]["original"][season][seasons[season].id]["_bannerpath"] = (
            seasons[season].image["original"]
        )
        _images["season"]["original"][season][seasons[season].id]["rating"] = 1

    return _images
# Buggy code
def _get_rss_data(self):
    """Get RSS data."""
    self.provider.add_cookies_from_ui()
    return self.get_rss_feed(self.provider.url)


# Traceback (TypeError)
2017-04-01 10:11:02 ERROR    Thread-37 :: [44b1453] Exception generated: canAddTorrentRssProvider() got an unexpected keyword argument 'titleTag'
Traceback (most recent call last):
File "H:\usr\local\medusa\medusa\server\web\core\base.py", line 259, in async_call
result = function(**kwargs)
TypeError: canAddTorrentRssProvider() got an unexpected keyword argument 'titleTag'

# Fixed code
def _get_rss_data(self):
    """Get RSS data."""
    return self.get_rss_feed(self.provider.url)