gurudesh/pytracebugs huggingface dataset:
# Buggy code
def from_url(cls, url: str) -> Optional["YukicoderProblem"]:
    # example: https://yukicoder.me/problems/no/499
    # example: http://yukicoder.me/problems/1476
    result = urllib.parse.urlparse(url)
    dirname, basename = posixpath.split(utils.normpath(result.path))
    if result.scheme in ("", "http", "https") and result.netloc == "yukicoder.me":
        n = None  # type: Optional[int]
        try:
            n = int(basename)
        except ValueError:
            pass
        if n is not None:
            if dirname == "/problems/no":
                return cls(problem_no=int(n))
            if dirname == "/problems":
                return cls(problem_id=int(n))
        return cls()
    return None


# Traceback (AssertionError)
dispatch.problem_from_url("https://yukicoder.me/contests/241/")  # Assert raises
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ryo/workspace/github/online-judge-tools/onlinejudge/dispatch.py", line 53, in problem_from_url
problem = cls.from_url(url)
File "/home/ryo/workspace/github/online-judge-tools/onlinejudge/service/yukicoder.py", line 359, in from_url
return cls()
File "/home/ryo/workspace/github/online-judge-tools/onlinejudge/service/yukicoder.py", line 238, in __init__
assert problem_no or problem_id
AssertionError
dispatch.problem_from_url("https://yahoo.co.jp")  # return None

# Fixed code
def from_url(cls, url: str) -> Optional["YukicoderProblem"]:
    # example: https://yukicoder.me/problems/no/499
    # example: http://yukicoder.me/problems/1476
    result = urllib.parse.urlparse(url)
    dirname, basename = posixpath.split(utils.normpath(result.path))
    if result.scheme in ("", "http", "https") and result.netloc == "yukicoder.me":
        n = None  # type: Optional[int]
        try:
            n = int(basename)
        except ValueError:
            pass
        if n is not None:
            if dirname == "/problems/no":
                return cls(problem_no=n)
            if dirname == "/problems":
                return cls(problem_id=n)
    return None
# Buggy code
def _AtCoderProblemContentPartial_from_row(tr: bs4.Tag):
    tds = tr.find_all("td")
    assert 4 <= len(tds) <= 5
    path = tds[1].find("a")["href"]
    problem = AtCoderProblem.from_url("https://atcoder.jp" + path)
    assert problem is not None
    alphabet = tds[0].text
    name = tds[1].text
    time_limit_msec = int(float(utils.remove_suffix(tds[2].text, " sec")) * 1000)
    memory_limit_byte = int(
        float(utils.remove_suffix(tds[3].text, " MB")) * 1000 * 1000
    )  # TODO: confirm this is MB truly, not MiB
    if len(tds) == 5:
        assert tds[4].text.strip() in ("", "Submit", "提出")

    self = AtCoderProblemContentPartial(
        alphabet, memory_limit_byte, name, problem, time_limit_msec
    )
    problem._cached_content = self
    return self


# Traceback (AssertionError)
$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import onlinejudge
onlinejudge.service.atcoder.AtCoderContest.from_url('https://atcoder.jp/contests/joi2019ho/tasks').list_problems()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/user/.local/lib/python3.6/site-packages/onlinejudge/service/atcoder.py", line 287, in list_problems
return [AtCoderProblem._from_table_row(tr) for tr in tbody.find_all('tr')]
File "/home/user/.local/lib/python3.6/site-packages/onlinejudge/service/atcoder.py", line 287, in <listcomp>
return [AtCoderProblem._from_table_row(tr) for tr in tbody.find_all('tr')]
File "/home/user/.local/lib/python3.6/site-packages/onlinejudge/service/atcoder.py", line 535, in _from_table_row
return _AtCoderProblemContentPartial_from_row(tr).problem
File "/home/user/.local/lib/python3.6/site-packages/onlinejudge/service/atcoder.py", line 364, in _AtCoderProblemContentPartial_from_row
time_limit_msec = int(float(utils.remove_suffix(tds[2].text, ' sec')) * 1000)
File "/home/user/.local/lib/python3.6/site-packages/onlinejudge/_implementation/utils.py", line 225, in remove_suffix
assert s.endswith(suffix)
AssertionError


# Fixed code
def _AtCoderProblemContentPartial_from_row(tr: bs4.Tag):
    tds = tr.find_all("td")
    assert 4 <= len(tds) <= 5
    path = tds[1].find("a")["href"]
    problem = AtCoderProblem.from_url("https://atcoder.jp" + path)
    assert problem is not None
    alphabet = tds[0].text
    name = tds[1].text
    if tds[2].text.endswith(" msec"):
        time_limit_msec = int(utils.remove_suffix(tds[2].text, " msec"))
    elif tds[2].text.endswith(" sec"):
        time_limit_msec = int(float(utils.remove_suffix(tds[2].text, " sec")) * 1000)
    else:
        assert False
    memory_limit_byte = int(
        float(utils.remove_suffix(tds[3].text, " MB")) * 1000 * 1000
    )  # TODO: confirm this is MB truly, not MiB
    if len(tds) == 5:
        assert tds[4].text.strip() in ("", "Submit", "提出")

    self = AtCoderProblemContentPartial(
        alphabet, memory_limit_byte, name, problem, time_limit_msec
    )
    problem._cached_content = self
    return self
