gurudesh/pytracebugs huggingface dataset:
# Buggy code
def mark(self):
    """
    Mark this node as an alias node.
    """
    self.alias = True


# Traceback (KeyError)
INFO [py] launching openage v0.4.1-377-g2be30ba76
INFO [py] compiled by GNU 10.2.0
Do you want to convert assets? [Y/n]
Y
Should we call wine to determine an AOE installation? [Y/n]
n
Could not find any installation directory automatically.
Please enter an AOE2 install path manually.
/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/
converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE'
INFO [py] Game edition detected:
INFO [py]  * Age of Empires 2: Definitive Edition
INFO [py] converting metadata
INFO [py] [0] palette
INFO [py] [1] empires.dat
INFO [py] Starting conversion...
INFO [py] Extracting Genie data...
INFO [py] Creating API-like objects...
INFO [py] Linking API-like objects...
INFO [py] Generating auxiliary objects...
INFO [py] Creating nyan objects...
Traceback (most recent call last):
File "/usr/bin/openage", line 15, in <module>
main()
File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main
return args.entrypoint(args, cli.error)
File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main
used_asset_path = convert_assets(
File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets
for current_item in convert(args):
File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert
yield from convert_metadata(args)
File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata
modpacks = args.converter.convert(gamespec,
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert
modpacks = cls._post_processor(dataset)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor
DE2NyanSubprocessor.convert(full_data_set)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert
cls._process_game_entities(gamedata)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities
cls.tech_group_to_tech(tech_group)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech
patches.extend(DE2TechSubprocessor.get_patches(tech_group))
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches
patches.extend(cls.resource_modify_effect(converter_group,
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect
upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]
KeyError:  208

# Fixed code
def mark(self):
    """
    Mark this node as an alias node.
    """
    self.marked = True
# Buggy code
def unmark(self):
    """
    Unmark this node as an alias node.
    """
    self.alias = False


# Traceback (KeyError)
INFO [py] launching openage v0.4.1-377-g2be30ba76
INFO [py] compiled by GNU 10.2.0
Do you want to convert assets? [Y/n]
Y
Should we call wine to determine an AOE installation? [Y/n]
n
Could not find any installation directory automatically.
Please enter an AOE2 install path manually.
/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/
converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE'
INFO [py] Game edition detected:
INFO [py]  * Age of Empires 2: Definitive Edition
INFO [py] converting metadata
INFO [py] [0] palette
INFO [py] [1] empires.dat
INFO [py] Starting conversion...
INFO [py] Extracting Genie data...
INFO [py] Creating API-like objects...
INFO [py] Linking API-like objects...
INFO [py] Generating auxiliary objects...
INFO [py] Creating nyan objects...
Traceback (most recent call last):
File "/usr/bin/openage", line 15, in <module>
main()
File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main
return args.entrypoint(args, cli.error)
File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main
used_asset_path = convert_assets(
File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets
for current_item in convert(args):
File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert
yield from convert_metadata(args)
File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata
modpacks = args.converter.convert(gamespec,
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert
modpacks = cls._post_processor(dataset)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor
DE2NyanSubprocessor.convert(full_data_set)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert
cls._process_game_entities(gamedata)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities
cls.tech_group_to_tech(tech_group)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech
patches.extend(DE2TechSubprocessor.get_patches(tech_group))
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches
patches.extend(cls.resource_modify_effect(converter_group,
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect
upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]
KeyError:  208

# Fixed code
def unmark(self):
    """
    Unmark this node as an alias node.
    """
    self.marked = False
# Buggy code
def dump(self, import_tree=None):
    """
    Returns the string representation of the member.
    """
    return self.dump_short(import_tree=import_tree)


# Traceback (KeyError)
INFO [py] launching openage v0.4.1-377-g2be30ba76
INFO [py] compiled by GNU 10.2.0
Do you want to convert assets? [Y/n]
Y
Should we call wine to determine an AOE installation? [Y/n]
n
Could not find any installation directory automatically.
Please enter an AOE2 install path manually.
/home/schatzi/nvme/Steam/steamapps/common/AoE2DE/
converting from '/home/schatzi/nvme/Steam/steamapps/common/AoE2DE'
INFO [py] Game edition detected:
INFO [py]  * Age of Empires 2: Definitive Edition
INFO [py] converting metadata
INFO [py] [0] palette
INFO [py] [1] empires.dat
INFO [py] Starting conversion...
INFO [py] Extracting Genie data...
INFO [py] Creating API-like objects...
INFO [py] Linking API-like objects...
INFO [py] Generating auxiliary objects...
INFO [py] Creating nyan objects...
Traceback (most recent call last):
File "/usr/bin/openage", line 15, in <module>
main()
File "/usr/lib/python3.9/site-packages/openage/__main__.py", line 132, in main
return args.entrypoint(args, cli.error)
File "/usr/lib/python3.9/site-packages/openage/game/main.py", line 71, in main
used_asset_path = convert_assets(
File "/usr/lib/python3.9/site-packages/openage/convert/main.py", line 100, in convert_assets
for current_item in convert(args):
File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 48, in convert
yield from convert_metadata(args)
File "/usr/lib/python3.9/site-packages/openage/convert/tool/driver.py", line 96, in convert_metadata
modpacks = args.converter.convert(gamespec,
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 63, in convert
modpacks = cls._post_processor(dataset)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/processor.py", line 153, in _post_processor
DE2NyanSubprocessor.convert(full_data_set)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 38, in convert
cls._process_game_entities(gamedata)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 120, in _process_game_entities
cls.tech_group_to_tech(tech_group)
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/nyan_subprocessor.py", line 596, in tech_group_to_tech
patches.extend(DE2TechSubprocessor.get_patches(tech_group))
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 147, in get_patches
patches.extend(cls.resource_modify_effect(converter_group,
File "/usr/lib/python3.9/site-packages/openage/convert/processor/conversion/de2/tech_subprocessor.py", line 276, in resource_modify_effect
upgrade_func = DE2TechSubprocessor.upgrade_resource_funcs[resource_id]
KeyError:  208

# Fixed code
def dump(self, indent_depth, import_tree=None, namespace=None):
    """
    Returns the string representation of the member.
    """
    return self.dump_short(indent_depth, import_tree=import_tree, namespace=namespace)
# Buggy code
def main(args, error):
    """CLI entry point"""
    del error  # unused

    # initialize libopenage
    from ..cppinterface.setup import setup

    setup(args)

    # conversion source
    if args.source_dir is not None:
        srcdir = CaseIgnoringDirectory(args.source_dir).root
    else:
        srcdir = None

    # Set verbosity for debug output
    if not args.debug_info:
        if args.devmode:
            args.debug_info = 3

        else:
            args.debug_info = 0

    # mount the config folder at "cfg/"
    from ..cvar.location import get_config_path
    from ..util.fslike.union import Union

    root = Union().root
    root["cfg"].mount(get_config_path())
    args.cfg_dir = root["cfg"]

    if args.interactive:
        interactive_browser(root["cfg"], srcdir)
        return 0

    # conversion target
    from ..assets import get_asset_path

    outdir = get_asset_path(args.output_dir)

    if args.force or wanna_convert() or conversion_required(outdir, args):
        if not convert_assets(outdir, args, srcdir):
            return 1
    else:
        print("assets are up to date; no conversion is required.")
        print("override with --force.")

    return 0


# Traceback (AttributeError)
INFO [py] launching openage v0.4.1-371-g0c6e704b
INFO [py] compiled by GNU 10.2.0
Do you want to convert assets? [Y/n]
y
Traceback (most recent call last):
File "/app/bin/openage", line 15, in <module>
main()
File "/app/lib/python3.8/site-packages/openage/__main__.py", line 132, in main
return args.entrypoint(args, cli.error)
File "/app/lib/python3.8/site-packages/openage/game/main.py", line 68, in main
used_asset_path = convert_assets(root["assets"], root["cfg"], args,
File "/app/lib/python3.8/site-packages/openage/convert/main.py", line 52, in convert_assets
debug_cli_args(args.debugdir, args.debug_info, args)
AttributeError: 'UnionPath' object has no attribute 'debug_info'

# Fixed code
def main(args, error):
    """CLI entry point"""
    del error  # unused

    # initialize libopenage
    from ..cppinterface.setup import setup

    setup(args)

    # conversion source
    if args.source_dir is not None:
        srcdir = CaseIgnoringDirectory(args.source_dir).root
    else:
        srcdir = None

    # mount the config folder at "cfg/"
    from ..cvar.location import get_config_path
    from ..util.fslike.union import Union

    root = Union().root
    root["cfg"].mount(get_config_path())
    args.cfg_dir = root["cfg"]

    if args.interactive:
        interactive_browser(root["cfg"], srcdir)
        return 0

    # conversion target
    from ..assets import get_asset_path

    outdir = get_asset_path(args.output_dir)

    if args.force or wanna_convert() or conversion_required(outdir, args):
        if not convert_assets(outdir, args, srcdir):
            return 1
    else:
        print("assets are up to date; no conversion is required.")
        print("override with --force.")

    return 0
# Buggy code
def save_slp(path, target, palette=None):
    """
    save a slp as png.
    """
    from .texture import Texture
    from .slp import SLP
    from .driver import get_palette

    if not palette:
        palette = get_palette(data, game_versions)

    with path.open("rb") as slpfile:
        tex = Texture(SLP(slpfile.read()), palette)

        out_path, filename = os.path.split(target)
        tex.save(Directory(out_path).root, filename)


# Traceback (ValueError)
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png
INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'...
INFO parsing slp image...
INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'...
INFO parsing palette data...
INFO packing texture...
Traceback (most recent call last):
File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/dev/openage/openage/__main__.py", line 128, in <module>
exit(main())
File "/home/dev/openage/openage/__main__.py", line 121, in main
return args.entrypoint(args, cli.error)
File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main
tex.save(Directory(path).root, filename)
File "/home/dev/openage/openage/convert/texture.py", line 170, in save
raise ValueError("Texture must be saved as name.png. got: %s" % filename)
ValueError: Texture must be saved as name.png. got: test

# Fixed code
def save_slp(path, target, palette=None):
    """
    save a slp as png.
    """
    from .texture import Texture
    from .slp import SLP
    from .driver import get_palette

    if not palette:
        palette = get_palette(data)

    with path.open("rb") as slpfile:
        tex = Texture(SLP(slpfile.read()), palette)

        out_path, filename = os.path.split(target)
        tex.save(Directory(out_path).root, filename)
# Buggy code
def main(args, error):
    """CLI entry point"""
    del error  # unused

    # initialize libopenage
    from ..cppinterface.setup import setup

    setup(args)

    # conversion source
    if args.source_dir is not None:
        srcdir = CaseIgnoringDirectory(args.source_dir).root
    else:
        srcdir = None

    if args.interactive:
        interactive_browser(srcdir)
        return 0

    # conversion target
    from ..assets import get_asset_path

    assets = get_asset_path(args)

    if args.force or conversion_required(assets, args):
        if not convert_assets(assets, args, srcdir):
            return 1
    else:
        print("assets are up to date; no conversion is required.")
        print("override with --force.")


# Traceback (ValueError)
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png
INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'...
INFO parsing slp image...
INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'...
INFO parsing palette data...
INFO packing texture...
Traceback (most recent call last):
File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/dev/openage/openage/__main__.py", line 128, in <module>
exit(main())
File "/home/dev/openage/openage/__main__.py", line 121, in main
return args.entrypoint(args, cli.error)
File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main
tex.save(Directory(path).root, filename)
File "/home/dev/openage/openage/convert/texture.py", line 170, in save
raise ValueError("Texture must be saved as name.png. got: %s" % filename)
ValueError: Texture must be saved as name.png. got: test

# Fixed code
def main(args, error):
    """CLI entry point"""
    del error  # unused

    # initialize libopenage
    from ..cppinterface.setup import setup

    setup(args)

    # conversion source
    if args.source_dir is not None:
        srcdir = CaseIgnoringDirectory(args.source_dir).root
    else:
        srcdir = None

    if args.interactive:
        interactive_browser(srcdir)
        return 0

    # conversion target
    from ..assets import get_asset_path

    outdir = get_asset_path(args.output_dir)

    if args.force or conversion_required(outdir, args):
        if not convert_assets(outdir, args, srcdir):
            return 1
    else:
        print("assets are up to date; no conversion is required.")
        print("override with --force.")
# Buggy code
def init_subparser(cli):
    """Initializes the parser for convert-specific args."""
    cli.set_defaults(entrypoint=main)

    cli.add_argument("--palette", default="50500", help="palette number")
    cli.add_argument(
        "--interfac", help=("drs archive where palette is contained (interfac.drs)")
    )
    cli.add_argument(
        "drs",
        help=(
            "drs archive filename that contains the slp "
            "e.g. path ~/games/aoe/graphics.drs"
        ),
    )
    cli.add_argument("slp", help=("slp filename inside the drs archive e.g. 326.slp"))
    cli.add_argument("output", help="image output path name")


# Traceback (ValueError)
dev@openage:~/openage$ python3 -m openage convert-file /home/dev/aoe1/data/Border.drs 20000.slp /home/dev/aoe1/data/test.png
INFO opening slp in drs '/home/dev/aoe1/data/Border.drs:20000.slp'...
INFO parsing slp image...
INFO opening palette in drs '/home/dev/aoe1/data/interfac.drs:50500.bin'...
INFO parsing palette data...
INFO packing texture...
Traceback (most recent call last):
File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/dev/openage/openage/__main__.py", line 128, in <module>
exit(main())
File "/home/dev/openage/openage/__main__.py", line 121, in main
return args.entrypoint(args, cli.error)
File "/home/dev/openage/openage/convert/singlefile.py", line 72, in main
tex.save(Directory(path).root, filename)
File "/home/dev/openage/openage/convert/texture.py", line 170, in save
raise ValueError("Texture must be saved as name.png. got: %s" % filename)
ValueError: Texture must be saved as name.png. got: test

# Fixed code
def init_subparser(cli):
    """Initializes the parser for convert-specific args."""
    import argparse

    cli.set_defaults(entrypoint=main)

    cli.add_argument("--palette", default="50500", help="palette number")
    cli.add_argument(
        "--interfac",
        type=argparse.FileType("rb"),
        help=(
            "drs archive where palette "
            "is contained (interfac.drs). "
            "If not set, assumed to be in same "
            "directory as the source drs archive"
        ),
    )
    cli.add_argument(
        "drs",
        type=argparse.FileType("rb"),
        help=(
            "drs archive filename that contains the slp "
            "e.g. path ~/games/aoe/graphics.drs"
        ),
    )
    cli.add_argument("slp", help=("slp filename inside the drs archive e.g. 326.slp"))
    cli.add_argument("output", help="image output path name")
# Buggy code
def authenticate(self, username=None, password=None):
    """Check the username/password and return a User."""
    host = getattr(settings, "AUTH_SMTP_SERVER_ADDRESS", "localhost")
    port = getattr(settings, "AUTH_SMTP_SERVER_PORT", 25)
    secured_mode = getattr(settings, "AUTH_SMTP_SECURED_MODE", None)
    if secured_mode == "ssl":
        smtp = smtplib.SMTP_SSL(host, port)
    else:
        smtp = smtplib.SMTP(host, port)
        if secured_mode == "starttls":
            smtp.starttls()
    try:
        smtp.login(username, password)
    except smtplib.SMTPException:
        return None
    return self.get_or_build_user(username)


# Traceback (TypeError)
Internal Server Error: /accounts/login/
Traceback (most recent call last):
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner
return func(*args, **kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner
return func(*args, **kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py", line 34, in dologin
password=form.cleaned_data["password"])
File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 70, in authenticate
user = _authenticate_with_backend(backend, backend_path, request, credentials)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 116, in _authenticate_with_backend
return backend.authenticate(*args, **credentials)
File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py", line 119, in authenticate
username=username, password=password)
TypeError: authenticate() takes at least 2 arguments (3 given)

# Fixed code
def authenticate(self, request, username=None, password=None):
    """Check the username/password and return a User."""
    host = getattr(settings, "AUTH_SMTP_SERVER_ADDRESS", "localhost")
    port = getattr(settings, "AUTH_SMTP_SERVER_PORT", 25)
    secured_mode = getattr(settings, "AUTH_SMTP_SECURED_MODE", None)
    if secured_mode == "ssl":
        smtp = smtplib.SMTP_SSL(host, port)
    else:
        smtp = smtplib.SMTP(host, port)
        if secured_mode == "starttls":
            smtp.starttls()
    try:
        smtp.login(username, password)
    except smtplib.SMTPException:
        return None
    return self.get_or_build_user(username)
# Buggy code
def authenticate(self, username, password):
    if self.global_params["authentication_type"] == "ldap":
        return super(LDAPBackend, self).authenticate(
            username=username, password=password
        )
    return None


# Traceback (TypeError)
Internal Server Error: /accounts/login/
Traceback (most recent call last):
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner
return func(*args, **kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner
return func(*args, **kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/core/views/auth.py", line 34, in dologin
password=form.cleaned_data["password"])
File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 70, in authenticate
user = _authenticate_with_backend(backend, backend_path, request, credentials)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 116, in _authenticate_with_backend
return backend.authenticate(*args, **credentials)
File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/lib/authbackends.py", line 119, in authenticate
username=username, password=password)
TypeError: authenticate() takes at least 2 arguments (3 given)

# Fixed code
def authenticate(self, *args, **kwargs):
    if self.global_params["authentication_type"] == "ldap":
        return super(LDAPBackend, self).authenticate(*args, **kwargs)
    return None
# Buggy code
def handle(self, *args, **options):
    exts_pool.load_all()
    self.csvwriter = csv.writer(sys.stdout, delimiter=options["sepchar"])
    getattr(self, "export_{}".format(options["objtype"]))()


# Traceback (TypeError)
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py", line 53, in run_from_argv
return super(SubcommandCommand, self).run_from_argv(argv)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/subcommand/base.py", line 84, in handle
return command.run_from_argv(argv)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_export.py", line 64, in handle
self.csvwriter = csv.writer(sys.stdout, delimiter=options["sepchar"])
File "/srv/modoboa/env/local/lib/python2.7/site-packages/backports/csv.py", line 185, in __init__
raise TypeError(*e.args)
TypeError: "delimiter" must be string, not bytes

# Fixed code
def handle(self, *args, **options):
    exts_pool.load_all()
    self.csvwriter = csv.writer(self.stdout, delimiter=smart_text(options["sepchar"]))
    getattr(self, "export_{}".format(options["objtype"]))()
# Buggy code
def get_mail_content(self, mailid):
    """Retrieve the content of a message."""
    return Quarantine.objects.filter(mail=mailid)


# Traceback (DataError)
Traceback (most recent call last):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f
return f(request, *args, **kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent
mail = SQLemail(mail_id, mformat="plain", links="0")

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__
{"name": label, "value": self.get_header(self.msg, f)}

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg
mail_text = "".join([qm.mail_text for qm in qmails])

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__
self._fetch_all()

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)

DataError: invalid byte sequence for encoding "UTF8": 0xb3

# Fixed code
def get_mail_content(self, mailid):
    """Retrieve the content of a message."""
    content = "".join(
        [str(qmail.mail_text) for qmail in Quarantine.objects.filter(mail=mailid)]
    )
    if isinstance(content, unicode):
        content = content.encode("utf-8")
    return content
# Buggy code
def get_mail_content(self, mailid):
    """Retrieve the content of a message."""
    return Quarantine.objects.filter(mail=mailid).extra(
        select={"mail_text": "convert_from(mail_text, 'UTF8')"}
    )


# Traceback (DataError)
Traceback (most recent call last):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f
return f(request, *args, **kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent
mail = SQLemail(mail_id, mformat="plain", links="0")

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__
{"name": label, "value": self.get_header(self.msg, f)}

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg
mail_text = "".join([qm.mail_text for qm in qmails])

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__
self._fetch_all()

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)

DataError: invalid byte sequence for encoding "UTF8": 0xb3

# Fixed code
def get_mail_content(self, mailid):
    """Retrieve the content of a message."""
    content = "".join(
        [str(qmail.mail_text) for qmail in Quarantine.objects.filter(mail=mailid)]
    )
    if isinstance(content, unicode):
        content = content.encode("utf-8")
    return content
# Buggy code
def msg(self):
    """Get message's content."""
    import email

    if self._msg is None:
        qmails = get_connector().get_mail_content(self.mailid)
        mail_text = "".join([qm.mail_text for qm in qmails])
        if type(mail_text) is unicode:
            mail_text = mail_text.encode("utf-8")
        self._msg = email.message_from_string(mail_text)
        self._parse(self._msg)
    return self._msg


# Traceback (DataError)
Traceback (most recent call last):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/lib.py", line 36, in wrapped_f
return f(request, *args, **kwargs)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/views.py", line 135, in getmailcontent
mail = SQLemail(mail_id, mformat="plain", links="0")

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 23, in __init__
{"name": label, "value": self.get_header(self.msg, f)}

File "/srv/modoboa/env/local/lib/python2.7/site-packages/modoboa/extensions/amavis/sql_email.py", line 44, in msg
mail_text = "".join([qm.mail_text for qm in qmails])

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 96, in __iter__
self._fetch_all()

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 713, in results_iter
for rows in self.execute_sql(MULTI):

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/models/sql/compiler.py", line 786, in execute_sql
cursor.execute(sql, params)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/srv/modoboa/env/local/lib/python2.7/site-packages/Django-1.6.8-py2.7.egg/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)

DataError: invalid byte sequence for encoding "UTF8": 0xb3

# Fixed code
def msg(self):
    """Get message's content."""
    import email

    if self._msg is None:
        mail_text = get_connector().get_mail_content(self.mailid)
        self._msg = email.message_from_string(mail_text)
        self._parse(self._msg)
    return self._msg
# Buggy code
def get_password_hasher(scheme):
    """Retrieve the hasher corresponding to :keyword:`scheme`.

    If no class is found, `PLAINHasher` is returned.

    :param str scheme: a valid scheme name
    :rtype: PasswordHasher sub class
    :return: The hasher class
    """
    try:
        scheme = scheme.replace("-", "")
        hasher = globals()["%sHasher" % scheme]
    except AttributeError:
        hasher = PLAINHasher
    return hasher


# Traceback (KeyError)
Traceback (most recent call last):

File "/srv/python-envs/service/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)

File "/srv/python-envs/service/lib/python2.7/site-packages/django/views/decorators/cache.py", line 89, in _wrapped_view_func
response = view_func(request, *args, **kwargs)

File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/views/auth.py", line 20, in dologin
password=form.cleaned_data["password"])

File "/srv/python-envs/service/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 60, in authenticate
user = backend.authenticate(**credentials)

File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/lib/authbackends.py", line 14, in authenticate
if not user.check_password(password):

File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/models.py", line 134, in check_password
hasher = get_password_hasher(scheme)

File "/srv/python-envs/service/lib/python2.7/site-packages/modoboa-1.1.0-py2.7.egg/modoboa/core/password_hashers/__init__.py", line 23, in get_password_hasher
hasher = globals()['%sHasher' % scheme]

KeyError: u'plainHasher'

# Fixed code
def get_password_hasher(scheme):
    """Retrieve the hasher corresponding to :keyword:`scheme`.

    If no class is found, `PLAINHasher` is returned.

    :param str scheme: a valid scheme name
    :rtype: PasswordHasher sub class
    :return: The hasher class
    """
    try:
        scheme = scheme.replace("-", "")
        hasher = globals()["%sHasher" % scheme.upper()]
    except KeyError:
        hasher = PLAINHasher
    return hasher
# Buggy code
def get_dependent_plate_dims(sites):
    """
    Return a list of dims for plates that are not common to all sites.
    """
    plate_sets = [
        site["cond_indep_stack"] for site in sites if site["type"] == "sample"
    ]
    all_plates = set().union(*plate_sets)
    common_plates = all_plates.intersection(*plate_sets)
    sum_plates = all_plates - common_plates
    sum_dims = list(sorted(f.dim for f in sum_plates))
    return sum_dims


# Traceback (TypeError)
3.8.1 (default, Jan  8 2020, 16:15:59)
[Clang 4.0.1 (tags/RELEASE_401/final)] 1.4.0 1.3.0
2.4235687255859375
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-6865281f40fd> in <module>
15
16 elbo = pyro.infer.RenyiELBO()
---> 17 print(elbo.loss(model, guide, torch.randn([3])))

~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/torch/autograd/grad_mode.py in decorate_no_grad(*args, **kwargs)
47         def decorate_no_grad(*args, **kwargs):
48             with self:
---> 49                 return func(*args, **kwargs)
50         return decorate_no_grad
51

~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/renyi_elbo.py in loss(self, model, guide, *args, **kwargs)
96         for model_trace, guide_trace in self._get_traces(model, guide, args, kwargs):
97             elbo_particle = 0.
---> 98             sum_dims = get_dependent_plate_dims(model_trace.nodes.values())
99
100             # compute elbo

~/miniconda3/envs/pDCM-dev/lib/python3.8/site-packages/pyro/infer/util.py in get_dependent_plate_dims(sites)
114     common_plates = all_plates.intersection(*plate_sets)
115     sum_plates = all_plates - common_plates
--> 116     sum_dims = list(sorted(f.dim for f in sum_plates))
117     return sum_dims
118

TypeError: '<' not supported between instances of 'NoneType' and 'NoneType'

# Fixed code
def get_dependent_plate_dims(sites):
    """
    Return a list of dims for plates that are not common to all sites.
    """
    plate_sets = [
        site["cond_indep_stack"] for site in sites if site["type"] == "sample"
    ]
    all_plates = set().union(*plate_sets)
    common_plates = all_plates.intersection(*plate_sets)
    sum_plates = all_plates - common_plates
    sum_dims = list(sorted(f.dim for f in sum_plates if f.dim is not None))
    return sum_dims
# Buggy code
def get_posterior(self, *args, **kwargs):
    """
    Returns a MultivariateNormal posterior distribution.
    """
    loc = pyro.param("{}_loc".format(self.prefix), lambda: torch.zeros(self.latent_dim))
    scale_tril = pyro.param(
        "{}_scale_tril".format(self.prefix),
        lambda: torch.eye(self.latent_dim),
        constraint=constraints.lower_cholesky,
    )
    return dist.MultivariateNormal(loc, scale_tril=scale_tril)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-6-68d49e4377f9>", line 26, in <module>
train()
File "<ipython-input-6-68d49e4377f9>", line 23, in train
svi.step(xs, prior_loc, prior_scale)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step
loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads
surrogate_loss_particle.backward(retain_graph=self.retain_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward
allow_unreachable=True)  # allow_unreachable flag
RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor

# Fixed code
def get_posterior(self, *args, **kwargs):
    """
    Returns a MultivariateNormal posterior distribution.
    """
    loc = pyro.param("{}_loc".format(self.prefix), self._init_loc)
    scale_tril = pyro.param(
        "{}_scale_tril".format(self.prefix),
        lambda: eye_like(loc, self.latent_dim),
        constraint=constraints.lower_cholesky,
    )
    return dist.MultivariateNormal(loc, scale_tril=scale_tril)
# Buggy code
def get_posterior(self, *args, **kwargs):
    """
    Returns a diagonal Normal posterior distribution.
    """
    loc = pyro.param("{}_loc".format(self.prefix), lambda: torch.zeros(self.latent_dim))
    scale = pyro.param(
        "{}_scale".format(self.prefix),
        lambda: torch.ones(self.latent_dim),
        constraint=constraints.positive,
    )
    return dist.Normal(loc, scale).to_event(1)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-6-68d49e4377f9>", line 26, in <module>
train()
File "<ipython-input-6-68d49e4377f9>", line 23, in train
svi.step(xs, prior_loc, prior_scale)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step
loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads
surrogate_loss_particle.backward(retain_graph=self.retain_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward
allow_unreachable=True)  # allow_unreachable flag
RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor

# Fixed code
def get_posterior(self, *args, **kwargs):
    """
    Returns a diagonal Normal posterior distribution.
    """
    loc = pyro.param("{}_loc".format(self.prefix), self._init_loc)
    scale = pyro.param(
        "{}_scale".format(self.prefix),
        lambda: loc.new_ones(self.latent_dim),
        constraint=constraints.positive,
    )
    return dist.Normal(loc, scale).to_event(1)
# Buggy code
def __init__(self, model, prefix="auto", rank=1):
    if not isinstance(rank, numbers.Number) or not rank > 0:
        raise ValueError("Expected rank > 0 but got {}".format(rank))
    self.rank = rank
    super(AutoLowRankMultivariateNormal, self).__init__(model, prefix)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-6-68d49e4377f9>", line 26, in <module>
train()
File "<ipython-input-6-68d49e4377f9>", line 23, in train
svi.step(xs, prior_loc, prior_scale)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step
loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads
surrogate_loss_particle.backward(retain_graph=self.retain_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward
allow_unreachable=True)  # allow_unreachable flag
RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor

# Fixed code
def __init__(self, model, prefix="auto", init_loc_fn=init_to_median, rank=1):
    if not isinstance(rank, numbers.Number) or not rank > 0:
        raise ValueError("Expected rank > 0 but got {}".format(rank))
    self.rank = rank
    super(AutoLowRankMultivariateNormal, self).__init__(
        model, prefix=prefix, init_loc_fn=init_loc_fn
    )
# Buggy code
def get_posterior(self, *args, **kwargs):
    """
    Returns a LowRankMultivariateNormal posterior distribution.
    """
    loc = pyro.param("{}_loc".format(self.prefix), lambda: torch.zeros(self.latent_dim))
    factor = pyro.param(
        "{}_cov_factor".format(self.prefix),
        lambda: torch.randn(self.latent_dim, self.rank) * (0.5 / self.rank) ** 0.5,
    )
    diagonal = pyro.param(
        "{}_cov_diag".format(self.prefix),
        lambda: torch.ones(self.latent_dim) * 0.5,
        constraint=constraints.positive,
    )
    return dist.LowRankMultivariateNormal(loc, factor, diagonal)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\IPython\core\interactiveshell.py", line 3265, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-6-68d49e4377f9>", line 26, in <module>
train()
File "<ipython-input-6-68d49e4377f9>", line 23, in train
svi.step(xs, prior_loc, prior_scale)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\svi.py", line 99, in step
loss = self.loss_and_grads(self.model, self.guide, *args, **kwargs)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\pyro\infer\trace_elbo.py", line 136, in loss_and_grads
surrogate_loss_particle.backward(retain_graph=self.retain_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\tensor.py", line 107, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "C:\tools\miniconda3\envs\scanner-pyro\lib\site-packages\torch\autograd\__init__.py", line 93, in backward
allow_unreachable=True)  # allow_unreachable flag
RuntimeError: Function AddBackward0 returned an invalid gradient at index 1 - expected type torch.cuda.FloatTensor but got torch.FloatTensor

# Fixed code
def get_posterior(self, *args, **kwargs):
    """
    Returns a LowRankMultivariateNormal posterior distribution.
    """
    loc = pyro.param("{}_loc".format(self.prefix), self._init_loc)
    factor = pyro.param(
        "{}_cov_factor".format(self.prefix),
        lambda: loc.new_empty(self.latent_dim, self.rank).normal_(
            0, (0.5 / self.rank) ** 0.5
        ),
    )
    diagonal = pyro.param(
        "{}_cov_diag".format(self.prefix),
        lambda: loc.new_full((self.latent_dim,), 0.5),
        constraint=constraints.positive,
    )
    return dist.LowRankMultivariateNormal(loc, factor, diagonal)