gurudesh/pytracebugs huggingface dataset:
# Buggy code
def jobState():
    currentData = printer.get_current_data()
    return jsonify(
        {
            "job": currentData["job"],
            "progress": currentData["progress"],
            "state": currentData["state"]["text"],
            "printingUser": currentData["printingUser"],
        }
    )


# Traceback (KeyError)
Apr 30 08:31:25 raspberrypi2 octoprint[23585]: 2018-04-30 08:31:25,061 - tornado.access - ERROR - 500 GET /api/job (172.20.0.33) 24.02ms
Apr 30 08:31:28 raspberrypi2 octoprint[23585]: 2018-04-30 08:31:28,054 - octoprint - ERROR - Exception on /api/job [GET]
Apr 30 08:31:28 raspberrypi2 octoprint[23585]: Traceback (most recent call last):
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:   File "/usr/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:     response = self.full_dispatch_request()
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:   File "/usr/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:     rv = self.handle_user_exception(e)
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:   File "/usr/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:     reraise(exc_type, exc_value, tb)
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:   File "/usr/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:     rv = self.dispatch_request()
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:   File "/usr/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:     return self.view_functions[rule.endpoint](**req.view_args)
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:   File "/usr/lib/python2.7/site-packages/octoprint/server/api/job.py", line 73, in jobState
Apr 30 08:31:28 raspberrypi2 octoprint[23585]:     "printingUser": currentData["printingUser"],
Apr 30 08:31:28 raspberrypi2 octoprint[23585]: KeyError: 'printingUser'

# Fixed code
def jobState():
    currentData = printer.get_current_data()
    return jsonify(
        {
            "job": currentData["job"],
            "progress": currentData["progress"],
            "state": currentData["state"]["text"],
        }
    )
# Buggy code
def update_library(self, show=None):
    """Handles updating the Emby Media Server host via HTTP API

    Returns:
        Returns True for no issue or False if there was an error

    """

    if settings.USE_EMBY:
        if not settings.EMBY_HOST:
            logger.debug("EMBY: No host specified, check your settings")
            return False

        params = {}
        if show:
            if show.indexer == 1:
                provider = "tvdb"
            elif show.indexer == 2:
                logger.warning("EMBY: TVRage Provider no longer valid")
                return False
            else:
                logger.warning("EMBY: Provider unknown")
                return False
            params.update({f"{provider}id": show.indexerid})

        url = urljoin(settings.EMBY_HOST, "emby/Library/Series/Updated")

        try:
            session = self.__make_session()
            response = session.get(url, params=params)
            response.raise_for_status()
            logger.debug(
                "EMBY: HTTP response: {0}".format(response.text.replace("\n", ""))
            )
            return True

        except requests.exceptions.RequestException as error:
            logger.warning(f"EMBY: Warning: Could not contact Emby at {url} {error}")

            return False


# Traceback (AttributeError)
2020-09-29 11:18:39 DEBUG :: AUTO :: Failed doing webui request "sickchill/cache/images/268592_fanart_jpg": Traceback (most recent call last):
2020-09-29 11:18:37 WARNING :: WEBSERVER-HOME_0 :: EMBY: Warning: Could not contact Emby at https://emby.mydomain.fr/emby/Library/Series/Updated 404 Client Error: Not Found for url: https://emby.mydomain.fr/emby/Library/Series/Updated?tvdbid=268592
AA AttributeError: 'WebRoot' object has no attribute 'sickchill/cache/images/268592_fanart_jpg'
AA method = getattr(self, route)
AA File "/opt/usenet/SickChill/sickchill/views/index.py", line 159, in get

# Fixed code
def update_library(self, show=None):
    """Handles updating the Emby Media Server host via HTTP API

    Returns:
        Returns True for no issue or False if there was an error

    """

    if settings.USE_EMBY:
        if not settings.EMBY_HOST:
            logger.debug("EMBY: No host specified, check your settings")
            return False

        params = {}
        if show:
            params.update(
                {"Updates": [{"Path": show.location, "UpdateType": "Created"}]}
            )
            url = urljoin(settings.EMBY_HOST, "emby/Library/Media/Updated")
        else:
            url = urljoin(settings.EMBY_HOST, "emby/Library/Refresh")

        try:
            session = self.__make_session()
            response = session.post(url, json=params)
            response.raise_for_status()
            logger.debug(
                "EMBY: HTTP response: {0}".format(response.text.replace("\n", ""))
            )
            return True

        except requests.exceptions.RequestException as error:
            logger.warning(f"EMBY: Warning: Could not contact Emby at {url} {error}")

            return False
# Buggy code
def _verify_download(self, file_name):
    try:
        bencodepy.decode_from_file(file_name)
    except bencodepy.DecodingError as e:
        logger.debug("Failed to validate torrent file: {0}".format(str(e)))
        logger.debug("Result is not a valid torrent file")
        return False
    return True