# Buggy code
def _load_details(self, session: Optional[requests.Session] = None, lang: str = "en"):
    assert lang in ("en", "ja")
    session = session or utils.get_default_session()
    resp = _request("GET", self.get_url(type="beta", lang=lang), session=session)
    soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding), utils.html_parser)

    contest_name, _, _ = soup.find("title").text.rpartition(" - ")
    contest_duration = soup.find("small", class_="contest-duration")
    self._start_time, end_time = [
        self._parse_start_time(a["href"]) for a in contest_duration.find_all("a")
    ]
    self._duration = end_time - self._start_time
    if lang == "en":
        self._contest_name_en = contest_name
    elif lang == "ja":
        self._contest_name_ja = contest_name
    else:
        assert False
    _, _, self._can_participate = soup.find(
        "span", text=re.compile(r"^(Can Participate|参加対象): ")
    ).text.partition(": ")
    _, _, self._rated_range = soup.find(
        "span", text=re.compile(r"^(Rated Range|Rated対象): ")
    ).text.partition(": ")
    penalty_text = soup.find("span", text=re.compile(r"^(Penalty|ペナルティ): ")).text
    m = re.match(r"(Penalty|ペナルティ): (\d+)( minutes|分)", penalty_text)
    assert m
    self._penalty = datetime.timedelta(minutes=int(m.group(2)))


# Traceback (AssertionError)
$ python3 -c 'from onlinejudge.service.atcoder import * ; AtCoderContest.from_url("https://atcoder.jp/contests/chokudai_S002").get_name()'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/user/GitHub/online-judge-tools/onlinejudge/service/atcoder.py", line 261, in get_name
self._load_details(lang='en', session=session)
File "/home/user/GitHub/online-judge-tools/onlinejudge/service/atcoder.py", line 255, in _load_details
assert m
AssertionError

# Fixed code
def _load_details(self, session: Optional[requests.Session] = None, lang: str = "en"):
    assert lang in ("en", "ja")
    session = session or utils.get_default_session()
    resp = _request("GET", self.get_url(type="beta", lang=lang), session=session)
    soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding), utils.html_parser)

    contest_name, _, _ = soup.find("title").text.rpartition(" - ")
    contest_duration = soup.find("small", class_="contest-duration")
    self._start_time, end_time = [
        self._parse_start_time(a["href"]) for a in contest_duration.find_all("a")
    ]
    self._duration = end_time - self._start_time
    if lang == "en":
        self._contest_name_en = contest_name
    elif lang == "ja":
        self._contest_name_ja = contest_name
    else:
        assert False
    _, _, self._can_participate = soup.find(
        "span", text=re.compile(r"^(Can Participate|参加対象): ")
    ).text.partition(": ")
    _, _, self._rated_range = soup.find(
        "span", text=re.compile(r"^(Rated Range|Rated対象): ")
    ).text.partition(": ")
    penalty_text = soup.find("span", text=re.compile(r"^(Penalty|ペナルティ): ")).text
    m = re.match(r"(Penalty|ペナルティ): (\d+)( minutes?|分)", penalty_text)
    assert m
    self._penalty = datetime.timedelta(minutes=int(m.group(2)))
# Buggy code
def download_sample_cases(
    self, session: Optional[requests.Session] = None
) -> List[TestCase]:
    session = session or utils.new_default_session()
    # get
    resp = utils.request("GET", self.get_url(), session=session)
    # parse
    soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding), utils.html_parser)
    samples = onlinejudge._implementation.testcase_zipper.SampleZipper()
    for pre in soup.find_all("pre"):
        log.debug("pre: %s", str(pre))
        it = self._parse_sample_tag(pre)
        if it is not None:
            data, name = it
            samples.add(data.encode(), name)
    return samples.get()


# Traceback (AttributeError)
kaito@PC:~/procon/procon/yukicoder/183/d$ oj dl https://yukicoder.me/problems/no/649
[x] problem recognized: <onlinejudge.service.yukicoder.YukicoderProblem object at 0x7f3e9ab14eb8>: https://yukicoder.me/problems/no/649
[x] load cookie from: /home/kaito/.local/share/online-judge-tools/cookie.jar
[x] GET: https://yukicoder.me/problems/no/649
[x] 200 OK
Traceback (most recent call last):
File "/home/kaito/.local/bin/oj", line 7, in <module>
onlinejudge.implementation.main.main(args=sys.argv[1:])
File "/home/kaito/.local/lib/python3.6/site-packages/onlinejudge/implementation/main.py", line 318, in main
run_program(namespace, parser=parser)
File "/home/kaito/.local/lib/python3.6/site-packages/onlinejudge/implementation/main.py", line 287, in run_program
download(args)
File "/home/kaito/.local/lib/python3.6/site-packages/onlinejudge/implementation/command/download.py", line 53, in download
samples = problem.download_sample_cases(session=sess)  # type: ignore
File "/home/kaito/.local/lib/python3.6/site-packages/onlinejudge/service/yukicoder.py", line 275, in download_sample_cases
it = self._parse_sample_tag(pre)
File "/home/kaito/.local/lib/python3.6/site-packages/onlinejudge/service/yukicoder.py", line 312, in _parse_sample_tag
if prv.name == 'h6' and tag.parent.name == 'div' and tag.parent['class'] == ['paragraph'] and pprv.name == 'h5':
AttributeError: 'NoneType' object has no attribute 'name'

# Fixed code
def download_sample_cases(
    self, session: Optional[requests.Session] = None
) -> List[TestCase]:
    session = session or utils.new_default_session()
    # get
    resp = utils.request("GET", self.get_url(), session=session)
    # parse
    soup = bs4.BeautifulSoup(resp.content.decode(resp.encoding), utils.html_parser)
    samples = onlinejudge._implementation.testcase_zipper.SampleZipper()
    for pre in soup.select(".sample pre"):
        log.debug("pre: %s", str(pre))
        it = self._parse_sample_tag(pre)
        if it is not None:
            data, name = it
            samples.add(data.encode(), name)
    return samples.get()
# Buggy code
def __init__(self, base_path, home_path=Path.home(), apps=None, input_enabled=True):
    self.base_path = base_path
    self.home_path = home_path
    self.dot_briefcase_path = home_path / ".briefcase"

    self.global_config = None
    self.apps = {} if apps is None else apps

    # Some details about the host machine
    self.host_arch = platform.machine()
    self.host_os = platform.system()

    # External service APIs.
    # These are abstracted to enable testing without patching.
    self.cookiecutter = cookiecutter
    self.requests = requests
    self.input = Console(enabled=input_enabled)
    self.os = os
    self.sys = sys
    self.shutil = shutil
    self.subprocess = Subprocess(self)

    # The internal Briefcase integrations API.
    self.integrations = integrations


