gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _getdict(self, value, default, sep):
    if value is None:
        return default or {}

    d = {}
    for line in value.split(sep):
        if line.strip():
            name, rest = line.split("=", 1)
            d[name.strip()] = rest.strip()

    return d


# Traceback (ValueError)
2017-09-01 18:22:20.661 | ++ lib/tempest:install_tempest:612          :   pushd /opt/stack/new/tempest
2017-09-01 18:22:20.661 | ~/tempest ~/devstack
2017-09-01 18:22:20.662 | ++ lib/tempest:install_tempest:613          :   tox -r --notest -efull
2017-09-01 18:22:21.720 | Traceback (most recent call last):
2017-09-01 18:22:21.720 |   File "/usr/local/bin/tox", line 11, in <module>
2017-09-01 18:22:21.720 |     sys.exit(cmdline())
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 38, in main
2017-09-01 18:22:21.720 |     config = prepare(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 26, in prepare
2017-09-01 18:22:21.720 |     config = parseconfig(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 242, in parseconfig
2017-09-01 18:22:21.720 |     parseini(config, inipath)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 796, in __init__
2017-09-01 18:22:21.721 |     replace=name in config.envlist)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 827, in make_envconfig
2017-09-01 18:22:21.721 |     res = meth(env_attr.name, env_attr.default, replace=replace)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 964, in getdict_setenv
2017-09-01 18:22:21.721 |     definitions = self._getdict(value, default=default, sep=sep)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 975, in _getdict
2017-09-01 18:22:21.721 |     name, rest = line.split('=', 1)
2017-09-01 18:22:21.721 | ValueError: need more than 1 value to unpack
2017-09-01 18:22:21.733 | + lib/tempest:install_tempest:1            :   exit_trap

# Fixed code
def _getdict(self, value, default, sep, replace=True):
    if value is None or not replace:
        return default or {}

    d = {}
    for line in value.split(sep):
        if line.strip():
            name, rest = line.split("=", 1)
            d[name.strip()] = rest.strip()

    return d
# Buggy code
def getbool(self, name, default=None, replace=True):
    s = self.getstring(name, default, replace=replace)
    if not s:
        s = default
    if s is None:
        raise KeyError("no config value [%s] %s found" % (self.section_name, name))

    if not isinstance(s, bool):
        if s.lower() == "true":
            s = True
        elif s.lower() == "false":
            s = False
        else:
            raise tox.exception.ConfigError(
                "boolean value %r needs to be 'True' or 'False'"
            )
    return s


# Traceback (ValueError)
2017-09-01 18:22:20.661 | ++ lib/tempest:install_tempest:612          :   pushd /opt/stack/new/tempest
2017-09-01 18:22:20.661 | ~/tempest ~/devstack
2017-09-01 18:22:20.662 | ++ lib/tempest:install_tempest:613          :   tox -r --notest -efull
2017-09-01 18:22:21.720 | Traceback (most recent call last):
2017-09-01 18:22:21.720 |   File "/usr/local/bin/tox", line 11, in <module>
2017-09-01 18:22:21.720 |     sys.exit(cmdline())
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 38, in main
2017-09-01 18:22:21.720 |     config = prepare(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 26, in prepare
2017-09-01 18:22:21.720 |     config = parseconfig(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 242, in parseconfig
2017-09-01 18:22:21.720 |     parseini(config, inipath)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 796, in __init__
2017-09-01 18:22:21.721 |     replace=name in config.envlist)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 827, in make_envconfig
2017-09-01 18:22:21.721 |     res = meth(env_attr.name, env_attr.default, replace=replace)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 964, in getdict_setenv
2017-09-01 18:22:21.721 |     definitions = self._getdict(value, default=default, sep=sep)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 975, in _getdict
2017-09-01 18:22:21.721 |     name, rest = line.split('=', 1)
2017-09-01 18:22:21.721 | ValueError: need more than 1 value to unpack
2017-09-01 18:22:21.733 | + lib/tempest:install_tempest:1            :   exit_trap

# Fixed code
def getbool(self, name, default=None, replace=True):
    s = self.getstring(name, default, replace=replace)
    if not s or not replace:
        s = default
    if s is None:
        raise KeyError("no config value [%s] %s found" % (self.section_name, name))

    if not isinstance(s, bool):
        if s.lower() == "true":
            s = True
        elif s.lower() == "false":
            s = False
        else:
            raise tox.exception.ConfigError(
                "boolean value %r needs to be 'True' or 'False'"
            )
    return s
# Buggy code
def __init__(self, envname, config, factors, reader):
    #: test environment name
    self.envname = envname
    #: global tox config object
    self.config = config
    #: set of factors
    self.factors = factors
    self._reader = reader


# Traceback (ValueError)
2017-09-01 18:22:20.661 | ++ lib/tempest:install_tempest:612          :   pushd /opt/stack/new/tempest
2017-09-01 18:22:20.661 | ~/tempest ~/devstack
2017-09-01 18:22:20.662 | ++ lib/tempest:install_tempest:613          :   tox -r --notest -efull
2017-09-01 18:22:21.720 | Traceback (most recent call last):
2017-09-01 18:22:21.720 |   File "/usr/local/bin/tox", line 11, in <module>
2017-09-01 18:22:21.720 |     sys.exit(cmdline())
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 38, in main
2017-09-01 18:22:21.720 |     config = prepare(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 26, in prepare
2017-09-01 18:22:21.720 |     config = parseconfig(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 242, in parseconfig
2017-09-01 18:22:21.720 |     parseini(config, inipath)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 796, in __init__
2017-09-01 18:22:21.721 |     replace=name in config.envlist)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 827, in make_envconfig
2017-09-01 18:22:21.721 |     res = meth(env_attr.name, env_attr.default, replace=replace)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 964, in getdict_setenv
2017-09-01 18:22:21.721 |     definitions = self._getdict(value, default=default, sep=sep)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 975, in _getdict
2017-09-01 18:22:21.721 |     name, rest = line.split('=', 1)
2017-09-01 18:22:21.721 | ValueError: need more than 1 value to unpack
2017-09-01 18:22:21.733 | + lib/tempest:install_tempest:1            :   exit_trap

# Fixed code
def __init__(self, envname, config, factors, reader):
    #: test environment name
    self.envname = envname
    #: global tox config object
    self.config = config
    #: set of factors
    self.factors = factors
    self._reader = reader
    self.missing_subs = []
    """Holds substitutions that could not be resolved.

        Pre 2.8.1 missing substitutions crashed with a ConfigError although this would not be a
        problem if the env is not part of the current testrun. So we need to remember this and
        check later when the testenv is actually run and crash only then.
        """
# Buggy code
def _replace(self, value, name=None, section_name=None, crossonly=False):
    if "{" not in value:
        return value

    section_name = section_name if section_name else self.section_name
    self._subststack.append((section_name, name))
    try:
        return Replacer(self, crossonly=crossonly).do_replace(value)
    finally:
        assert self._subststack.pop() == (section_name, name)


# Traceback (ValueError)
2017-09-01 18:22:20.661 | ++ lib/tempest:install_tempest:612          :   pushd /opt/stack/new/tempest
2017-09-01 18:22:20.661 | ~/tempest ~/devstack
2017-09-01 18:22:20.662 | ++ lib/tempest:install_tempest:613          :   tox -r --notest -efull
2017-09-01 18:22:21.720 | Traceback (most recent call last):
2017-09-01 18:22:21.720 |   File "/usr/local/bin/tox", line 11, in <module>
2017-09-01 18:22:21.720 |     sys.exit(cmdline())
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 38, in main
2017-09-01 18:22:21.720 |     config = prepare(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 26, in prepare
2017-09-01 18:22:21.720 |     config = parseconfig(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 242, in parseconfig
2017-09-01 18:22:21.720 |     parseini(config, inipath)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 796, in __init__
2017-09-01 18:22:21.721 |     replace=name in config.envlist)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 827, in make_envconfig
2017-09-01 18:22:21.721 |     res = meth(env_attr.name, env_attr.default, replace=replace)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 964, in getdict_setenv
2017-09-01 18:22:21.721 |     definitions = self._getdict(value, default=default, sep=sep)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 975, in _getdict
2017-09-01 18:22:21.721 |     name, rest = line.split('=', 1)
2017-09-01 18:22:21.721 | ValueError: need more than 1 value to unpack
2017-09-01 18:22:21.733 | + lib/tempest:install_tempest:1            :   exit_trap

# Fixed code
def _replace(self, value, name=None, section_name=None, crossonly=False):
    if "{" not in value:
        return value

    section_name = section_name if section_name else self.section_name
    self._subststack.append((section_name, name))
    try:
        replaced = Replacer(self, crossonly=crossonly).do_replace(value)
        assert self._subststack.pop() == (section_name, name)
    except tox.exception.MissingSubstitution:
        if not section_name.startswith(testenvprefix):
            raise tox.exception.ConfigError(
                "substitution env:%r: unknown or recursive definition in "
                "section %r." % (value, section_name)
            )
        raise
    return replaced
# Buggy code
def _replace_env(self, match):
    envkey = match.group("substitution_value")
    if not envkey:
        raise tox.exception.ConfigError("env: requires an environment variable name")

    default = match.group("default_value")

    envvalue = self.reader.get_environ_value(envkey)
    if envvalue is None:
        if default is None:
            raise tox.exception.ConfigError(
                "substitution env:%r: unknown environment variable %r "
                " or recursive definition." % (envkey, envkey)
            )
        return default
    return envvalue


# Traceback (ValueError)
2017-09-01 18:22:20.661 | ++ lib/tempest:install_tempest:612          :   pushd /opt/stack/new/tempest
2017-09-01 18:22:20.661 | ~/tempest ~/devstack
2017-09-01 18:22:20.662 | ++ lib/tempest:install_tempest:613          :   tox -r --notest -efull
2017-09-01 18:22:21.720 | Traceback (most recent call last):
2017-09-01 18:22:21.720 |   File "/usr/local/bin/tox", line 11, in <module>
2017-09-01 18:22:21.720 |     sys.exit(cmdline())
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 38, in main
2017-09-01 18:22:21.720 |     config = prepare(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/session.py", line 26, in prepare
2017-09-01 18:22:21.720 |     config = parseconfig(args)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 242, in parseconfig
2017-09-01 18:22:21.720 |     parseini(config, inipath)
2017-09-01 18:22:21.720 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 796, in __init__
2017-09-01 18:22:21.721 |     replace=name in config.envlist)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 827, in make_envconfig
2017-09-01 18:22:21.721 |     res = meth(env_attr.name, env_attr.default, replace=replace)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 964, in getdict_setenv
2017-09-01 18:22:21.721 |     definitions = self._getdict(value, default=default, sep=sep)
2017-09-01 18:22:21.721 |   File "/usr/local/lib/python2.7/dist-packages/tox/config.py", line 975, in _getdict
2017-09-01 18:22:21.721 |     name, rest = line.split('=', 1)
2017-09-01 18:22:21.721 | ValueError: need more than 1 value to unpack
2017-09-01 18:22:21.733 | + lib/tempest:install_tempest:1            :   exit_trap

# Fixed code
def _replace_env(self, match):
    envkey = match.group("substitution_value")
    if not envkey:
        raise tox.exception.ConfigError("env: requires an environment variable name")
    default = match.group("default_value")
    envvalue = self.reader.get_environ_value(envkey)
    if envvalue is not None:
        return envvalue
    if default is not None:
        return default
    raise tox.exception.MissingSubstitution(envkey)
# Buggy code
def get_display_name(self, locale=None):
    """Return the display name of the locale using the given locale.

    The display name will include the language, territory, script, and
    variant, if those are specified.

    >>> Locale('zh', 'CN', script='Hans').get_display_name('en')
    u'Chinese (Simplified, China)'

    :param locale: the locale to use
    """
    if locale is None:
        locale = self
    locale = Locale.parse(locale)
    retval = locale.languages.get(self.language)
    if self.territory or self.script or self.variant:
        details = []
        if self.script:
            details.append(locale.scripts.get(self.script))
        if self.territory:
            details.append(locale.territories.get(self.territory))
        if self.variant:
            details.append(locale.variants.get(self.variant))
        details = filter(None, details)
        if details:
            retval += " (%s)" % ", ".join(details)
    return retval


# Traceback (TypeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/will/tmp/babel-bug/env/lib/python3.6/site-packages/babel/core.py", line 392, in get_display_name
retval += ' (%s)' % u', '.join(details)
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

# Fixed code
def get_display_name(self, locale=None):
    """Return the display name of the locale using the given locale.

    The display name will include the language, territory, script, and
    variant, if those are specified.

    >>> Locale('zh', 'CN', script='Hans').get_display_name('en')
    u'Chinese (Simplified, China)'

    :param locale: the locale to use
    """
    if locale is None:
        locale = self
    locale = Locale.parse(locale)
    retval = locale.languages.get(self.language)
    if retval and (self.territory or self.script or self.variant):
        details = []
        if self.script:
            details.append(locale.scripts.get(self.script))
        if self.territory:
            details.append(locale.territories.get(self.territory))
        if self.variant:
            details.append(locale.variants.get(self.variant))
        details = filter(None, details)
        if details:
            retval += " (%s)" % ", ".join(details)
    return retval
# Buggy code
def _get_header_comment(self):
    comment = self._header_comment
    year = datetime.now(LOCALTZ).strftime("%Y")
    if hasattr(self.revision_date, "strftime"):
        year = self.revision_date.strftime("%Y")
    comment = (
        comment.replace("PROJECT", self.project)
        .replace("VERSION", self.version)
        .replace("YEAR", year)
        .replace("ORGANIZATION", self.copyright_holder)
    )
    if self.locale:
        comment = comment.replace(
            "Translations template", "%s translations" % self.locale.english_name
        )
    return comment


# Traceback (babel.core.UnknownLocaleError)
Traceback (most recent call last):
File "/usr/local/bin/pybabel", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 908, in main
return CommandLineInterface().run(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 832, in run
return cmdinst.run()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 182, in run
self._run_domain(domain)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 221, in _run_domain
catalog = read_po(infile, locale)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 331, in read_po
parser.parse(fileobj)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 265, in parse
self._process_comment(line)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 224, in _process_comment
self._finish_current_message()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 164, in _finish_current_message
self._add_message()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 158, in _add_message
self.catalog[msgid] = message
File "/usr/local/lib/python3.5/dist-packages/babel/messages/catalog.py", line 596, in __setitem__
self.mime_headers = _parse_header(message.string).items()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/catalog.py", line 399, in _set_mime_headers
self.locale = Locale.parse(value)
File "/usr/local/lib/python3.5/dist-packages/babel/core.py", line 331, in parse
raise UnknownLocaleError(input_id)
babel.core.UnknownLocaleError: unknown locale 'sr_SP'

# Fixed code
def _get_header_comment(self):
    comment = self._header_comment
    year = datetime.now(LOCALTZ).strftime("%Y")
    if hasattr(self.revision_date, "strftime"):
        year = self.revision_date.strftime("%Y")
    comment = (
        comment.replace("PROJECT", self.project)
        .replace("VERSION", self.version)
        .replace("YEAR", year)
        .replace("ORGANIZATION", self.copyright_holder)
    )
    locale_name = self.locale.english_name if self.locale else self.locale_identifier
    if locale_name:
        comment = comment.replace(
            "Translations template", "%s translations" % locale_name
        )
    return comment
# Buggy code
def plural_expr(self):
    """The plural expression used by the catalog or locale.

    >>> Catalog(locale='en').plural_expr
    '(n != 1)'
    >>> Catalog(locale='ga').plural_expr
    '(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)'

    :type: `string_types`"""
    if self._plural_expr is None:
        expr = "(n != 1)"
        if self.locale:
            expr = get_plural(self.locale)[1]
        self._plural_expr = expr
    return self._plural_expr


# Traceback (babel.core.UnknownLocaleError)
Traceback (most recent call last):
File "/usr/local/bin/pybabel", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 908, in main
return CommandLineInterface().run(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 832, in run
return cmdinst.run()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 182, in run
self._run_domain(domain)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/frontend.py", line 221, in _run_domain
catalog = read_po(infile, locale)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 331, in read_po
parser.parse(fileobj)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 265, in parse
self._process_comment(line)
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 224, in _process_comment
self._finish_current_message()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 164, in _finish_current_message
self._add_message()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/pofile.py", line 158, in _add_message
self.catalog[msgid] = message
File "/usr/local/lib/python3.5/dist-packages/babel/messages/catalog.py", line 596, in __setitem__
self.mime_headers = _parse_header(message.string).items()
File "/usr/local/lib/python3.5/dist-packages/babel/messages/catalog.py", line 399, in _set_mime_headers
self.locale = Locale.parse(value)
File "/usr/local/lib/python3.5/dist-packages/babel/core.py", line 331, in parse
raise UnknownLocaleError(input_id)
babel.core.UnknownLocaleError: unknown locale 'sr_SP'

# Fixed code
def plural_expr(self):
    """The plural expression used by the catalog or locale.

    >>> Catalog(locale='en').plural_expr
    '(n != 1)'
    >>> Catalog(locale='ga').plural_expr
    '(n==1 ? 0 : n==2 ? 1 : n>=3 && n<=6 ? 2 : n>=7 && n<=10 ? 3 : 4)'
    >>> Catalog(locale='ding').plural_expr  # unknown locale
    '(n != 1)'

    :type: `string_types`"""
    if self._plural_expr is None:
        expr = "(n != 1)"
        if self.locale:
            expr = get_plural(self.locale)[1]
        self._plural_expr = expr
    return self._plural_expr
# Buggy code
def format_period(self, char):
    period = {0: "am", 1: "pm"}[int(self.value.hour >= 12)]
    return get_period_names(locale=self.locale)[period]


# Traceback (KeyError)
import babel
babel.__version__
'2.3.1'
from datetime import datetime
from babel.dates import format_time
format_time(datetime(2016, 4, 8, 12, 34, 56), locale='zh_TW')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/dev/shm/babel231/local/lib/python2.7/site-packages/babel/dates.py", line 787, in format_time
return parse_pattern(format).apply(time, locale)
File "/dev/shm/babel231/local/lib/python2.7/site-packages/babel/dates.py", line 1208, in apply
return self % DateTimeFormat(datetime, locale)
File "/dev/shm/babel231/local/lib/python2.7/site-packages/babel/dates.py", line 1205, in __mod__
return self.format % other
File "/dev/shm/babel231/local/lib/python2.7/site-packages/babel/dates.py", line 1242, in __getitem__
return self.format_period(char)
File "/dev/shm/babel231/local/lib/python2.7/site-packages/babel/dates.py", line 1384, in format_period
return get_period_names(locale=self.locale)[period]
File "/dev/shm/babel231/local/lib/python2.7/site-packages/babel/localedata.py", line 207, in __getitem__
orig = val = self._data[key]
KeyError: 'pm'

# Fixed code
def format_period(self, char):
    period = {0: "am", 1: "pm"}[int(self.value.hour >= 12)]
    for width in ("wide", "narrow", "abbreviated"):
        period_names = get_period_names(
            context="format", width=width, locale=self.locale
        )
        if period in period_names:
            return period_names[period]
    raise ValueError("Could not format period %s in %s" % (period, self.locale))
# Buggy code
def check_http_service(endpoint):
    if endpoint.family == socket.AF_INET:
        url = "http://{host}:{port}/health".format(
            host=endpoint.address.host, port=endpoint.address.port
        )
    elif endpoint.family == socket.AF_UNIX:
        quoted_path = urllib.quote(endpoint.address, safe="")
        url = "http+unix://{path}/health".format(path=quoted_path)
    else:
        raise ValueError("unrecognized socket family %r" % endpoint.family)

    session = requests.Session()
    add_unix_socket_support(session)
    response = session.get(url, timeout=TIMEOUT)
    response.raise_for_status()
    response.json()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/baseplate-healthcheck3", line 9, in <module>
load_entry_point('baseplate', 'console_scripts', 'baseplate-healthcheck3')()
File "/usr/lib/python3/dist-packages/baseplate/server/healthcheck.py", line 68, in run_healthchecks
checker(args.endpoint)
File "/usr/lib/python3/dist-packages/baseplate/server/healthcheck.py", line 35, in check_http_service
quoted_path = urllib.quote(endpoint.address, safe="")
AttributeError: 'module' object has no attribute 'quote'

# Fixed code
def check_http_service(endpoint):
    if endpoint.family == socket.AF_INET:
        url = "http://{host}:{port}/health".format(
            host=endpoint.address.host, port=endpoint.address.port
        )
    elif endpoint.family == socket.AF_UNIX:
        quoted_path = quote(endpoint.address, safe="")
        url = "http+unix://{path}/health".format(path=quoted_path)
    else:
        raise ValueError("unrecognized socket family %r" % endpoint.family)

    session = requests.Session()
    add_unix_socket_support(session)
    response = session.get(url, timeout=TIMEOUT)
    response.raise_for_status()
    response.json()
# Buggy code
def set_password(self, service, repo_url, password):
    raise NotImplementedError


# Traceback (dbus.exceptions.DBusException)
2020-08-31 20:53:34,066 - vorta.borg.borg_thread - DEBUG - Using VortaSecretStorageKeyring keyring to store passwords.
2020-08-31 20:53:34,066 - asyncio - DEBUG - Using selector: EpollSelector
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/vorta/views/repo_add_dialog.py", line 64, in run
params = BorgInitThread.prepare(self.values)
File "/home/user/.local/lib/python3.8/site-packages/vorta/borg/init.py", line 20, in prepare
ret = super().prepare(profile)
File "/home/user/.local/lib/python3.8/site-packages/vorta/borg/borg_thread.py", line 121, in prepare
ret['password'] = keyring.get_password('vorta-repo', profile.repo.url)
File "/home/user/.local/lib/python3.8/site-packages/vorta/keyring/secretstorage.py", line 30, in get_password
collection = secretstorage.get_default_collection(self.connection)
File "/usr/lib/python3/dist-packages/secretstorage/collection.py", line 155, in get_default_collection
return Collection(bus)
File "/usr/lib/python3/dist-packages/secretstorage/collection.py", line 42, in __init__
self.collection_props_iface.Get(COLLECTION_IFACE, 'Label',
File "/usr/lib/python3/dist-packages/secretstorage/util.py", line 31, in function_out
return function_in(*args, **kwargs)
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 141, in __call__
return self._connection.call_blocking(self._named_service,
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 652, in call_blocking
reply_message = self.send_message_with_reply_and_block(
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownObject: No such object path '/org/freedesktop/secrets/aliases/default'

# Fixed code
def set_password(self, service, repo_url, password):
    """
    Writes a password to the underlying store.
    """
    raise NotImplementedError
# Buggy code
def set_password(self, service, repo_url, password):
    asyncio.set_event_loop(asyncio.new_event_loop())
    collection = secretstorage.get_default_collection(self.connection)
    attributes = {
        "application": "Vorta",
        "service": service,
        "repo_url": repo_url,
        "xdg:schema": "org.freedesktop.Secret.Generic",
    }
    collection.create_item(repo_url, attributes, password, replace=True)


# Traceback (dbus.exceptions.DBusException)
2020-08-31 20:53:34,066 - vorta.borg.borg_thread - DEBUG - Using VortaSecretStorageKeyring keyring to store passwords.
2020-08-31 20:53:34,066 - asyncio - DEBUG - Using selector: EpollSelector
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/vorta/views/repo_add_dialog.py", line 64, in run
params = BorgInitThread.prepare(self.values)
File "/home/user/.local/lib/python3.8/site-packages/vorta/borg/init.py", line 20, in prepare
ret = super().prepare(profile)
File "/home/user/.local/lib/python3.8/site-packages/vorta/borg/borg_thread.py", line 121, in prepare
ret['password'] = keyring.get_password('vorta-repo', profile.repo.url)
File "/home/user/.local/lib/python3.8/site-packages/vorta/keyring/secretstorage.py", line 30, in get_password
collection = secretstorage.get_default_collection(self.connection)
File "/usr/lib/python3/dist-packages/secretstorage/collection.py", line 155, in get_default_collection
return Collection(bus)
File "/usr/lib/python3/dist-packages/secretstorage/collection.py", line 42, in __init__
self.collection_props_iface.Get(COLLECTION_IFACE, 'Label',
File "/usr/lib/python3/dist-packages/secretstorage/util.py", line 31, in function_out
return function_in(*args, **kwargs)
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 141, in __call__
return self._connection.call_blocking(self._named_service,
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 652, in call_blocking
reply_message = self.send_message_with_reply_and_block(
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownObject: No such object path '/org/freedesktop/secrets/aliases/default'

# Fixed code
def set_password(self, service, repo_url, password):
    try:
        asyncio.set_event_loop(asyncio.new_event_loop())
        collection = secretstorage.get_default_collection(self.connection)
        attributes = {
            "application": "Vorta",
            "service": service,
            "repo_url": repo_url,
            "xdg:schema": "org.freedesktop.Secret.Generic",
        }
        collection.create_item(repo_url, attributes, password, replace=True)
    except secretstorage.exceptions.ItemNotFoundException:
        logger.error("SecretStorage writing failed", exc_info=sys.exc_info())
# Buggy code
def get_password(self, service, repo_url):
    asyncio.set_event_loop(asyncio.new_event_loop())
    collection = secretstorage.get_default_collection(self.connection)
    if collection.is_locked():
        collection.unlock()
    attributes = {"application": "Vorta", "service": service, "repo_url": repo_url}
    items = list(collection.search_items(attributes))
    logger.debug("Found %i passwords matching repo URL.", len(items))
    if len(items) > 0:
        return items[0].get_secret().decode("utf-8")
    return None


# Traceback (dbus.exceptions.DBusException)
2020-08-31 20:53:34,066 - vorta.borg.borg_thread - DEBUG - Using VortaSecretStorageKeyring keyring to store passwords.
2020-08-31 20:53:34,066 - asyncio - DEBUG - Using selector: EpollSelector
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/vorta/views/repo_add_dialog.py", line 64, in run
params = BorgInitThread.prepare(self.values)
File "/home/user/.local/lib/python3.8/site-packages/vorta/borg/init.py", line 20, in prepare
ret = super().prepare(profile)
File "/home/user/.local/lib/python3.8/site-packages/vorta/borg/borg_thread.py", line 121, in prepare
ret['password'] = keyring.get_password('vorta-repo', profile.repo.url)
File "/home/user/.local/lib/python3.8/site-packages/vorta/keyring/secretstorage.py", line 30, in get_password
collection = secretstorage.get_default_collection(self.connection)
File "/usr/lib/python3/dist-packages/secretstorage/collection.py", line 155, in get_default_collection
return Collection(bus)
File "/usr/lib/python3/dist-packages/secretstorage/collection.py", line 42, in __init__
self.collection_props_iface.Get(COLLECTION_IFACE, 'Label',
File "/usr/lib/python3/dist-packages/secretstorage/util.py", line 31, in function_out
return function_in(*args, **kwargs)
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 141, in __call__
return self._connection.call_blocking(self._named_service,
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 652, in call_blocking
reply_message = self.send_message_with_reply_and_block(
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownObject: No such object path '/org/freedesktop/secrets/aliases/default'

# Fixed code
def get_password(self, service, repo_url):
    if self.is_unlocked:
        asyncio.set_event_loop(asyncio.new_event_loop())
        collection = secretstorage.get_default_collection(self.connection)
        attributes = {"application": "Vorta", "service": service, "repo_url": repo_url}
        items = list(collection.search_items(attributes))
        logger.debug("Found %i passwords matching repo URL.", len(items))
        if len(items) > 0:
            return items[0].get_secret().decode("utf-8")
    return None
# Buggy code
def validate(self):
    """Pre-flight check for valid input and borg binary."""
    if self.is_remote_repo and not re.match(r".+:.+", self.values["repo_url"]):
        self._set_status(
            self.tr("Please enter a valid repo URL or select a local path.")
        )
        return False

    if self.__class__ == AddRepoWindow:
        if self.values["encryption"] != "none":
            if len(self.values["password"]) < 8:
                self._set_status(self.tr("Please use a longer passphrase."))
                return False

    return True


# Traceback (IndexError)
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/peewee.py", line 6665, in get
return clone.execute(database)[0]
File "/app/lib/python3.7/site-packages/peewee.py", line 4121, in __getitem__
return self.row_cache[item]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/vorta/application.py", line 80, in open_main_window_action
self.main_window = MainWindow(self)
File "/app/lib/python3.7/site-packages/vorta/views/main_window.py", line 37, in __init__
self.repoTab = RepoTab(self.repoTabSlot)
File "/app/lib/python3.7/site-packages/vorta/views/repo_tab.py", line 59, in __init__
self.init_repo_stats()
File "/app/lib/python3.7/site-packages/vorta/views/repo_tab.py", line 74, in init_repo_stats
repo = self.profile().repo
File "/app/lib/python3.7/site-packages/peewee.py", line 4269, in __get__
return self.get_rel_instance(instance)
File "/app/lib/python3.7/site-packages/peewee.py", line 4260, in get_rel_instance
obj = self.rel_model.get(self.field.rel_field == value)
File "/app/lib/python3.7/site-packages/peewee.py", line 6242, in get
return sq.get()
File "/app/lib/python3.7/site-packages/peewee.py", line 6670, in get
(clone.model, sql, params))
vorta.models.RepoModelDoesNotExist: <Model: RepoModel> instance matching query does not exist:
SQL: SELECT "t1"."id", "t1"."url", "t1"."added_at", "t1"."encryption", "t1"."unique_size", "t1"."unique_csize", "t1"."total_size", "t1"."total_unique_chunks", "t1"."extra_borg_arguments" FROM "repomodel" AS "t1" WHERE ("t1"."id" = ?) LIMIT ? OFFSET ?
Params: [1, 1, 0]

# Fixed code
def validate(self):
    """Pre-flight check for valid input and borg binary."""
    if self.is_remote_repo and not re.match(r".+:.+", self.values["repo_url"]):
        self._set_status(
            self.tr("Please enter a valid repo URL or select a local path.")
        )
        return False

    if RepoModel.get_or_none(RepoModel.url == self.values["repo_url"]) is not None:
        self._set_status(self.tr("This repo has already been added."))
        return False

    if self.__class__ == AddRepoWindow:
        if self.values["encryption"] != "none":
            if len(self.values["password"]) < 8:
                self._set_status(self.tr("Please use a longer passphrase."))
                return False

    return True
# Buggy code
def process_new_repo(self, result):
    if result["returncode"] == 0:
        new_repo = RepoModel.get(url=result["params"]["repo_url"])
        profile = self.profile()
        profile.repo = new_repo.id
        profile.save()

        self.repoSelector.addItem(new_repo.url, new_repo.id)
        self.repoSelector.setCurrentIndex(self.repoSelector.count() - 1)
        self.repo_added.emit()
        self.init_repo_stats()


# Traceback (IndexError)
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/peewee.py", line 6665, in get
return clone.execute(database)[0]
File "/app/lib/python3.7/site-packages/peewee.py", line 4121, in __getitem__
return self.row_cache[item]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/vorta/application.py", line 80, in open_main_window_action
self.main_window = MainWindow(self)
File "/app/lib/python3.7/site-packages/vorta/views/main_window.py", line 37, in __init__
self.repoTab = RepoTab(self.repoTabSlot)
File "/app/lib/python3.7/site-packages/vorta/views/repo_tab.py", line 59, in __init__
self.init_repo_stats()
File "/app/lib/python3.7/site-packages/vorta/views/repo_tab.py", line 74, in init_repo_stats
repo = self.profile().repo
File "/app/lib/python3.7/site-packages/peewee.py", line 4269, in __get__
return self.get_rel_instance(instance)
File "/app/lib/python3.7/site-packages/peewee.py", line 4260, in get_rel_instance
obj = self.rel_model.get(self.field.rel_field == value)
File "/app/lib/python3.7/site-packages/peewee.py", line 6242, in get
return sq.get()
File "/app/lib/python3.7/site-packages/peewee.py", line 6670, in get
(clone.model, sql, params))
vorta.models.RepoModelDoesNotExist: <Model: RepoModel> instance matching query does not exist:
SQL: SELECT "t1"."id", "t1"."url", "t1"."added_at", "t1"."encryption", "t1"."unique_size", "t1"."unique_csize", "t1"."total_size", "t1"."total_unique_chunks", "t1"."extra_borg_arguments" FROM "repomodel" AS "t1" WHERE ("t1"."id" = ?) LIMIT ? OFFSET ?
Params: [1, 1, 0]

# Fixed code
def process_new_repo(self, result):
    if result["returncode"] == 0:
        new_repo = RepoModel.get(url=result["params"]["repo_url"])
        profile = self.profile()
        profile.repo = new_repo.id
        profile.save()

        self.set_repos()
        self.repoSelector.setCurrentIndex(self.repoSelector.count() - 1)
        self.repo_added.emit()
        self.init_repo_stats()
# Buggy code
def from_public_key_recovery(
    klass, signature, data, curve, hashfunc=sha1, sigdecode=sigdecode_string
):
    # Given a signature and corresponding message this function
    # returns a list of verifying keys for this signature and message

    digest = hashfunc(data).digest()
    return klass.from_public_key_recovery_with_digest(
        signature, digest, curve, hashfunc=sha1, sigdecode=sigdecode_string
    )


# Traceback (AssertionError)
correct 88546510979682037774707173221481493851486333744139811890585270440885638210651 25114176564622922097833533925221099216470038098832442934481636541806701930216

88546510979682037774707173221481493851486333744139811890585270440885638210651 25114176564622922097833533925221099216470038098832442934481636541806701930216
Traceback (most recent call last):
File "C:\Users\hasee\Desktop\test2.py", line 85, in <module>
signature=signature, data=data, curve=curve, sigdecode=ecdsa.util.sigdecode_der)
File "D:\anaconda3\envs\py37\lib\site-packages\ecdsa\keys.py", line 89, in from_public_key_recovery
return klass.from_public_key_recovery_with_digest(signature, digest, curve, hashfunc=sha1, sigdecode=sigdecode_string)
File "D:\anaconda3\envs\py37\lib\site-packages\ecdsa\keys.py", line 97, in from_public_key_recovery_with_digest
r, s = sigdecode(signature, generator.order())
File "D:\anaconda3\envs\py37\lib\site-packages\ecdsa\util.py", line 238, in sigdecode_string
assert len(signature) == 2 * l, (len(signature), 2 * l)
AssertionError: (71, 64)

# Fixed code
def from_public_key_recovery(
    klass, signature, data, curve, hashfunc=sha1, sigdecode=sigdecode_string
):
    # Given a signature and corresponding message this function
    # returns a list of verifying keys for this signature and message

    digest = hashfunc(data).digest()
    return klass.from_public_key_recovery_with_digest(
        signature, digest, curve, hashfunc=sha1, sigdecode=sigdecode
    )
# Buggy code
def __lt__(self, a):
    return self._path.__lt__(a)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/visidata/basesheet.py", line 136, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "sort-desc", line 1, in <module>
File "/usr/lib/python3.9/site-packages/visidata/sort.py", line 28, in orderBy
sheet.sort()
File "/usr/lib/python3.9/site-packages/visidata/sheets.py", line 983, in sort
self.rows[1:] = sorted(self.rows[1:], key=self.sortkey)
File "/usr/lib/python3.9/site-packages/visidata/sort.py", line 38, in __lt__
return other.obj < self.obj
TypeError: '<' not supported between instances of 'Path' and 'Path'

# Fixed code
def __lt__(self, a):
    if isinstance(a, visidata.Path):
        return self._path.__lt__(a._path)
    return self._path.__lt__(a)
# Buggy code
def vd_cli():
    vd.status(__version_info__)
    rc = -1
    try:
        rc = main_vd()
    except visidata.ExpectedException as e:
        print("Error: " + str(e))
    except FileNotFoundError as e:
        print(e)
        if options.debug:
            raise
    sys.stderr.flush()
    sys.stdout.flush()
    os._exit(rc)  # cleanup can be expensive with large datasets


# Traceback (BrokenPipeError)
seq 10000 | awk 'BEGIN{print "x,y"} {print $1","2*$1}' | vd -f csv -b - | head
opening - as csv
saving 1 sheets to - as tsv
x       y
1       2
2       4
3       6
4       8
5       10
6       12
7       14
8       16
9       18
Traceback (most recent call last):
File "/home/rob/envs/base/bin/vd", line 6, in <module>
visidata.main.vd_cli()
File "/home/rob/envs/base/lib/python3.8/site-packages/visidata/main.py", line 299, in vd_cli
rc = main_vd()
File "/home/rob/envs/base/lib/python3.8/site-packages/visidata/main.py", line 284, in main_vd
saveSheets(outpath, vd.sheets[0], confirm_overwrite=False)
File "/home/rob/envs/base/lib/python3.8/site-packages/visidata/vdobj.py", line 37, in _vdfunc
return func(visidata.vd, *args, **kwargs)
File "/home/rob/envs/base/lib/python3.8/site-packages/visidata/save.py", line 105, in saveSheets
return vd.execAsync(savefunc, givenpath, *vsheets)
File "/home/rob/envs/base/lib/python3.8/site-packages/visidata/main.py", line 198, in <lambda>
vd.execAsync = lambda func, *args, **kwargs: func(*args, **kwargs) # disable async
File "/home/rob/envs/base/lib/python3.8/site-packages/visidata/loaders/tsv.py", line 73, in save_tsv
fp.write(unitsep.join(dispvals.values()))
BrokenPipeError: [Errno 32] Broken pipe

# Fixed code
def vd_cli():
    vd.status(__version_info__)
    rc = -1
    try:
        rc = main_vd()
    except BrokenPipeError:
        os.dup2(
            os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno()
        )  # handle broken pipe gracefully
    except visidata.ExpectedException as e:
        print("Error: " + str(e))
    except FileNotFoundError as e:
        print(e)
        if options.debug:
            raise
    sys.stderr.flush()
    sys.stdout.flush()
    os._exit(rc)  # cleanup can be expensive with large datasets
# Buggy code
def setMacro(ks, vs):
    vd.macrobindings[ks] = vs
    BaseSheet.addCommand(ks, vs.name, "runMacro(vd.macrobindings[keystrokes])")


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/visidata/basesheet.py", line 136, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "macro-record", line 1, in <module>
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 52, in startMacro
vd.cmdlog.saveMacro(vd.macroMode.rows, ks)
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 37, in saveMacro
append_tsv_row(vd.macrosheet, (ks, macropath))
File "/usr/lib/python3.9/site-packages/visidata/loaders/tsv.py", line 81, in append_tsv_row
if not vs.source.exists():
AttributeError: 'NoneType' object has no attribute 'exists'

# Fixed code
def setMacro(ks, vs):
    vd.macrobindings[ks] = vs
    if vd.isLongname(ks):
        BaseSheet.addCommand("", ks, "runMacro(vd.macrobindings[longname])")
    else:
        BaseSheet.addCommand(ks, vs.name, "runMacro(vd.macrobindings[keystrokes])")
# Buggy code
def macrosheet(vd):
    macrospath = Path(os.path.join(options.visidata_dir, "macros.tsv"))
    macrosheet = vd.loadInternalSheet(
        TsvSheet,
        macrospath,
        columns=(ColumnItem("command", 0), ColumnItem("filename", 1)),
    ) or vd.error("error loading macros")

    real_macrosheet = IndexSheet("user_macros", rows=[])
    for ks, fn in macrosheet.rows:
        vs = vd.loadInternalSheet(CommandLog, Path(fn))
        vd.status(f"setting {ks}")
        setMacro(ks, vs)
        real_macrosheet.addRow(vs)

    return real_macrosheet


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/visidata/basesheet.py", line 136, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "macro-record", line 1, in <module>
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 52, in startMacro
vd.cmdlog.saveMacro(vd.macroMode.rows, ks)
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 37, in saveMacro
append_tsv_row(vd.macrosheet, (ks, macropath))
File "/usr/lib/python3.9/site-packages/visidata/loaders/tsv.py", line 81, in append_tsv_row
if not vs.source.exists():
AttributeError: 'NoneType' object has no attribute 'exists'

# Fixed code
def macrosheet(vd):
    macrospath = Path(os.path.join(options.visidata_dir, "macros.tsv"))
    macrosheet = vd.loadInternalSheet(
        TsvSheet,
        macrospath,
        columns=(ColumnItem("command", 0), ColumnItem("filename", 1)),
    ) or vd.error("error loading macros")

    real_macrosheet = IndexSheet("user_macros", rows=[], source=macrosheet)
    for ks, fn in macrosheet.rows:
        vs = vd.loadInternalSheet(CommandLog, Path(fn))
        vd.status(f"setting {ks}")
        setMacro(ks, vs)
        real_macrosheet.addRow(vs)

    return real_macrosheet
# Buggy code
def saveMacro(self, rows, ks):
    vs = copy(self)
    vs.rows = rows
    macropath = Path(fnSuffix(options.visidata_dir + "macro"))
    vd.save_vd(macropath, vs)
    setMacro(ks, vs)
    append_tsv_row(vd.macrosheet, (ks, macropath))


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3.9/site-packages/visidata/basesheet.py", line 136, in execCommand
exec(code, vdglobals, LazyChainMap(vd, self))
File "macro-record", line 1, in <module>
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 52, in startMacro
vd.cmdlog.saveMacro(vd.macroMode.rows, ks)
File "/usr/lib/python3.9/site-packages/visidata/macros.py", line 37, in saveMacro
append_tsv_row(vd.macrosheet, (ks, macropath))
File "/usr/lib/python3.9/site-packages/visidata/loaders/tsv.py", line 81, in append_tsv_row
if not vs.source.exists():
AttributeError: 'NoneType' object has no attribute 'exists'

# Fixed code
def saveMacro(self, rows, ks):
    vs = copy(self)
    vs.rows = rows
    macropath = Path(fnSuffix(options.visidata_dir + "macro"))
    vd.save_vd(macropath, vs)
    setMacro(ks, vs)
    append_tsv_row(vd.macrosheet.source, (ks, macropath))