# Traceback (AttributeError)
AA AttributeError: module 'bencodepy' has no attribute 'DecodingError'
AA except bencodepy.DecodingError as e:
AA File "/opt/sickchill/sickchill/providers/torrent/TorrentProvider.py", line 109, in _verify_download
AA if self._verify_download(downloaded_filename):
AA File "/opt/sickchill/sickchill/providers/GenericProvider.py", line 105, in download_result
AA newResult = resProvider.download_result(result)
AA File "/opt/sickchill/sickchill/oldbeard/search.py", line 34, in _downloadResult
AA dlResult = _downloadResult(result)
AA File "/opt/sickchill/sickchill/oldbeard/search.py", line 111, in snatchEpisode
AA self.success = search.snatchEpisode(search_result[0])
AA File "/opt/sickchill/sickchill/oldbeard/search_queue.py", line 174, in run
AA Traceback (most recent call last):
AA During handling of the above exception, another exception occurred:
AA AttributeError: module 'bencodepy' has no attribute 'decode_from_file'
AA bencodepy.decode_from_file(file_name)
AA File "/opt/sickchill/sickchill/providers/torrent/TorrentProvider.py", line 108, in _verify_download

# Fixed code
def _verify_download(self, file_name):
    try:
        bencodepy.bread(file_name)
    except bencodepy.BencodeDecodeError as e:
        logger.debug("Failed to validate torrent file: {0}".format(str(e)))
        logger.debug("Result is not a valid torrent file")
        return False
    return True
# Buggy code
def __call__(self, target, *args, **kwargs):
    @wraps(target)
    def wrapper(*args, **kwargs):
        try:
            result = target(*args, **kwargs)
        except self.catch as e:
            if self.image_api and not kwargs.get("lang"):
                if args[1].lang != "en":
                    logger.debug(
                        "Could not find the image on the indexer, re-trying to find it in english"
                    )
                    kwargs["lang"] = "en"
                    return wrapper(*args, **kwargs)

            logger.debug(
                "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                    error=str(e)
                )
            )
            result = self.default_return
        except RHTTPError as e:
            logger.debug(
                "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                    error=str(e)
                )
            )
            result = self.default_return

        return result

    wrapper.__doc__ = target.__doc__
    return wrapper


# Traceback (TypeError)
View Log:
AA TypeError: argument of type 'NoneType' is not iterable
AA if 'outputType' in out_dict:
AA File "/opt/sickchill/sickchill/views/api/webapi.py", line 105, in get
AA result = method(*self.path_args, **self.path_kwargs)
AA File "/opt/sickchill/lib3/tornado/web.py", line 1701, in _execute
AA Traceback (most recent call last):
AA HTTPServerRequest(protocol='https', host='home.xxx', method='GET', uri='/tv/api/xxx/?cmd=sb.searchtvdb&amp;name=Game&amp;lang=en', version='HTTP/1.0', remote_ip='10.10.10.1')
2020-09-12 05:01:41 ERROR :: WEBSERVER :: Uncaught exception GET /tv/api/xxx/?cmd=sb.searchtvdb&amp;name=Game&amp;lang=en (10.10.10.1)

View Error:
2020-09-12 05:01:41 Uncaught exception %s
%r

# Fixed code
def __call__(self, target, *args, **kwargs):
    @wraps(target)
    def wrapper(*args, **kwargs):
        try:
            result = target(*args, **kwargs)
        except self.catch as e:
            if self.image_api and not kwargs.get("lang"):
                if args[1].lang != "en":
                    logger.debug(
                        "Could not find the image on the indexer, re-trying to find it in english"
                    )
                    kwargs["lang"] = "en"
                    return wrapper(*args, **kwargs)

            logger.debug(
                "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                    error=str(e)
                )
            )
            logger.debug(traceback.format_exc())
            result = self.default_return
        except RHTTPError as e:
            logger.debug(
                "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                    error=str(e)
                )
            )
            logger.debug(traceback.format_exc())
            result = self.default_return

        return result

    wrapper.__doc__ = target.__doc__
    return wrapper
# Buggy code
def wrapper(*args, **kwargs):
    try:
        result = target(*args, **kwargs)
    except self.catch as e:
        if self.image_api and not kwargs.get("lang"):
            if args[1].lang != "en":
                logger.debug(
                    "Could not find the image on the indexer, re-trying to find it in english"
                )
                kwargs["lang"] = "en"
                return wrapper(*args, **kwargs)

        logger.debug(
            "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                error=str(e)
            )
        )
        result = self.default_return
    except RHTTPError as e:
        logger.debug(
            "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                error=str(e)
            )
        )
        result = self.default_return

    return result


# Traceback (TypeError)
View Log:
AA TypeError: argument of type 'NoneType' is not iterable
AA if 'outputType' in out_dict:
AA File "/opt/sickchill/sickchill/views/api/webapi.py", line 105, in get
AA result = method(*self.path_args, **self.path_kwargs)
AA File "/opt/sickchill/lib3/tornado/web.py", line 1701, in _execute
AA Traceback (most recent call last):
AA HTTPServerRequest(protocol='https', host='home.xxx', method='GET', uri='/tv/api/xxx/?cmd=sb.searchtvdb&amp;name=Game&amp;lang=en', version='HTTP/1.0', remote_ip='10.10.10.1')
2020-09-12 05:01:41 ERROR :: WEBSERVER :: Uncaught exception GET /tv/api/xxx/?cmd=sb.searchtvdb&amp;name=Game&amp;lang=en (10.10.10.1)