# Traceback (ImportError)
(beeware-dev) osboxes@osboxes:~/beeware-tutorial/helloworld$ briefcase run

[helloworld] Starting app...

Traceback (most recent call last):
File "/tmp/.mount_Hello_63m7qR/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/tmp/.mount_Hello_63m7qR/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/tmp/.mount_Hello_63m7qR/usr/app/helloworld/__main__.py", line 4, in <module>
main().main_loop()
File "/tmp/.mount_Hello_63m7qR/usr/app/helloworld/app.py", line 40, in main
return HelloWorld()
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga/app.py", line 208, in __init__
self.factory = get_platform_factory(factory)
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga/platform.py", line 39, in get_platform_factory
from toga_gtk import factory
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga_gtk/factory.py", line 1, in <module>
from .app import App, DocumentApp, MainWindow
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga_gtk/app.py", line 8, in <module>
import gbulb
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gbulb/__init__.py", line 1, in <module>
from .glib_events import *
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gbulb/glib_events.py", line 12, in <module>
from gi.repository import GLib, Gio
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gi/__init__.py", line 42, in <module>
from . import _gi
ImportError: libffi.so.6: cannot open shared object file: No such file or directory

Unable to start app helloworld.

# Fixed code
def __init__(self, base_path, home_path=Path.home(), apps=None, input_enabled=True):
    self.base_path = base_path
    self.home_path = home_path
    self.dot_briefcase_path = home_path / ".briefcase"

    self.global_config = None
    self.apps = {} if apps is None else apps
    self._path_index = {}

    # Some details about the host machine
    self.host_arch = platform.machine()
    self.host_os = platform.system()

    # External service APIs.
    # These are abstracted to enable testing without patching.
    self.cookiecutter = cookiecutter
    self.requests = requests
    self.input = Console(enabled=input_enabled)
    self.os = os
    self.sys = sys
    self.shutil = shutil
    self.subprocess = Subprocess(self)

    # The internal Briefcase integrations API.
    self.integrations = integrations
# Buggy code
def __init__(self, *args, **options):
    super().__init__(*args, **options)
    self._path_index = {}
    self._s3 = None


# Traceback (ImportError)
(beeware-dev) osboxes@osboxes:~/beeware-tutorial/helloworld$ briefcase run

[helloworld] Starting app...

Traceback (most recent call last):
File "/tmp/.mount_Hello_63m7qR/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/tmp/.mount_Hello_63m7qR/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/tmp/.mount_Hello_63m7qR/usr/app/helloworld/__main__.py", line 4, in <module>
main().main_loop()
File "/tmp/.mount_Hello_63m7qR/usr/app/helloworld/app.py", line 40, in main
return HelloWorld()
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga/app.py", line 208, in __init__
self.factory = get_platform_factory(factory)
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga/platform.py", line 39, in get_platform_factory
from toga_gtk import factory
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga_gtk/factory.py", line 1, in <module>
from .app import App, DocumentApp, MainWindow
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga_gtk/app.py", line 8, in <module>
import gbulb
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gbulb/__init__.py", line 1, in <module>
from .glib_events import *
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gbulb/glib_events.py", line 12, in <module>
from gi.repository import GLib, Gio
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gi/__init__.py", line 42, in <module>
from . import _gi
ImportError: libffi.so.6: cannot open shared object file: No such file or directory

Unable to start app helloworld.

# Fixed code
def __init__(self, *args, **options):
    super().__init__(*args, **options)
    self._s3 = None
# Buggy code
def verify_tools(self):
    super().verify_tools()

    try:
        print()
        print("Ensure we have the linuxdeploy AppImage...")
        self.linuxdeploy_appimage = self.download_url(
            url=self.linuxdeploy_download_url,
            download_path=self.dot_briefcase_path / "tools",
        )
        self.os.chmod(str(self.linuxdeploy_appimage), 0o755)
    except requests_exceptions.ConnectionError:
        raise NetworkFailure("downloading linuxdeploy AppImage")


# Traceback (ImportError)
(beeware-dev) osboxes@osboxes:~/beeware-tutorial/helloworld$ briefcase run

[helloworld] Starting app...

Traceback (most recent call last):
File "/tmp/.mount_Hello_63m7qR/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/tmp/.mount_Hello_63m7qR/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/tmp/.mount_Hello_63m7qR/usr/app/helloworld/__main__.py", line 4, in <module>
main().main_loop()
File "/tmp/.mount_Hello_63m7qR/usr/app/helloworld/app.py", line 40, in main
return HelloWorld()
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga/app.py", line 208, in __init__
self.factory = get_platform_factory(factory)
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga/platform.py", line 39, in get_platform_factory
from toga_gtk import factory
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga_gtk/factory.py", line 1, in <module>
from .app import App, DocumentApp, MainWindow
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/toga_gtk/app.py", line 8, in <module>
import gbulb
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gbulb/__init__.py", line 1, in <module>
from .glib_events import *
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gbulb/glib_events.py", line 12, in <module>
from gi.repository import GLib, Gio
File "/tmp/.mount_Hello_63m7qR/usr/app_packages/gi/__init__.py", line 42, in <module>
from . import _gi
ImportError: libffi.so.6: cannot open shared object file: No such file or directory

Unable to start app helloworld.

# Fixed code
def verify_tools(self):
    super().verify_tools()
    self.linuxdeploy_appimage_path = verify_linuxdeploy(self)
# Buggy code
def infer_temperature_model(self):
    """Infer temperature model from system attributes."""
    params = set(self.system.temperature_model_parameters.keys())
    # remove or statement in v0.9
    if {"a", "b", "deltaT"} <= params or (
        not params
        and self.system.racking_model is None
        and self.system.module_type is None
    ):
        return self.sapm_temp
    elif {"u_c", "u_v"} <= params:
        return self.pvsyst_temp
    elif {"u0", "u1"} <= params:
        return self.faiman_temp
    else:
        raise ValueError(
            "could not infer temperature model from "
            "system.temperature_module_parameters {}.".format(
                self.system.temperature_model_parameters
            )
        )


# Traceback (TypeError)
In [1]: import pvlib
...: import pandas as pd
...:
...: index_naive = pd.date_range('2019-01-01', freq='h', periods=3)
...:
...: kwargs = {
...:     'poa_global': pd.Series(1000, index_naive),
...:     'temp_air': pd.Series(20, index_naive),
...:     'wind_speed': pd.Series(1, index_naive),
...:     'noct_installed': 45
...: }
...:

In [2]: print(pvlib.temperature.fuentes(**kwargs))
2019-01-01 00:00:00    47.85
2019-01-01 01:00:00    50.85
2019-01-01 02:00:00    50.85
Freq: H, Name: tmod, dtype: float64

In [3]: kwargs['poa_global'].index = index_naive.tz_localize('UTC')
...: print(pvlib.temperature.fuentes(**kwargs))
...:
Traceback (most recent call last):

File "<ipython-input-3-ff99badadc91>", line 2, in <module>
print(pvlib.temperature.fuentes(**kwargs))

File "/home/kevin/anaconda3/lib/python3.7/site-packages/pvlib/temperature.py", line 602, in fuentes
timedelta_hours = np.diff(poa_global.index).astype(float) / 1e9 / 60 / 60

TypeError: float() argument must be a string or a number, not 'Timedelta'

# Fixed code
def infer_temperature_model(self):
    """Infer temperature model from system attributes."""
    params = set(self.system.temperature_model_parameters.keys())
    # remove or statement in v0.9
    if {"a", "b", "deltaT"} <= params or (
        not params
        and self.system.racking_model is None
        and self.system.module_type is None
    ):
        return self.sapm_temp
    elif {"u_c", "u_v"} <= params:
        return self.pvsyst_temp
    elif {"u0", "u1"} <= params:
        return self.faiman_temp
    elif {"noct_installed"} <= params:
        return self.fuentes_temp
    else:
        raise ValueError(
            "could not infer temperature model from "
            "system.temperature_module_parameters {}.".format(
                self.system.temperature_model_parameters
            )
        )
# Buggy code
def _linearly_scale(inputmatrix, inputmin, inputmax, outputmin, outputmax):
    """used by linke turbidity lookup function"""

    inputrange = inputmax - inputmin
    outputrange = outputmax - outputmin
    outputmatrix = (inputmatrix - inputmin) * outputrange / inputrange + outputmin
    return outputmatrix


# Traceback (IndexError)
from pvlib.clearsky import lookup_linke_turbidity
import pandas as pd
time = pd.DatetimeIndex(start='1/1/2016', end='1/2/2016', freq='H')
import os
lookup_linke_turbidity(time, 90, 180, os.path.join('Downloads', 'LinkeTurbidities.mat'))

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\pvlib\clearsky.py", line 210, in lookup_linke_turbidity
g = linke_turbidity_table[latitude_index][longitude_index]
IndexError: index 4320 is out of bounds for axis 0 with size 4320

# Fixed code
def _linearly_scale(inputmatrix, inputmin, inputmax, outputmin, outputmax):
    """linearly scale input to output, used by Linke turbidity lookup"""
    inputrange = inputmax - inputmin
    outputrange = outputmax - outputmin
    delta = outputrange / inputrange  # number of indices per input unit
    inputmin = inputmin + 1.0 / delta / 2.0  # shift to center of index
    outputmax = outputmax - 1  # shift index to zero indexing
    outputmatrix = (inputmatrix - inputmin) * delta + outputmin
    err = IndexError(
        "Input, %g, is out of range (%g, %g)."
        % (inputmatrix, inputmax - inputrange, inputmax)
    )
    # round down if input is within half an index or else raise index error
    if outputmatrix > outputmax:
        if np.around(outputmatrix - outputmax, 1) <= 0.5:
            outputmatrix = outputmax
        else:
            raise err
    elif outputmatrix < outputmin:
        if np.around(outputmin - outputmatrix, 1) <= 0.5:
            outputmatrix = outputmin
        else:
            raise err
    return outputmatrix
# Buggy code
def slugify(value):
    """Remove special characters from a string and slugify it.

    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    value = str(value)
    # This differs from the Lutris website implementation which uses the Django
    # version of `slugify` and uses the "NFKD" normalization method instead of
    # "NFD". This creates some inconsistencies in titles containing a trademark
    # symbols or some other special characters. The website version of slugify
    # will likely get updated to use the same normalization method.
    value = unicodedata.normalize("NFD", value).encode("ascii", "ignore")
    value = value.decode("utf-8")
    value = str(re.sub(r"[^\w\s-]", "", value)).strip().lower()
    return re.sub(r"[-\s]+", "-", value)


# Traceback (ValueError)
Saving メイド☆ぱらだいす ～目指せ！メイドナンバーワン！～ (ppsspp)
DEBUG    2020-06-10 11:02:58,692 [config.save:211]:Saving LutrisConfig(level=game, game_config_id=-1591779765, runner=ppsspp) config to ~/.config/lutris/games/-1591779765.yml
Traceback (most recent call last):
File "~/src/lutris/lutris/gui/config/common.py", line 535, in on_save
self.game.save()
File "~/src/lutris/lutris/game.py", line 252, in save
playtime=self.playtime,
File "~/src/lutris/lutris/pga.py", line 382, in add_or_update
game_id = get_matching_game(params)
File "~/src/lutris/lutris/pga.py", line 400, in get_matching_game
raise ValueError("Can't add or update without an identifier")
ValueError: Can't add or update without an identifier

# Fixed code
def slugify(value):
    """Remove special characters from a string and slugify it.

    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    _value = str(value)
    # This differs from the Lutris website implementation which uses the Django
    # version of `slugify` and uses the "NFKD" normalization method instead of
    # "NFD". This creates some inconsistencies in titles containing a trademark
    # symbols or some other special characters. The website version of slugify
    # will likely get updated to use the same normalization method.
    _value = unicodedata.normalize("NFD", _value).encode("ascii", "ignore")
    _value = _value.decode("utf-8")
    _value = str(re.sub(r"[^\w\s-]", "", _value)).strip().lower()
    slug = re.sub(r"[-\s]+", "-", _value)
    if not slug:
        # The slug is empty, likely because the string contains only non-latin
        # characters
        slug = str(uuid.uuid5(uuid.NAMESPACE_URL, str(value)))
    return slug