View Error:
2020-09-12 05:01:41 Uncaught exception %s
%r

# Fixed code
def wrapper(*args, **kwargs):
    try:
        result = target(*args, **kwargs)
    except self.catch as e:
        if self.image_api and not kwargs.get("lang"):
            if args[1].lang != "en":
                logger.debug(
                    "Could not find the image on the indexer, re-trying to find it in english"
                )
                kwargs["lang"] = "en"
                return wrapper(*args, **kwargs)

        logger.debug(
            "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                error=str(e)
            )
        )
        logger.debug(traceback.format_exc())
        result = self.default_return
    except RHTTPError as e:
        logger.debug(
            "Could not find item on the indexer: (Indexer probably doesn't have this item) [{error}]".format(
                error=str(e)
            )
        )
        logger.debug(traceback.format_exc())
        result = self.default_return

    return result
# Buggy code
def __init__(self):
    """Gets a list of most popular TV series from imdb"""

    self.base_url = "https://imdb.com"
    self.url = urljoin(self.base_url, "search/title")

    self.params = {
        "at": 0,
        "sort": "moviemeter",
        "title_type": "tv_series",
        "year": "{0},{1}".format(date.today().year - 1, date.today().year + 1),
    }

    self.session = helpers.make_session()


# Traceback (UnboundLocalError)
AA UnboundLocalError: local variable 'e' referenced before assignment
AA popular_shows=popular_shows, imdb_exception=e,
AA File "C:\SickChill\SickChill\sickchill\views\manage\add_shows.py", line 309, in popularShows
AA return function(**kwargs)
AA File "C:\SickChill\SickChill\sickchill\views\index.py", line 183, in async_call
AA result = self.fn(*self.args, **self.kwargs)
AA File "C:\SickChill\Python3\lib\concurrent\futures\thread.py", line 57, in run
AA value = future.result()
AA File "C:\SickChill\SickChill\lib3\tornado\gen.py", line 735, in run
AA results = yield self.async_call(method)
AA File "C:\SickChill\SickChill\sickchill\views\index.py", line 160, in get
AA yielded = self.gen.throw(*exc_info)  # type: ignore
AA File "C:\SickChill\SickChill\lib3\tornado\gen.py", line 742, in run
AA result = await result
AA File "C:\SickChill\SickChill\lib3\tornado\web.py", line 1703, in _execute
AA Traceback (most recent call last):
AA HTTPServerRequest(protocol='http', host='192.168.1.3:8081', method='GET', uri='/addShows/popularShows/', version='HTTP/1.1', remote_ip='192.168.1.2')
2020-09-10 15:56:01 ERROR :: WEBSERVER :: Uncaught exception GET /addShows/popularShows/ (192.168.1.2)
2020-09-10 15:56:01 WARNING :: WEBSERVER-ADDSHOWS_0 :: Could not get popular shows: list index out of range

# Fixed code
def __init__(self):
    """Gets a list of most popular TV series from imdb"""
    self.session = helpers.make_session()
    self.imdb = Imdb(session=self.session)
# Buggy code
def popularShows(self):
    """
    Fetches data from IMDB to show a list of popular shows.
    """
    t = PageTemplate(rh=self, filename="addShows_popularShows.mako")
    e = None

    try:
        popular_shows = imdb_popular.fetch_popular_shows()
    except Exception as e:
        logger.warning("Could not get popular shows: {0}".format(str(e)))
        popular_shows = None

    return t.render(
        title=_("Popular Shows"),
        header=_("Popular Shows"),
        popular_shows=popular_shows,
        imdb_exception=e,
        topmenu="home",
        controller="addShows",
        action="popularShows",
    )


# Traceback (UnboundLocalError)
AA UnboundLocalError: local variable 'e' referenced before assignment
AA popular_shows=popular_shows, imdb_exception=e,
AA File "C:\SickChill\SickChill\sickchill\views\manage\add_shows.py", line 309, in popularShows
AA return function(**kwargs)
AA File "C:\SickChill\SickChill\sickchill\views\index.py", line 183, in async_call
AA result = self.fn(*self.args, **self.kwargs)
AA File "C:\SickChill\Python3\lib\concurrent\futures\thread.py", line 57, in run
AA value = future.result()
AA File "C:\SickChill\SickChill\lib3\tornado\gen.py", line 735, in run
AA results = yield self.async_call(method)
AA File "C:\SickChill\SickChill\sickchill\views\index.py", line 160, in get
AA yielded = self.gen.throw(*exc_info)  # type: ignore
AA File "C:\SickChill\SickChill\lib3\tornado\gen.py", line 742, in run
AA result = await result
AA File "C:\SickChill\SickChill\lib3\tornado\web.py", line 1703, in _execute
AA Traceback (most recent call last):
AA HTTPServerRequest(protocol='http', host='192.168.1.3:8081', method='GET', uri='/addShows/popularShows/', version='HTTP/1.1', remote_ip='192.168.1.2')
2020-09-10 15:56:01 ERROR :: WEBSERVER :: Uncaught exception GET /addShows/popularShows/ (192.168.1.2)
2020-09-10 15:56:01 WARNING :: WEBSERVER-ADDSHOWS_0 :: Could not get popular shows: list index out of range