# Buggy code
def sort_view(self, key="name", ascending=True):
    self.modelsort.set_sort_column_id(
        self.sort_columns[key],
        Gtk.SortType.ASCENDING if ascending else Gtk.SortType.DESCENDING,
    )


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/batapete/src/lutris/lutris/gui/views/store.py", line 237, in on_sort_column_changed
raise ValueError("Invalid sort key for col %s" % col)
ValueError: Invalid sort key for col 9

# Fixed code
def sort_view(self, key="name", ascending=True):
    """Sort the model on a given column name"""
    try:
        sort_column = self.sort_columns[key]
    except KeyError:
        logger.error("Invalid column name '%s'", key)
        sort_column = COL_NAME
    self.modelsort.set_sort_column_id(
        sort_column,
        Gtk.SortType.ASCENDING if ascending else Gtk.SortType.DESCENDING,
    )
# Buggy code
def game_exe(self):
    """Return the game's executable's path."""
    exe = self.game_config.get("exe")
    if exe:
        if os.path.isabs(exe):
            exe_path = exe
        else:
            exe_path = os.path.join(self.game_path, exe)
        return exe_path


# Traceback (TypeError)
DEBUG    2019-04-10 16:55:14,595 [game.save:212]:Saving S (linux)
DEBUG    2019-04-10 16:55:14,595 [config.save:208]:Saving LutrisConfig(level=game, game_config_id=s-1554908114, runner=linux) config to /home/user/.config/lutris/games/s-1554908114.yml
DEBUG    2019-04-10 16:55:14,667 [lutriswindow.on_game_updated:697]:Updating game S (linux)
DEBUG    2019-04-10 16:55:14,675 [store.get_missing_media:182]:Requesting missing icons from API for s
DEBUG    2019-04-10 16:55:14,677 [http.get:68]:GET https://lutris.net/api/games
DEBUG    2019-04-10 16:55:14,829 [api.get_game_api_page:134]:No game found for s
DEBUG    2019-04-10 16:55:23,219 [game.save:212]:Saving S (linux)
DEBUG    2019-04-10 16:55:23,220 [config.save:208]:Saving LutrisConfig(level=game, game_config_id=s-1554908114, runner=linux) config to /home/user/.config/lutris/games/s-1554908114.yml
DEBUG    2019-04-10 16:55:23,280 [lutriswindow.on_game_updated:697]:Updating game S (linux)
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/lutris/game_actions.py", line 201, in on_edit_game_configuration
EditGameConfigDialog(self.window, self.game)
File "/usr/lib/python3/dist-packages/lutris/gui/config/edit_game.py", line 19, in __init__
self.build_tabs("game")
File "/usr/lib/python3/dist-packages/lutris/gui/config/common.py", line 68, in build_tabs
self._build_game_tab()
File "/usr/lib/python3/dist-packages/lutris/gui/config/common.py", line 307, in _build_game_tab
self.game_box = GameBox(self.lutris_config, self.game)
File "/usr/lib/python3/dist-packages/lutris/gui/config/boxes.py", line 615, in __init__
self.generate_widgets("game")
File "/usr/lib/python3/dist-packages/lutris/gui/config/boxes.py", line 90, in generate_widgets
self.call_widget_generator(option, option_key, value, default)
File "/usr/lib/python3/dist-packages/lutris/gui/config/boxes.py", line 185, in call_widget_generator
self.generate_file_chooser(option, value)
File "/usr/lib/python3/dist-packages/lutris/gui/config/boxes.py", line 390, in generate_file_chooser
path = os.path.join(self.game.directory, path)
File "/usr/lib/python3.6/posixpath.py", line 80, in join
a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not NoneType

# Fixed code
def game_exe(self):
    """Return the game's executable's path."""
    exe = self.game_config.get("exe")
    if not exe:
        return
    if os.path.isabs(exe):
        return exe
    if self.game_path:
        return os.path.join(self.game_path, exe)
    return system.find_executable(exe)
# Buggy code
def get_system_paths():
    """Return paths of system libraries"""
    paths = []
    # This prioritizes system libraries over
    # the Lutris and Steam runtimes.
    for lib_paths in LINUX_SYSTEM.iter_lib_folders():
        for index, _arch in enumerate(LINUX_SYSTEM.runtime_architectures):
            paths.append(lib_paths[index])
    return paths


# Traceback (IndexError)
DEBUG    2019-03-30 14:02:57,737 [application.launch:341]:Adding game EFMB (linux) (140618847460016) to running games
DEBUG    2019-03-30 14:02:57,742 [display._get_vidmodes:15]:Retrieving video modes from XrandR
DEBUG    2019-03-30 14:02:57,761 [game.configure_game:305]:Launching EFMB: {'command': ['/home/cxf/Downloads/EFMB_linux/EFMB/runner']}
DEBUG    2019-03-30 14:02:57,761 [game.configure_game:306]:Game info: {
"command": [
"/home/cxf/Downloads/EFMB_linux/EFMB/runner"
]
}
Traceback (most recent call last):
File "/home/cxf/.lutris/lutris/game_actions.py", line 156, in on_game_run
self.application.launch(self.game)
File "/home/cxf/.lutris/lutris/gui/application.py", line 344, in launch
game.play()
File "/home/cxf/.lutris/lutris/game.py", line 277, in play
self.configure_game(True)
File "/home/cxf/.lutris/lutris/exceptions.py", line 26, in wrapper
return function(*args, **kwargs)
File "/home/cxf/.lutris/lutris/game.py", line 447, in configure_game
game_env = gameplay_info.get("env") or self.runner.get_env()
File "/home/cxf/.lutris/lutris/runners/runner.py", line 149, in get_env
runtime_env = self.get_runtime_env()
File "/home/cxf/.lutris/lutris/runners/runner.py", line 176, in get_runtime_env
prefer_system_libs=self.system_config.get("prefer_system_libs", True)
File "/home/cxf/.lutris/lutris/runtime.py", line 214, in get_env
wine_path=wine_path
File "/home/cxf/.lutris/lutris/runtime.py", line 291, in get_paths
wine_path=wine_path
File "/home/cxf/.lutris/lutris/runtime.py", line 279, in get_runtime_paths
paths += get_system_paths()
File "/home/cxf/.lutris/lutris/runtime.py", line 240, in get_system_paths
paths.append(lib_paths[index])
IndexError: list index out of range

# Fixed code
def get_system_paths():
    """Return paths of system libraries"""
    paths = []
    # This prioritizes system libraries over
    # the Lutris and Steam runtimes.
    for lib_paths in LINUX_SYSTEM.iter_lib_folders():
        for path in lib_paths:
            paths.append(path)
    return paths
# Buggy code
def get_outputs():
    """Return list of tuples containing output name and geometry"""
    outputs = list()
    for line in get_vidmodes():
        parts = line.split()
        if len(parts) < 2:
            continue
        if parts[1] == "connected":
            geom = parts[2] if parts[2] != "primary" else parts[3]
            if geom.startswith("("):  # Screen turned off, no geometry
                continue
            outputs.append((parts[0], geom))
    return outputs


# Traceback (IndexError)
ubuntu-gnome@ubuntu-gnome:~$ lutris
Traceback (most recent call last):
File "/usr/bin/lutris", line 48, in <module>
from lutris.installer import InstallerDialog
File "/usr/lib/pymodules/python2.7/lutris/installer.py", line 24, in <module>
from lutris.gui.config_dialogs import AddGameDialog
File "/usr/lib/pymodules/python2.7/lutris/gui/config_dialogs.py", line 11, in <module>
from lutris.gui.config_boxes import GameBox,  RunnerBox, SystemBox
File "/usr/lib/pymodules/python2.7/lutris/gui/config_boxes.py", line 7, in <module>
from lutris import sysoptions
File "/usr/lib/pymodules/python2.7/lutris/sysoptions.py", line 16, in <module>
outputs = display.get_output_names()
File "/usr/lib/pymodules/python2.7/lutris/util/display.py", line 29, in get_output_names
return [output[0] for output in get_outputs()]
File "/usr/lib/pymodules/python2.7/lutris/util/display.py", line 21, in get_outputs
geom = parts[2] if parts[2] != 'primary' else parts[3]
IndexError: list index out of range

# Fixed code
def get_outputs():
    """Return list of tuples containing output name and geometry"""
    outputs = list()
    for line in get_vidmodes():
        parts = line.split()
        if len(parts) < 2:
            continue
        if parts[1] == "connected":
            if len(parts) == 2:
                continue
            geom = parts[2] if parts[2] != "primary" else parts[3]
            if geom.startswith("("):  # Screen turned off, no geometry
                continue
            outputs.append((parts[0], geom))
    return outputs
# Buggy code
def launch_install(self, script_index):
    script = self.scripts[script_index]
    self.interpreter = installer.ScriptInterpreter(script, self)
    game_name = self.interpreter.game_name.replace("&", "&amp;")
    self.title_label.set_markup("<b>Installing {}</b>".format(game_name))
    self.continue_install()


# Traceback (UnicodeEncodeError)
$ lutris -d
DEBUG    2015-04-09 14:16:41,545 [lutris]:Welcome to Lutris

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines
DEBUG    2015-04-09 14:16:41,678 [lutriswindow]:Getting game list
DEBUG    2015-04-09 14:16:41,886 [lutriswindow]:Switching view
DEBUG    2015-04-09 14:16:42,207 [lutriswindow]:Connecting signals
INFO     2015-04-09 14:16:42,334 [lutriswindow]:Connected as orbea
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: sync_all
DEBUG    2015-04-09 14:16:42,336 [sync]:Syncing game library
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: update_runtime
DEBUG    2015-04-09 14:16:42,336 [sync]:97 games in local library
DEBUG    2015-04-09 14:16:42,338 [api]:Fetching game library
DEBUG    2015-04-09 14:16:43,747 [sync]:97 games in remote library (inc. unpublished)
DEBUG    2015-04-09 14:16:43,770 [sync]:0 games updated
DEBUG    2015-04-09 14:16:43,770 [sync]:Syncing local steam games
DEBUG    2015-04-09 14:16:43,992 [jobs]:Async call: sync_icons
DEBUG    2015-04-09 14:16:43,993 [resources]:Fetching icons
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 833, in on_installer_selected
self.launch_install(self.installer_choice)
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 781, in launch_install
self.title_label.set_markup("<b>Installing {}</b>".format(game_name))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u014d' in position 12: ordinal not in range(128)

# Fixed code
def launch_install(self, script_index):
    script = self.scripts[script_index]
    self.interpreter = installer.ScriptInterpreter(script, self)
    game_name = self.interpreter.game_name.replace("&", "&amp;")
    self.title_label.set_markup("<b>Installing {}</b>".format(game_name))
    self.continue_install()
# Buggy code
def db_insert(db_path, table, fields):
    field_names = ", ".join(fields.keys())
    placeholders = ("?, " * len(fields))[:-2]
    field_values = tuple(fields.values())
    with db_cursor(db_path) as cursor:
        cursor.execute(
            "insert into {0}({1}) values ({2})".format(
                table, field_names, placeholders
            ),
            field_values,
        )