# Fixed code
def popularShows(self):
    """
    Fetches data from IMDB to show a list of popular shows.
    """
    t = PageTemplate(rh=self, filename="addShows_popularShows.mako")
    try:
        popular_shows = imdb_popular.fetch_popular_shows()
        imdb_exception = None
    except Exception as error:
        logger.warning("Could not get popular shows: {0}".format(str(error)))
        logger.debug(traceback.format_exc())
        popular_shows = None
        imdb_exception = error

    return t.render(
        title=_("Popular Shows"),
        header=_("Popular Shows"),
        popular_shows=popular_shows,
        imdb_exception=imdb_exception,
        topmenu="home",
        controller="addShows",
        action="popularShows",
    )
# Buggy code
def setup_gettext(language=None):
    languages = [language] if language else None
    if not [
        key
        for key in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")
        if key in os.environ
    ]:
        os.environ["LC_MESSAGES"] = "en_US.UTF-8"
    gt = gettext.translation("messages", locale_dir(), languages=languages)
    gt.install(names=["ngettext"])


# Traceback (FileNotFoundError)
Big-Mac:SickChill tony$ python3 SickChill.py
Traceback (most recent call last):
File "SickChill.py", line 14, in <module>
import sickchill.start
File "/Applications/SickChill/sickchill/__init__.py", line 1, in <module>
from .show.indexers import indexer, ShowIndexer
File "/Applications/SickChill/sickchill/show/indexers/__init__.py", line 1, in <module>
from .handler import ShowIndexer
File "/Applications/SickChill/sickchill/show/indexers/handler.py", line 3, in <module>
from sickchill import logger, settings
File "/Applications/SickChill/sickchill/logger.py", line 19, in <module>
from sickchill import settings
File "/Applications/SickChill/sickchill/settings.py", line 11, in <module>
from sickchill.oldbeard.common import SD
File "/Applications/SickChill/sickchill/oldbeard/common.py", line 16, in <module>
setup_gettext()
File "/Applications/SickChill/sickchill/init_helpers.py", line 27, in setup_gettext
gt = gettext.translation('messages', locale_dir(), languages=languages)
File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/gettext.py", line 588, in translation
raise FileNotFoundError(ENOENT,
FileNotFoundError: [Errno 2] No translation file found for domain: 'messages'

# Fixed code
def setup_gettext(language=None):
    languages = [language] if language else None
    if not [
        key
        for key in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG")
        if os.environ.get(key)
    ]:
        os.environ["LC_MESSAGES"] = "en_US.UTF-8"
    print(locale_dir())
    gt = gettext.translation(
        "messages", locale_dir(), languages=languages, fallback=True
    )
    gt.install(names=["ngettext"])
# Buggy code
def retryEpisode(self, show, season, episode, downCurQuality):
    # retrieve the episode object and fail if we can't get one
    ep_obj = self._getEpisode(show, season, episode)
    if isinstance(ep_obj, str):
        return json.dumps({"result": "failure"})

    # make a queue item for it and put it on the queue
    ep_queue_item = search_queue.FailedQueueItem(
        ep_obj.show, [ep_obj], bool(int(downCurQuality))
    )
    sickbeard.searchQueueScheduler.action.add_item(ep_queue_item)

    if not ep_queue_item.started and ep_queue_item.success is None:
        return json.dumps(
            {"result": "success"}
        )  # I Actually want to call it queued, because the search hasnt been started yet!
    if ep_queue_item.started and ep_queue_item.success is None:
        return json.dumps({"result": "success"})
    else:
        return json.dumps({"result": "failure"})


# Traceback (TypeError)
Thread-18 :: [6116245] Failed doing webui callback: Traceback (most recent call last):
File "C:\SickRage\sickbeard\webserve.py", line 285, in async_call
result = function(**kwargs)
TypeError: retryEpisode() takes exactly 5 arguments (4 given)

# Fixed code
def retryEpisode(self, show, season, episode, downCurQuality=0):
    # retrieve the episode object and fail if we can't get one
    ep_obj = self._getEpisode(show, season, episode)
    if isinstance(ep_obj, str):
        return json.dumps({"result": "failure"})

    # make a queue item for it and put it on the queue
    ep_queue_item = search_queue.FailedQueueItem(
        ep_obj.show, [ep_obj], bool(int(downCurQuality))
    )
    sickbeard.searchQueueScheduler.action.add_item(ep_queue_item)

    if not ep_queue_item.started and ep_queue_item.success is None:
        return json.dumps(
            {"result": "success"}
        )  # I Actually want to call it queued, because the search hasnt been started yet!
    if ep_queue_item.started and ep_queue_item.success is None:
        return json.dumps({"result": "success"})
    else:
        return json.dumps({"result": "failure"})
# Buggy code
def locals_import_from(node, locals_):
    # Don't add future imports to locals.
    if node.modname == "__future__":
        return

    # Sort the list for having the locals ordered by their first
    # appearance.
    def sort_locals(my_list):
        my_list.sort(key=lambda node: node.fromlineno)

    for name, asname in node.names:
        if name == "*":
            try:
                imported = util.do_import_module(node, node.modname)
            except exceptions.AstroidBuildingError:
                continue
            for name in imported.wildcard_import_names():
                locals_[name].append(node)
                sort_locals(locals_[name])
        else:
            locals_[asname or name].append(node)
            sort_locals(locals_[asname or name])


# Traceback (AssertionError)
FAIL: test_builtin_fromlineno_missing (unittest_nodes.ArgumentsNodeTC)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/code/astroid/.tox/py34/lib/python3.4/site-packages/astroid/tests/unittest_nodes.py", line 479, in test_builtin_fromlineno_missing
self.assertEqual(new.args.fromlineno, 0)
AssertionError: 1 != 0

# Fixed code
def locals_import_from(node, locals_):
    # Don't add future imports to locals.
    if node.modname == "__future__":
        return

    # Sort the list for having the locals ordered by their first
    # appearance.
    def sort_locals(my_list):
        my_list.sort(key=lambda node: node.fromlineno or 0)

    for name, asname in node.names:
        if name == "*":
            try:
                imported = util.do_import_module(node, node.modname)
            except exceptions.AstroidBuildingError:
                continue
            for name in imported.wildcard_import_names():
                locals_[name].append(node)
                sort_locals(locals_[name])
        else:
            locals_[asname or name].append(node)
            sort_locals(locals_[asname or name])
# Buggy code
def sort_locals(my_list):
    my_list.sort(key=lambda node: node.fromlineno)


# Traceback (AssertionError)
FAIL: test_builtin_fromlineno_missing (unittest_nodes.ArgumentsNodeTC)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/code/astroid/.tox/py34/lib/python3.4/site-packages/astroid/tests/unittest_nodes.py", line 479, in test_builtin_fromlineno_missing
self.assertEqual(new.args.fromlineno, 0)
AssertionError: 1 != 0

# Fixed code
def sort_locals(my_list):
    my_list.sort(key=lambda node: node.fromlineno or 0)
# Buggy code
def fromlineno(self):
    if self.lineno is None:
        return self._fixed_source_line()
    else:
        return self.lineno


# Traceback (AssertionError)
FAIL: test_builtin_fromlineno_missing (unittest_nodes.ArgumentsNodeTC)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/code/astroid/.tox/py34/lib/python3.4/site-packages/astroid/tests/unittest_nodes.py", line 479, in test_builtin_fromlineno_missing
self.assertEqual(new.args.fromlineno, 0)
AssertionError: 1 != 0

# Fixed code
def fromlineno(self):
    return self.lineno
# Buggy code
def tolineno(self):
    if not self._astroid_fields:
        # can't have children
        lastchild = None
    else:
        lastchild = self.last_child()
    if lastchild is None:
        return self.fromlineno
    else:
        return lastchild.tolineno

    # TODO / FIXME:
    assert self.fromlineno is not None, self
    assert self.tolineno is not None, self


# Traceback (AssertionError)
FAIL: test_builtin_fromlineno_missing (unittest_nodes.ArgumentsNodeTC)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/code/astroid/.tox/py34/lib/python3.4/site-packages/astroid/tests/unittest_nodes.py", line 479, in test_builtin_fromlineno_missing
self.assertEqual(new.args.fromlineno, 0)
AssertionError: 1 != 0

# Fixed code
def tolineno(self):
    if not self._astroid_fields:
        # can't have children
        lastchild = None
    else:
        lastchild = self.last_child()
    if lastchild is None:
        return self.fromlineno
    else:
        return lastchild.tolineno
# Buggy code
def fromlineno(self):
    lineno = super(Arguments, self).fromlineno
    return max(lineno, self.parent.fromlineno or 0)


# Traceback (AssertionError)
FAIL: test_builtin_fromlineno_missing (unittest_nodes.ArgumentsNodeTC)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/code/astroid/.tox/py34/lib/python3.4/site-packages/astroid/tests/unittest_nodes.py", line 479, in test_builtin_fromlineno_missing
self.assertEqual(new.args.fromlineno, 0)
AssertionError: 1 != 0

# Fixed code
def fromlineno(self):
    # Let the Function's lineno be the lineno for this.
    if self.parent.fromlineno:
        return self.parent.fromlineno

    return super(Arguments, self).fromlineno
# Buggy code
def const_factory(value):
    """return an astroid node for a python value"""
    # XXX we should probably be stricter here and only consider stuff in
    # CONST_CLS or do better treatment: in case where value is not in CONST_CLS,
    # we should rather recall the builder on this value than returning an empty
    # node (another option being that const_factory shouldn't be called with something
    # not in CONST_CLS)
    assert not isinstance(value, bases.NodeNG)
    try:
        return CONST_CLS[value.__class__](value)
    except (KeyError, AttributeError):
        node = EmptyNode()
        node.object = value
        return node


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def const_factory(value):
    """return an astroid node for a python value"""
    # XXX we should probably be stricter here and only consider stuff in
    # CONST_CLS or do better treatment: in case where value is not in CONST_CLS,
    # we should rather recall the builder on this value than returning an empty
    # node (another option being that const_factory shouldn't be called with something
    # not in CONST_CLS)
    assert not isinstance(value, bases.NodeNG)
    try:
        return CONST_CLS[value.__class__](value)
    except (KeyError, AttributeError) as exc:
        node = EmptyNode()
        node.object = value
        return node
# Buggy code
def for_assigned_stmts(self, node, context=None, asspath=None):
    if asspath is None:
        for lst in self.iter.infer(context):
            if isinstance(lst, (nodes.Tuple, nodes.List)):
                for item in lst.elts:
                    yield item
    else:
        for inferred in _resolve_looppart(self.iter.infer(context), asspath, context):
            yield inferred


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def for_assigned_stmts(self, node=None, context=None, asspath=None):
    if asspath is None:
        for lst in self.iter.infer(context):
            if isinstance(lst, (nodes.Tuple, nodes.List)):
                for item in lst.elts:
                    yield item
    else:
        for inferred in _resolve_looppart(self.iter.infer(context), asspath, context):
            yield inferred
# Buggy code
def assend_assigned_stmts(self, context=None):
    return self.parent.assigned_stmts(self, context=context)


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def assend_assigned_stmts(self, node=None, context=None, asspath=None):
    return self.parent.assigned_stmts(node=self, context=context)
# Buggy code
def arguments_assigned_stmts(self, node, context, asspath=None):
    if context.callcontext:
        # reset call context/name
        callcontext = context.callcontext
        context = contextmod.copy_context(context)
        context.callcontext = None
        args = arguments.CallSite(callcontext)
        return args.infer_argument(self.parent, node.name, context)
    return _arguments_infer_argname(self, node.name, context)


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def arguments_assigned_stmts(self, node=None, context=None, asspath=None):
    if context.callcontext:
        # reset call context/name
        callcontext = context.callcontext
        context = contextmod.copy_context(context)
        context.callcontext = None
        args = arguments.CallSite(callcontext)
        return args.infer_argument(self.parent, node.name, context)
    return _arguments_infer_argname(self, node.name, context)
# Buggy code
def assign_assigned_stmts(self, node, context=None, asspath=None):
    if not asspath:
        yield self.value
        return
    for inferred in _resolve_asspart(self.value.infer(context), asspath, context):
        yield inferred


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def assign_assigned_stmts(self, node=None, context=None, asspath=None):
    if not asspath:
        yield self.value
        return
    for inferred in _resolve_asspart(self.value.infer(context), asspath, context):
        yield inferred
# Buggy code
def excepthandler_assigned_stmts(self, node, context=None, asspath=None):
    for assigned in node_classes.unpack_infer(self.type):
        if isinstance(assigned, nodes.ClassDef):
            assigned = bases.Instance(assigned)
        yield assigned


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def excepthandler_assigned_stmts(self, node=None, context=None, asspath=None):
    for assigned in node_classes.unpack_infer(self.type):
        if isinstance(assigned, nodes.ClassDef):
            assigned = bases.Instance(assigned)
        yield assigned
# Buggy code
def with_assigned_stmts(self, node, context=None, asspath=None):
    if asspath is None:
        for _, vars in self.items:
            if vars is None:
                continue
            for lst in vars.infer(context):
                if isinstance(lst, (nodes.Tuple, nodes.List)):
                    for item in lst.nodes:
                        yield item


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def with_assigned_stmts(self, node=None, context=None, asspath=None):
    if asspath is None:
        for _, vars in self.items:
            if vars is None:
                continue
            for lst in vars.infer(context):
                if isinstance(lst, (nodes.Tuple, nodes.List)):
                    for item in lst.nodes:
                        yield item
# Buggy code
def mulass_assigned_stmts(self, nodes, node=None, context=None, asspath=None):
    if asspath is None:
        asspath = []
    asspath.insert(0, self.elts.index(node))
    return self.parent.assigned_stmts(self, context, asspath)


# Traceback (TypeError)
#!python

Traceback (most recent call last):
File "a.py", line 5, in <module>
f.wildcard_import_names()
File "astroid\scoped_nodes.py", line 471, in wildcard_import_names
explicit = next(all.assigned_stmts())
TypeError: mulass_assigned_stmts() takes at least 2 arguments (1 given)

# Fixed code
def mulass_assigned_stmts(self, nodes, node=None, context=None, asspath=None):
    if asspath is None:
        asspath = []

    try:
        index = self.elts.index(node)
    except ValueError:
        util.reraise(
            exceptions.InferenceError(
                "Tried to retrieve a node {node!r} which does not exist",
                node=self,
                assign_path=asspath,
                context=context,
            )
        )

    asspath.insert(0, index)
    return self.parent.assigned_stmts(node=self, context=context, asspath=asspath)
# Buggy code
def __getattribute__(self, name):
    if name == "next":
        raise AttributeError("next method should not be called")
    if name.startswith("__") and name.endswith("__"):
        return super(_Yes, self).__getattribute__(name)
    return self


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib64/python3.5/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib64/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/__main__.py", line 3, in <module>
pylint.run_pylint()
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/__init__.py", line 23, in run_pylint
Run(sys.argv[1:])
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 1315, in __init__
linter.check(args)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 734, in check
self._do_check(files_or_modules)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 865, in _do_check
self.check_astroid_module(ast_node, walker, rawcheckers, tokencheckers)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 945, in check_astroid_module
walker.walk(ast_node)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/utils.py", line 938, in walk
self.walk(child)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/utils.py", line 938, in walk
self.walk(child)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/utils.py", line 935, in walk
cb(astroid)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/checkers/base.py", line 1946, in visit_assign
if var_type == astroid.YES or var_type.as_string() == 'None':
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/bases.py", line 611, in as_string
return to_code(self)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/as_string.py", line 79, in __call__
return node.accept(self)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/bases.py", line 395, in accept
return func(self)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/as_string.py", line 341, in visit_list
return '[%s]' % ', '.join([child.accept(self) for child in node.elts])
TypeError: sequence item 0: expected str instance, _Yes found

# Fixed code
def __getattribute__(self, name):
    if name == "next":
        raise AttributeError("next method should not be called")
    if name.startswith("__") and name.endswith("__"):
        return super(_Yes, self).__getattribute__(name)
    if name == "accept":
        return super(_Yes, self).__getattribute__(name)
    return self
# Buggy code
def __getattribute__(self, name):
    if name == "next":
        raise AttributeError("next method should not be called")
    if name.startswith("__") and name.endswith("__"):
        return object.__getattribute__(self, name)
    return self


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib64/python3.5/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib64/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/__main__.py", line 3, in <module>
pylint.run_pylint()
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/__init__.py", line 23, in run_pylint
Run(sys.argv[1:])
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 1315, in __init__
linter.check(args)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 734, in check
self._do_check(files_or_modules)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 865, in _do_check
self.check_astroid_module(ast_node, walker, rawcheckers, tokencheckers)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/lint.py", line 945, in check_astroid_module
walker.walk(ast_node)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/utils.py", line 938, in walk
self.walk(child)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/utils.py", line 938, in walk
self.walk(child)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/utils.py", line 935, in walk
cb(astroid)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/pylint/checkers/base.py", line 1946, in visit_assign
if var_type == astroid.YES or var_type.as_string() == 'None':
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/bases.py", line 611, in as_string
return to_code(self)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/as_string.py", line 79, in __call__
return node.accept(self)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/bases.py", line 395, in accept
return func(self)
File "/home/florian/proj/qutebrowser/git/.tox/pylint/lib/python3.5/site-packages/astroid/as_string.py", line 341, in visit_list
return '[%s]' % ', '.join([child.accept(self) for child in node.elts])
TypeError: sequence item 0: expected str instance, _Yes found

# Fixed code
def __getattribute__(self, name):
    if name == "next":
        raise AttributeError("next method should not be called")
    if name.startswith("__") and name.endswith("__"):
        return object.__getattribute__(self, name)
    if name == "accept":
        return object.__getattribute__(self, name)
    return self
# Buggy code
def getattr(self, name, context=None):
    if name == "im_func":
        return [self._proxied]
    return super(UnboundMethod, self).getattr(name, context)


# Traceback (AttributeError)
#!python

Traceback (most recent call last):
File "C:\Python34\Scripts\pylint-script.py", line 9, in <module>
load_entry_point('pylint==1.4.3', 'console_scripts', 'pylint')()
File "e:\projects\repos\pylint\pylint\__init__.py", line 23, in run_pylint
Run(sys.argv[1:])
File "e:\projects\repos\pylint\pylint\lint.py", line 1343, in __init__
linter.check(args)
File "e:\projects\repos\pylint\pylint\lint.py", line 754, in check
self._do_check(files_or_modules)
File "e:\projects\repos\pylint\pylint\lint.py", line 877, in _do_check
self.check_astroid_module(ast_node, walker, rawcheckers, tokencheckers)
File "e:\projects\repos\pylint\pylint\lint.py", line 958, in check_astroid_module
walker.walk(ast_node)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 874, in walk
cb(astroid)
File "e:\projects\repos\pylint\pylint\checkers\typecheck.py", line 652, in visit_with
infered.getattr('__enter__')
File "e:\projects\repos\astroid-1\astroid\bases.py", line 264, in getattr
return super(UnboundMethod, self).getattr(name, context)
AttributeError: 'super' object has no attribute 'getattr'

# Fixed code
def getattr(self, name, context=None):
    if name == "im_func":
        return [self._proxied]
    return self._proxied.getattr(name, context)
# Buggy code
def igetattr(self, name, context=None):
    if name == "im_func":
        return iter((self._proxied,))
    return super(UnboundMethod, self).igetattr(name, context)


# Traceback (AttributeError)
#!python

Traceback (most recent call last):
File "C:\Python34\Scripts\pylint-script.py", line 9, in <module>
load_entry_point('pylint==1.4.3', 'console_scripts', 'pylint')()
File "e:\projects\repos\pylint\pylint\__init__.py", line 23, in run_pylint
Run(sys.argv[1:])
File "e:\projects\repos\pylint\pylint\lint.py", line 1343, in __init__
linter.check(args)
File "e:\projects\repos\pylint\pylint\lint.py", line 754, in check
self._do_check(files_or_modules)
File "e:\projects\repos\pylint\pylint\lint.py", line 877, in _do_check
self.check_astroid_module(ast_node, walker, rawcheckers, tokencheckers)
File "e:\projects\repos\pylint\pylint\lint.py", line 958, in check_astroid_module
walker.walk(ast_node)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 877, in walk
self.walk(child)
File "e:\projects\repos\pylint\pylint\utils.py", line 874, in walk
cb(astroid)
File "e:\projects\repos\pylint\pylint\checkers\typecheck.py", line 652, in visit_with
infered.getattr('__enter__')
File "e:\projects\repos\astroid-1\astroid\bases.py", line 264, in getattr
return super(UnboundMethod, self).getattr(name, context)
AttributeError: 'super' object has no attribute 'getattr'

# Fixed code
def igetattr(self, name, context=None):
    if name == "im_func":
        return iter((self._proxied,))
    return self._proxied.igetattr(name, context)
# Buggy code
def configure_parser(sub_parsers):
    config_parser = sub_parsers.add_parser(
        "config",
        formatter_class=RawDescriptionHelpFormatter,
        description=config_description,
        help=config_description,
        epilog=config_example,
    )
    config_subparser = config_parser.add_subparsers()
    configure_vars_parser(config_subparser)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/USERNAME/miniconda3/lib/python3.7/site-packages/conda/exceptions.py", line 1078, in __call__
return func(*args, **kwargs)
File "/home/USERNAME/miniconda3/lib/python3.7/site-packages/conda_env/cli/main.py", line 76, in do_call
relative_mod, func_name = args.func.rsplit('.', 1)
AttributeError: 'Namespace' object has no attribute 'func'

# Fixed code
def configure_parser(sub_parsers):
    config_parser = sub_parsers.add_parser(
        "config",
        formatter_class=RawDescriptionHelpFormatter,
        description=config_description,
        help=config_description,
        epilog=config_example,
    )
    config_parser.set_defaults(func=".main_config.execute")
    config_subparser = config_parser.add_subparsers()
    configure_vars_parser(config_subparser)
# Buggy code
def __str__(self):
    try:
        return text_type(self.message % self._kwargs)
    except TypeError:
        # TypeError: not enough arguments for format string
        debug_message = "\n".join(
            (
                "class: " + self.__class__.__name__,
                "message:",
                self.message,
                "kwargs:",
                text_type(self._kwargs),
            )
        )
        sys.stderr.write(debug_message)
        raise


# Traceback (ValueError)
$ source ~/anaconda/bin/activate
Traceback (most recent call last):
File "/home/ondrej/anaconda/lib/python2.7/site-packages/conda/gateways/logging.py", line 64, in emit
msg = self.format(record)
File "/home/ondrej/anaconda/lib/python2.7/logging/__init__.py", line 734, in format
return fmt.format(record)
File "/home/ondrej/anaconda/lib/python2.7/logging/__init__.py", line 465, in format
record.message = record.getMessage()
File "/home/ondrej/anaconda/lib/python2.7/logging/__init__.py", line 329, in getMessage
msg = msg % self.args
File "/home/ondrej/anaconda/lib/python2.7/site-packages/conda/__init__.py", line 43, in __repr__
return '%s: %s' % (self.__class__.__name__, text_type(self))
File "/home/ondrej/anaconda/lib/python2.7/site-packages/conda/__init__.py", line 47, in __str__
return text_type(self.message % self._kwargs)
ValueError: unsupported format character '{' (0x7b) at index 458
Logged from file exceptions.py, line 770
$ echo $ZSH_VERSION
5.3.1

# Fixed code
def __str__(self):
    try:
        return text_type(self.message % self._kwargs)
    except:
        debug_message = "\n".join(
            (
                "class: " + self.__class__.__name__,
                "message:",
                self.message,
                "kwargs:",
                text_type(self._kwargs),
                "",
            )
        )
        sys.stderr.write(debug_message)
        raise