# Traceback (UnicodeEncodeError)
$ lutris -d
DEBUG    2015-04-09 14:16:41,545 [lutris]:Welcome to Lutris

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines
DEBUG    2015-04-09 14:16:41,678 [lutriswindow]:Getting game list
DEBUG    2015-04-09 14:16:41,886 [lutriswindow]:Switching view
DEBUG    2015-04-09 14:16:42,207 [lutriswindow]:Connecting signals
INFO     2015-04-09 14:16:42,334 [lutriswindow]:Connected as orbea
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: sync_all
DEBUG    2015-04-09 14:16:42,336 [sync]:Syncing game library
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: update_runtime
DEBUG    2015-04-09 14:16:42,336 [sync]:97 games in local library
DEBUG    2015-04-09 14:16:42,338 [api]:Fetching game library
DEBUG    2015-04-09 14:16:43,747 [sync]:97 games in remote library (inc. unpublished)
DEBUG    2015-04-09 14:16:43,770 [sync]:0 games updated
DEBUG    2015-04-09 14:16:43,770 [sync]:Syncing local steam games
DEBUG    2015-04-09 14:16:43,992 [jobs]:Async call: sync_icons
DEBUG    2015-04-09 14:16:43,993 [resources]:Fetching icons
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 833, in on_installer_selected
self.launch_install(self.installer_choice)
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 781, in launch_install
self.title_label.set_markup("<b>Installing {}</b>".format(game_name))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u014d' in position 12: ordinal not in range(128)

# Fixed code
def db_insert(db_path, table, fields):
    field_names = ", ".join(fields.keys())
    placeholders = ("?, " * len(fields))[:-2]
    field_values = _decode_utf8_values(fields.values())
    with db_cursor(db_path) as cursor:
        cursor.execute(
            "insert into {0}({1}) values ({2})".format(
                table, field_names, placeholders
            ),
            field_values,
        )
# Buggy code
def db_update(db_path, table, updated_fields, row):
    """update `table` with the values given in the dict `values` on the
    condition given with the tuple `row`
    """
    field_names = "=?, ".join(updated_fields.keys()) + "=?"
    field_values = tuple(updated_fields.values())
    condition_field = "{0}=?".format(row[0])
    condition_value = (row[1],)
    with db_cursor(db_path) as cursor:
        query = "UPDATE {0} SET {1} WHERE {2}".format(
            table, field_names, condition_field
        )
        cursor.execute(query, field_values + condition_value)


# Traceback (UnicodeEncodeError)
$ lutris -d
DEBUG    2015-04-09 14:16:41,545 [lutris]:Welcome to Lutris

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines
DEBUG    2015-04-09 14:16:41,678 [lutriswindow]:Getting game list
DEBUG    2015-04-09 14:16:41,886 [lutriswindow]:Switching view
DEBUG    2015-04-09 14:16:42,207 [lutriswindow]:Connecting signals
INFO     2015-04-09 14:16:42,334 [lutriswindow]:Connected as orbea
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: sync_all
DEBUG    2015-04-09 14:16:42,336 [sync]:Syncing game library
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: update_runtime
DEBUG    2015-04-09 14:16:42,336 [sync]:97 games in local library
DEBUG    2015-04-09 14:16:42,338 [api]:Fetching game library
DEBUG    2015-04-09 14:16:43,747 [sync]:97 games in remote library (inc. unpublished)
DEBUG    2015-04-09 14:16:43,770 [sync]:0 games updated
DEBUG    2015-04-09 14:16:43,770 [sync]:Syncing local steam games
DEBUG    2015-04-09 14:16:43,992 [jobs]:Async call: sync_icons
DEBUG    2015-04-09 14:16:43,993 [resources]:Fetching icons
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 833, in on_installer_selected
self.launch_install(self.installer_choice)
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 781, in launch_install
self.title_label.set_markup("<b>Installing {}</b>".format(game_name))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u014d' in position 12: ordinal not in range(128)

# Fixed code
def db_update(db_path, table, updated_fields, row):
    """update `table` with the values given in the dict `values` on the
    condition given with the tuple `row`
    """
    field_names = "=?, ".join(updated_fields.keys()) + "=?"
    field_values = _decode_utf8_values(updated_fields.values())
    condition_field = "{0}=?".format(row[0])
    condition_value = (row[1],)
    with db_cursor(db_path) as cursor:
        query = "UPDATE {0} SET {1} WHERE {2}".format(
            table, field_names, condition_field
        )
        cursor.execute(query, field_values + condition_value)
# Buggy code
def slugify(value):
    """Remove special characters from a string and slugify it.

    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    value = unicodedata.normalize("NFKD", unicode(value)).encode("ascii", "ignore")
    value = unicode(re.sub("[^\w\s-]", "", value).strip().lower())
    return re.sub("[-\s]+", "-", value)


# Traceback (UnicodeEncodeError)
$ lutris -d
DEBUG    2015-04-09 14:16:41,545 [lutris]:Welcome to Lutris

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines

(lutris:11906): Gtk-WARNING **: Unknown property: GtkLabel.lines
DEBUG    2015-04-09 14:16:41,678 [lutriswindow]:Getting game list
DEBUG    2015-04-09 14:16:41,886 [lutriswindow]:Switching view
DEBUG    2015-04-09 14:16:42,207 [lutriswindow]:Connecting signals
INFO     2015-04-09 14:16:42,334 [lutriswindow]:Connected as orbea
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: sync_all
DEBUG    2015-04-09 14:16:42,336 [sync]:Syncing game library
DEBUG    2015-04-09 14:16:42,336 [jobs]:Async call: update_runtime
DEBUG    2015-04-09 14:16:42,336 [sync]:97 games in local library
DEBUG    2015-04-09 14:16:42,338 [api]:Fetching game library
DEBUG    2015-04-09 14:16:43,747 [sync]:97 games in remote library (inc. unpublished)
DEBUG    2015-04-09 14:16:43,770 [sync]:0 games updated
DEBUG    2015-04-09 14:16:43,770 [sync]:Syncing local steam games
DEBUG    2015-04-09 14:16:43,992 [jobs]:Async call: sync_icons
DEBUG    2015-04-09 14:16:43,993 [resources]:Fetching icons
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 833, in on_installer_selected
self.launch_install(self.installer_choice)
File "/usr/lib64/python2.7/site-packages/lutris/installer.py", line 781, in launch_install
self.title_label.set_markup("<b>Installing {}</b>".format(game_name))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u014d' in position 12: ordinal not in range(128)

# Fixed code
def slugify(value):
    """Remove special characters from a string and slugify it.

    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    value = value.decode("UTF-8")
    value = unicodedata.normalize("NFKD", value).encode("ascii", "ignore")
    value = unicode(re.sub("[^\w\s-]", "", value).strip().lower())
    return re.sub("[-\s]+", "-", value)
# Buggy code
def _check_for_async(self):
    if self.config.check_for_async:
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            pass
        else:
            logger.warning(
                "It appears that you are using PRAW in an asynchronous"
                " environment.\nIt is strongly recommended to use Async PRAW:"
                " https://asyncpraw.readthedocs.io.\nSee"
                " https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments"
                " for more info.\n",
            )


# Traceback (AttributeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/../venv/lib64/python3.6/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
self._fetch()
File "/../venv/lib64/python3.6/site-packages/praw/models/reddit/redditor.py", line 170, in _fetch
data = self._fetch_data()
File "/../venv/lib64/python3.6/site-packages/praw/models/reddit/redditor.py", line 167, in _fetch_data
return self._reddit.request("GET", path, params)
File "/../venv/lib64/python3.6/site-packages/praw/reddit.py", line 793, in request
self._check_for_async()
File "/../venv/lib64/python3.6/site-packages/praw/reddit.py", line 371, in _check_for_async
asyncio.get_running_loop()
AttributeError: module 'asyncio' has no attribute 'get_running_loop'

# Fixed code
def _check_for_async(self):
    if self.config.check_for_async:
        in_async = False
        if sys.version_info >= (3, 7, 0):
            try:
                asyncio.get_running_loop()
                in_async = True
            except RuntimeError:
                pass
        else:  # pragma: no cover # not able to be covered in > Python 3.6.12
            in_async = asyncio.get_event_loop().is_running()
        if in_async:
            logger.warning(
                "It appears that you are using PRAW in an asynchronous"
                " environment.\nIt is strongly recommended to use Async PRAW:"
                " https://asyncpraw.readthedocs.io.\nSee"
                " https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments"
                " for more info.\n",
            )
# Buggy code
def id_from_url(url: str) -> str:
    """Return the ID contained within a submission URL.

    :param url: A url to a submission in one of the following formats (http urls
        will also work):

        * https://redd.it/2gmzqe
        * https://reddit.com/comments/2gmzqe/
        * https://www.reddit.com/r/redditdev/comments/2gmzqe/praw_https/
        * https://www.reddit.com/gallery/2gmzqe

    :raises: :class:`.InvalidURL` if URL is not a valid submission URL.

    """
    parts = RedditBase._url_parts(url)
    if "comments" not in parts and "gallery" not in parts:
        submission_id = parts[-1]
        if "r" in parts:
            raise InvalidURL(url, message="Invalid URL (subreddit, not submission): {}")
    elif "gallery" in parts:
        submission_id = parts[parts.index("gallery") + 1]
    else:
        submission_id = parts[parts.index("comments") + 1]

    if not submission_id.isalnum():
        raise InvalidURL(url)
    return submission_id


# Traceback (IndexError)
IndexError                                Traceback (most recent call last)
<ipython-input-14-87a53f614e22> in <module>
----> 1 reddit.submission(url="https://reddit.com/comments/")

~/.local/share/virtualenvs/tmp-agwWamBd/lib/python3.8/site-packages/praw/reddit.py in submission(self, id, url)
798
799         """
--> 800         return models.Submission(self, id=id, url=url)

~/.local/share/virtualenvs/tmp-agwWamBd/lib/python3.8/site-packages/praw/models/reddit/submission.py in __init__(self, reddit, id, url, _data)
538             self.id = id
539         elif url is not None:
--> 540             self.id = self.id_from_url(url)
541
542         self._comments_by_id = {}

~/.local/share/virtualenvs/tmp-agwWamBd/lib/python3.8/site-packages/praw/models/reddit/submission.py in id_from_url(url)
422                 )
423         else:
--> 424             submission_id = parts[parts.index("comments") + 1]
425
426         if not submission_id.isalnum():

IndexError: list index out of range

# Fixed code
def id_from_url(url: str) -> str:
    """Return the ID contained within a submission URL.

    :param url: A url to a submission in one of the following formats (http urls
        will also work):

        * https://redd.it/2gmzqe
        * https://reddit.com/comments/2gmzqe/
        * https://www.reddit.com/r/redditdev/comments/2gmzqe/praw_https/
        * https://www.reddit.com/gallery/2gmzqe

    :raises: :class:`.InvalidURL` if URL is not a valid submission URL.

    """
    parts = RedditBase._url_parts(url)
    if "comments" not in parts and "gallery" not in parts:
        submission_id = parts[-1]
        if "r" in parts:
            raise InvalidURL(url, message="Invalid URL (subreddit, not submission): {}")

    elif "gallery" in parts:
        submission_id = parts[parts.index("gallery") + 1]

    elif parts[-1] == "comments":
        raise InvalidURL(url, message="Invalid URL (submission id not present): {}")

    else:
        submission_id = parts[parts.index("comments") + 1]

    if not submission_id.isalnum():
        raise InvalidURL(url)
    return submission_id