gurudesh/pytracebugs huggingface dataset:
# Buggy code
def run_simulation(
    fragment_or_module,
    generators,
    clocks={"sync": 10},
    vcd_name=None,
    special_overrides={},
):
    assert not special_overrides

    if hasattr(fragment_or_module, "get_fragment"):
        fragment = fragment_or_module.get_fragment()
    else:
        fragment = fragment_or_module

    if not isinstance(generators, dict):
        generators = {"sync": generators}
        fragment.domains += ClockDomain("sync")

    sim = Simulator(fragment)
    for domain, period in clocks.items():
        sim.add_clock(period / 1e9, domain=domain)
    for domain, processes in generators.items():

        def wrap(process):
            def wrapper():
                yield from process

            return wrapper

        if isinstance(processes, Iterable) and not inspect.isgenerator(processes):
            for process in processes:
                sim.add_sync_process(wrap(process), domain=domain)
        else:
            sim.add_sync_process(wrap(processes), domain=domain)

    if vcd_name is not None:
        with sim.write_vcd(vcd_name):
            sim.run()
    else:
        sim.run()


# Traceback (AttributeError)
Traceback (most recent call last):
File "src/test_run_simulation_bug.py", line 28, in <module>
test1()
File "src/test_run_simulation_bug.py", line 24, in test1
vcd_name="test_run_simulation_bug.vcd")
File "/home/jacob/projects/nmigen/nmigen/compat/sim/__init__.py", line 22, in run_simulation
fragment.domains += ClockDomain("sync")
AttributeError: 'MyModule' object has no attribute 'domains'

# Fixed code
def run_simulation(
    fragment_or_module,
    generators,
    clocks={"sync": 10},
    vcd_name=None,
    special_overrides={},
):
    assert not special_overrides

    if hasattr(fragment_or_module, "get_fragment"):
        fragment = fragment_or_module.get_fragment()
    else:
        fragment = fragment_or_module

    fragment = Fragment.get(fragment, platform=None)

    if not isinstance(generators, dict):
        generators = {"sync": generators}
        if "sync" not in fragment.domains:
            fragment.add_domains(ClockDomain("sync"))

    sim = Simulator(fragment)
    for domain, period in clocks.items():
        sim.add_clock(period / 1e9, domain=domain)
    for domain, processes in generators.items():

        def wrap(process):
            def wrapper():
                yield from process

            return wrapper

        if isinstance(processes, Iterable) and not inspect.isgenerator(processes):
            for process in processes:
                sim.add_sync_process(wrap(process), domain=domain)
        else:
            sim.add_sync_process(wrap(processes), domain=domain)

    if vcd_name is not None:
        with sim.write_vcd(vcd_name):
            sim.run()
    else:
        sim.run()
# Buggy code
def build(self, **kwargs):
    checkout_path = self.project.checkout_path(self.version.slug)
    build_command = [
        self.project.venv_bin(version=self.version.slug, bin="mkdocs"),
        self.builder,
        "--clean",
        "--site-dir",
        self.build_dir,
    ]
    if self.use_theme:
        build_command.extend(["--theme", "readthedocs"])
    cmd_ret = self.run(*build_command, cwd=checkout_path)
    return cmd_ret.successful


# Traceback (OSError)
doc_builder
-----

Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/readthedocs/projects/utils.py", line 85, in run
stderr=subprocess.PIPE, env=environment)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def build(self, **kwargs):
    checkout_path = self.project.checkout_path(self.version.slug)
    build_command = [
        "python",
        self.project.venv_bin(version=self.version.slug, bin="mkdocs"),
        self.builder,
        "--clean",
        "--site-dir",
        self.build_dir,
    ]
    if self.use_theme:
        build_command.extend(["--theme", "readthedocs"])
    cmd_ret = self.run(
        *build_command,
        cwd=checkout_path,
        bin_path=self.project.venv_bin(version=self.version.slug, bin=None),
    )
    return cmd_ret.successful
# Buggy code
def __init__(
    self,
    command,
    cwd=None,
    shell=False,
    environment=None,
    combine_output=True,
    input_data=None,
    build_env=None,
):
    self.command = command
    self.shell = shell
    if cwd is None:
        cwd = os.getcwd()
    self.cwd = cwd
    self.environment = os.environ.copy()
    if environment is not None:
        self.environment.update(environment)
    self.combine_output = combine_output
    self.build_env = build_env
    self.status = None
    self.input_data = input_data
    self.output = None
    self.error = None


# Traceback (OSError)
doc_builder
-----

Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/readthedocs/projects/utils.py", line 85, in run
stderr=subprocess.PIPE, env=environment)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def __init__(
    self,
    command,
    cwd=None,
    shell=False,
    environment=None,
    combine_output=True,
    input_data=None,
    build_env=None,
    bin_path=None,
):
    self.command = command
    self.shell = shell
    if cwd is None:
        cwd = os.getcwd()
    self.cwd = cwd
    self.environment = os.environ.copy()
    if environment is not None:
        self.environment.update(environment)
    self.combine_output = combine_output
    self.build_env = build_env
    self.bin_path = bin_path
    self.status = None
    self.input_data = input_data
    self.output = None
    self.error = None
# Buggy code
def venv_bin(self, version=LATEST, bin="python"):
    return os.path.join(self.venv_path(version), "bin", bin)


# Traceback (OSError)
doc_builder
-----

Traceback (most recent call last):
File "/home/docs/checkouts/readthedocs.org/readthedocs/projects/utils.py", line 85, in run
stderr=subprocess.PIPE, env=environment)
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def venv_bin(self, version=LATEST, bin="python"):
    """Return path to the virtualenv bin path, or a specific binary

    By default, return the path to the ``python`` binary in the virtual
    environment path. If ``bin`` is :py:data:`None`, then return the path to
    the virtual env path.
    """
    if bin is None:
        bin = ""
    return os.path.join(self.venv_path(version), "bin", bin)
# Buggy code
def dnf_autoremove():
    """Run 'dnf autoremove' and return size in bytes recovered"""
    if os.path.exists("/var/run/dnf.pid"):
        msg = (
            _(
                "%s cannot be cleaned because it is currently running.  Close it, and try again."
            )
            % "Dnf"
        )
        raise RuntimeError(msg)
    cmd = ["dnf", "-y", "autoremove"]
    process = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    freed_bytes = 0
    while True:
        line = process.stdout.readline().replace("\n", "")
        if "Error: This command has to be run under the root user." == line:
            raise RuntimeError("dnf autoremove >> requires root permissions")
        if "Nothing to do." == line:
            break
        cregex = re.compile("Freed space: ([\d.]+[\s]+[BkMG])")
        match = cregex.search(line)
        if match:
            freed_bytes = parseSize(match.group(1))
            break
        if "" == line and process.poll() != None:
            break
    logger.debug("dnf_autoremove >> total freed bytes: %s", freed_bytes)
    return freed_bytes


# Traceback (TypeError)
↪ sudo bleachbit
closest monitor (0) geometry = (0, 0)+(3840, 2160), window geometry = (1520, 766)+(1441, 978)
Error: dnf.autoremove: Function: dnf autoremove
Traceback (most recent call last):
File "/usr/share/bleachbit/Worker.py", line 87, in execute
for ret in cmd.execute(self.really_delete):
File "/usr/share/bleachbit/Command.py", line 142, in execute
func_ret = self.func()
File "/usr/share/bleachbit/Unix.py", line 717, in dnf_autoremove
line = process.stdout.readline().replace("\n", "")
TypeError: a bytes-like object is required, not 'str'
subprocess 18280 is still running

<exit code 0>

# Fixed code
def dnf_autoremove():
    """Run 'dnf autoremove' and return size in bytes recovered"""
    if os.path.exists("/var/run/dnf.pid"):
        msg = (
            _(
                "%s cannot be cleaned because it is currently running.  Close it, and try again."
            )
            % "Dnf"
        )
        raise RuntimeError(msg)
    cmd = ["dnf", "-y", "autoremove"]
    process = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
    freed_bytes = 0
    while True:
        line = (
            process.stdout.readline()
            .decode(bleachbit.stdout_encoding)
            .replace("\n", "")
        )
        if "Error: This command has to be run under the root user." == line:
            raise RuntimeError("dnf autoremove >> requires root permissions")
        if "Nothing to do." == line:
            break
        cregex = re.compile("Freed space: ([\d.]+[\s]+[BkMG])")
        match = cregex.search(line)
        if match:
            freed_bytes = parseSize(match.group(1))
            break
        if "" == line and process.poll() != None:
            break
    logger.debug("dnf_autoremove >> total freed bytes: %s", freed_bytes)
    return freed_bytes
# Buggy code
def delete_ooo_history(path):
    """Erase the OpenOffice.org MRU in Common.xcu.  No longer valid in Apache OpenOffice.org 3.4."""
    import xml.dom.minidom

    dom1 = xml.dom.minidom.parse(path)
    changed = False
    for node in dom1.getElementsByTagName("node"):
        if node.hasAttribute("oor:name"):
            if "History" == node.getAttribute("oor:name"):
                node.parentNode.removeChild(node)
                node.unlink()
                changed = True
                break
    if changed:
        dom1.writexml(open(path, "w"))


# Traceback (UnicodeDecodeError)
Błąd: google_chrome.cache: Command to clean JSON file, path=C:\Users\UserXXX\AppData\Local\Google\Chrome\User Data\Default\Preferences, address=dns_prefetching/host_referral_list
Traceback (most recent call last):
File "C:\projects\bleachbit\bleachbit\Worker.py", line 87, in execute
File "C:\projects\bleachbit\bleachbit\Command.py", line 244, in execute
File "C:\projects\bleachbit\bleachbit\FileUtilities.py", line 263, in clean_json
File "C:\Python34\lib\json\__init__.py", line 265, in load
File "C:\Python34\lib\encodings\cp1250.py", line 23, in decode
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 28203: character maps to <undefined>
Błąd: google_chrome.cache: Command to clean JSON file, path=C:\Users\UserXXX\AppData\Local\Google\Chrome\User Data\Default\Preferences, address=dns_prefetching/startup_list
Traceback (most recent call last):
File "C:\projects\bleachbit\bleachbit\Worker.py", line 87, in execute
File "C:\projects\bleachbit\bleachbit\Command.py", line 244, in execute
File "C:\projects\bleachbit\bleachbit\FileUtilities.py", line 263, in clean_json
File "C:\Python34\lib\json\__init__.py", line 265, in load
File "C:\Python34\lib\encodings\cp1250.py", line 23, in decode
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 28203: character maps to <undefined>
Błąd: google_chrome.cache: Command to clean JSON file, path=C:\Users\UserXXX\AppData\Local\Google\Chrome\User Data\Default\Preferences, address=net/http_server_properties/servers
Traceback (most recent call last):
File "C:\projects\bleachbit\bleachbit\Worker.py", line 87, in execute
File "C:\projects\bleachbit\bleachbit\Command.py", line 244, in execute
File "C:\projects\bleachbit\bleachbit\FileUtilities.py", line 263, in clean_json
File "C:\Python34\lib\json\__init__.py", line 265, in load
File "C:\Python34\lib\encodings\cp1250.py", line 23, in decode
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 28203: character maps to <undefined>

# Fixed code
def delete_ooo_history(path):
    """Erase the OpenOffice.org MRU in Common.xcu.  No longer valid in Apache OpenOffice.org 3.4."""
    import xml.dom.minidom

    dom1 = xml.dom.minidom.parse(path)
    changed = False
    for node in dom1.getElementsByTagName("node"):
        if node.hasAttribute("oor:name"):
            if "History" == node.getAttribute("oor:name"):
                node.parentNode.removeChild(node)
                node.unlink()
                changed = True
                break
    if changed:
        dom1.writexml(open(path, "w", encoding="utf-8"))
# Buggy code
def __shred_sqlite_char_columns(table, cols=None, where=""):
    """Create an SQL command to shred character columns"""
    cmd = ""
    if cols and options.get("shred"):
        cmd += "update or ignore %s set %s %s;" % (
            table,
            ",".join(["%s = randomblob(length(%s))" % (col, col) for col in cols]),
            where,
        )
        cmd += "update or ignore %s set %s %s;" % (
            table,
            ",".join(["%s = zeroblob(length(%s))" % (col, col) for col in cols]),
            where,
        )
    cmd += "delete from %s %s;" % (table, where)
    return cmd


# Traceback (OperationalError)
Error: google_chrome.history: Function: Clean file: C:\Users\<redacted>\AppData\Local\Google\Chrome\User Data\Default\History
Traceback (most recent call last):
File "bleachbit\Worker.pyo", line 88, in execute
File "bleachbit\Command.pyo", line 162, in execute
File "bleachbit\Special.pyo", line 199, in delete_chrome_history
File "bleachbit\FileUtilities.pyo", line 406, in execute_sqlite3
OperationalError: no such column: lower_term: C:\Users\<redacted>\AppData\Local\Google\Chrome\User Data\Default\History
ERROR:bleachbit.Worker:Error: google_chrome.history: Function: Clean file: C:\Users\<redacted>\AppData\Local\Google\Chrome\User Data\Default\History
Traceback (most recent call last):
File "bleachbit\Worker.pyo", line 88, in execute
File "bleachbit\Command.pyo", line 162, in execute
File "bleachbit\Special.pyo", line 199, in delete_chrome_history
File "bleachbit\FileUtilities.pyo", line 406, in execute_sqlite3
OperationalError: no such column: lower_term: C:\Users\<redacted>\AppData\Local\Google\Chrome\User Data\Default\History

# Fixed code
def __shred_sqlite_char_columns(table, cols=None, where=""):
    """Create an SQL command to shred character columns"""
    cmd = ""
    if not where:
        # If None, set to empty string.
        where = ""
    if cols and options.get("shred"):
        cmd += "update or ignore %s set %s %s;" % (
            table,
            ",".join(["%s = randomblob(length(%s))" % (col, col) for col in cols]),
            where,
        )
        cmd += "update or ignore %s set %s %s;" % (
            table,
            ",".join(["%s = zeroblob(length(%s))" % (col, col) for col in cols]),
            where,
        )
    cmd += "delete from %s %s;" % (table, where)
    return cmd
# Buggy code
def set_environ(varname, path):
    """Define an environment variable for use in CleanerML and Winapp2.ini"""
    if not path:
        return
    if varname in os.environ:
        # logger.debug('set_environ(%s, %s): skipping because environment variable is already defined', varname, path)
        if "nt" == os.name:
            os.environ[varname] = bleachbit.expandvars("%%%s%%" % varname).encode(
                "utf-8"
            )
        # Do not redefine the environment variable when it already exists
        # But re-encode them with utf-8 instead of mbcs
        return
    try:
        if not os.path.exists(path):
            raise RuntimeError(
                "Variable %s points to a non-existent path %s" % (varname, path)
            )
        os.environ[varname] = path.encode("utf8")
    except:
        logger.exception(
            "set_environ(%s, %s): exception when setting environment variable",
            varname,
            path,
        )


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "bleachbit\Windows.pyo", line 600, in set_environ
UnicodeDecodeError: 'utf8' codec can't decode byte 0xdc in position 26: invalid continuation byte
set_environ(cd, C:\Users\xxxxx-xxxxxx-x-xxÜö\AppData\Local\BleachBit): exception when setting environment variable

# Fixed code
def set_environ(varname, path):
    """Define an environment variable for use in CleanerML and Winapp2.ini"""
    if not path:
        return
    if varname in os.environ:
        # logger.debug('set_environ(%s, %s): skipping because environment variable is already defined', varname, path)
        if "nt" == os.name:
            os.environ[varname] = bleachbit.expandvars("%%%s%%" % varname).encode(
                "utf-8"
            )
        # Do not redefine the environment variable when it already exists
        # But re-encode them with utf-8 instead of mbcs
        return
    try:
        if not os.path.exists(path):
            raise RuntimeError(
                "Variable %s points to a non-existent path %s" % (varname, path)
            )
        os.environ[varname] = path if isinstance(path, str) else path.encode("utf8")
    except:
        logger.exception(
            "set_environ(%s, %s): exception when setting environment variable",
            varname,
            path,
        )
# Buggy code
def run_setup():
    setup(
        name="bleachbit",
        version=bleachbit.APP_VERSION,
        description="Free space and maintain privacy",
        long_description="BleachBit frees space and maintains privacy by quickly wiping files you don't need and didn't know you had. Supported applications include Firefox, Flash, Internet Explorer, Java, Opera, Safari, GNOME, and many others.",
        author="Andrew Ziem",
        author_email="andrew@bleachbit.org",
        download_url="https://www.bleachbit.org/download",
        license="GPLv3",
        url=bleachbit.APP_URL,
        platforms="Linux and Windows; Python v2.6 and 2.7; GTK v3.12+",
        packages=["bleachbit"],
        **args,
    )


# Traceback (IOError)
Automatically preserving language en.
Downloading https://sourceforge.net/projects/bleachbit/files/chaff/clinton_subject_model.json.bz2/download to B:\BleachBit-Portable\clinton_subject_model.json.bz2
Traceback (most recent call last):
File "bleachbit\GuiChaff.pyo", line 160, in on_make_files
File "bleachbit\GuiChaff.pyo", line 140, in download_models_dialog
File "bleachbit\GuiChaff.pyo", line 130, in download_models_gui
File "bleachbit\Chaff.pyo", line 141, in download_models
File "urllib2.pyo", line 144, in urlopen
File "ssl.pyo", line 440, in create_default_context
IOError: [Errno 2] No such file or directory

# Fixed code
def run_setup():
    setup(
        name="bleachbit",
        version=bleachbit.APP_VERSION,
        description="Free space and maintain privacy",
        long_description="BleachBit frees space and maintains privacy by quickly wiping files you don't need and didn't know you had. Supported applications include Firefox, Flash, Internet Explorer, Java, Opera, Safari, GNOME, and many others.",
        author="Andrew Ziem",
        author_email="andrew@bleachbit.org",
        download_url="https://www.bleachbit.org/download",
        license="GPLv3",
        url=bleachbit.APP_URL,
        platforms="Linux and Windows; Python v2.6 and 2.7; GTK v3.12+",
        packages=["bleachbit", "bleachbit.markovify"],
        **args,
    )
# Buggy code
def __init__(self):
    self.queue = []


# Traceback (ImportError)
C:\Program Files (x86)\BleachBit>bleachbit_console.exe
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 125, in cb_make_chaff
File "bleachbit\GuiChaff.pyo", line 30, in <module>
File "bleachbit\Chaff.pyo", line 39, in <module>
ImportError: No module named markovify

# Fixed code
def __init__(self):
    self.queue = []
    self.msg = ""
# Buggy code
def read(self):
    for msg in self.queue:
        yield msg + "\n"
    queue = []


# Traceback (ImportError)
C:\Program Files (x86)\BleachBit>bleachbit_console.exe
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 125, in cb_make_chaff
File "bleachbit\GuiChaff.pyo", line 30, in <module>
File "bleachbit\Chaff.pyo", line 39, in <module>
ImportError: No module named markovify

# Fixed code
def read(self):
    for msg in self.queue:
        yield msg
    queue = []
# Buggy code
def write(self, msg):
    self.queue.append(msg)


# Traceback (ImportError)
C:\Program Files (x86)\BleachBit>bleachbit_console.exe
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 125, in cb_make_chaff
File "bleachbit\GuiChaff.pyo", line 30, in <module>
File "bleachbit\Chaff.pyo", line 39, in <module>
ImportError: No module named markovify

# Fixed code
def write(self, msg):
    self.msg += msg
    if self.msg[-1] == "\n":
        self.queue.append(self.msg)
        self.msg = ""
# Buggy code
def __init__(self, append_text):
    logging.Handler.__init__(self)
    self.append_text = append_text
    self.update_log_level()


# Traceback (ImportError)
C:\Program Files (x86)\BleachBit>bleachbit_console.exe
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 125, in cb_make_chaff
File "bleachbit\GuiChaff.pyo", line 30, in <module>
File "bleachbit\Chaff.pyo", line 39, in <module>
ImportError: No module named markovify

# Fixed code
def __init__(self, append_text):
    logging.Handler.__init__(self)
    self.append_text = append_text
    self.msg = ""
    self.update_log_level()
# Buggy code
def cb_shred_quit(self, action, param):
    """Shred settings (for privacy reasons) and quit"""
    # build a list of paths to delete
    paths = []
    if "nt" == os.name and portable_mode:
        # in portable mode on Windows, the options directory includes
        # executables
        paths.append(bleachbit.options_file)
    else:
        paths.append(bleachbit.options_dir)

    # prompt the user to confirm
    if not self.shred_paths(paths):
        logger.debug("user aborted shred")
        # aborted
        return

    # in portable mode, rebuild a minimal bleachbit.ini
    if "nt" == os.name and portable_mode:
        with open(bleachbit.options_file, "w") as f:
            f.write("[Portable]\n")

    # Quit the application through the idle loop to allow the worker
    # to delete the files.  Use the lowest priority because the worker
    # uses the standard priority.  Otherwise, this will quit before
    # the files are deleted.
    GLib.idle_add(lambda: Gtk.main_quit(), priority=GObject.PRIORITY_LOW)


# Traceback (AttributeError)
Traceback (most recent call last):
File "bleachbit/bleachbit/GUI.py", line 177, in cb_shred_quit
if not self.shred_paths(paths):
AttributeError: 'Bleachbit' object has no attribute 'shred_paths'

# Fixed code
def cb_shred_quit(self, action, param):
    """Shred settings (for privacy reasons) and quit"""
    # build a list of paths to delete
    paths = []
    if "nt" == os.name and portable_mode:
        # in portable mode on Windows, the options directory includes
        # executables
        paths.append(bleachbit.options_file)
    else:
        paths.append(bleachbit.options_dir)

    # prompt the user to confirm
    if not GUI.shred_paths(self._window, paths):
        logger.debug("user aborted shred")
        # aborted
        return

    # in portable mode, rebuild a minimal bleachbit.ini
    if "nt" == os.name and portable_mode:
        with open(bleachbit.options_file, "w") as f:
            f.write("[Portable]\n")

    # Quit the application through the idle loop to allow the worker
    # to delete the files.  Use the lowest priority because the worker
    # uses the standard priority.  Otherwise, this will quit before
    # the files are deleted.
    GLib.idle_add(lambda: self.quit(), priority=GObject.PRIORITY_LOW)
# Buggy code
def build_app_menu(self):
    builder = Gtk.Builder()
    builder.add_from_file(
        os.path.join(bleachbit.bleachbit_exe_path, "data", "app-menu.ui")
    )
    menu = builder.get_object("app-menu")
    self.set_app_menu(menu)

    # set up mappings between <attribute name="action"> in app-menu.ui and methods in this class
    actions = {
        "shredFiles": self.cb_shred_file,
        "shredFolders": self.cb_shred_folder,
        "wipeFreeSpace": self.cb_wipe_free_space,
        "shredQuit": self.cb_shred_quit,
        "preferences": self.cb_preferences_dialog,
        "diagnostics": self.diagnostic_dialog,
        "about": self.about,
        "quit": self.quit,
    }

    for actionName, callback in actions.items():
        action = Gio.SimpleAction.new(actionName, None)
        action.connect("activate", callback)
        self.add_action(action)

    # help needs more parameters and needs to be declared separately
    helpAction = Gio.SimpleAction.new("help", None)
    helpAction.connect(
        "activate", GuiBasic.open_url, bleachbit.help_contents_url, self._window
    )
    self.add_action(helpAction)


# Traceback (AttributeError)
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 124, in cb_shred_file
File "bleachbit\GuiBasic.pyo", line 94, in browse_files
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 135, in cb_shred_folder
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 173, in cb_wipe_free_space
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
```

# Fixed code
def build_app_menu(self):
    builder = Gtk.Builder()
    builder.add_from_file(
        os.path.join(bleachbit.bleachbit_exe_path, "data", "app-menu.ui")
    )
    menu = builder.get_object("app-menu")
    self.set_app_menu(menu)

    # set up mappings between <attribute name="action"> in app-menu.ui and methods in this class
    actions = {
        "shredFiles": self.cb_shred_file,
        "shredFolders": self.cb_shred_folder,
        "shredClipboard": self.cb_shred_clipboard,
        "wipeFreeSpace": self.cb_wipe_free_space,
        "shredQuit": self.cb_shred_quit,
        "preferences": self.cb_preferences_dialog,
        "diagnostics": self.diagnostic_dialog,
        "about": self.about,
        "quit": self.quit,
    }

    for actionName, callback in actions.items():
        action = Gio.SimpleAction.new(actionName, None)
        action.connect("activate", callback)
        self.add_action(action)

    # help needs more parameters and needs to be declared separately
    helpAction = Gio.SimpleAction.new("help", None)
    helpAction.connect(
        "activate", GuiBasic.open_url, bleachbit.help_contents_url, self._window
    )
    self.add_action(helpAction)
# Buggy code
def setup_drag_n_drop(self):
    def cb_drag_data_received(widget, context, x, y, data, info, time):
        if info == 80:
            uris = data.get_uris()
            paths = FileUtilities.uris_to_paths(uris)
            self.shred_paths(paths)

    self.drag_dest_set(
        Gtk.DestDefaults.MOTION | Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP,
        [Gtk.TargetEntry.new("text/uri-list", 0, 80)],
        Gdk.DragAction.COPY,
    )
    self.connect("drag_data_received", cb_drag_data_received)


# Traceback (AttributeError)
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 124, in cb_shred_file
File "bleachbit\GuiBasic.pyo", line 94, in browse_files
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 135, in cb_shred_folder
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 173, in cb_wipe_free_space
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
```

# Fixed code
def setup_drag_n_drop(self):
    def cb_drag_data_received(widget, context, x, y, data, info, time):
        if info == 80:
            uris = data.get_uris()
            paths = FileUtilities.uris_to_paths(uris)
            self.shred_paths(paths)

    def setup_widget(widget):
        widget.drag_dest_set(
            Gtk.DestDefaults.MOTION
            | Gtk.DestDefaults.HIGHLIGHT
            | Gtk.DestDefaults.DROP,
            [Gtk.TargetEntry.new("text/uri-list", 0, 80)],
            Gdk.DragAction.COPY,
        )
        widget.connect("drag_data_received", cb_drag_data_received)

    setup_widget(self)
    setup_widget(self.textview)
    self.textview.connect("drag_motion", lambda widget, context, x, y, time: True)
# Buggy code
def browse_folder(parent, title, multiple, stock_button):
    """Ask the user to select a folder.  Return the full path or None."""

    if "nt" == os.name and None == os.getenv("BB_NATIVE"):
        ret = Windows.browse_folder(parent.window.handle if parent else None, title)
        return [ret] if multiple and not ret is None else ret

    # fall back to GTK+
    chooser = Gtk.FileChooserDialog(
        transient_for=parent, title=title, action=Gtk.FileChooserAction.SELECT_FOLDER
    )
    chooser.add_buttons(
        _("_Cancel"), Gtk.ResponseType.CANCEL, stock_button, Gtk.ResponseType.OK
    )
    chooser.set_default_response(Gtk.ResponseType.OK)
    chooser.set_select_multiple(multiple)
    chooser.set_current_folder(expanduser("~"))
    resp = chooser.run()
    if multiple:
        ret = chooser.get_filenames()
    else:
        ret = chooser.get_filename()
    chooser.hide()
    chooser.destroy()
    if Gtk.ResponseType.OK != resp:
        # user cancelled
        return None
    return ret


# Traceback (AttributeError)
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 124, in cb_shred_file
File "bleachbit\GuiBasic.pyo", line 94, in browse_files
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 135, in cb_shred_folder
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 173, in cb_wipe_free_space
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
```

# Fixed code
def browse_folder(parent, title, multiple, stock_button):
    """Ask the user to select a folder.  Return the full path or None."""

    if "nt" == os.name and None == os.getenv("BB_NATIVE"):
        ret = Windows.browse_folder(parent, title)
        return [ret] if multiple and not ret is None else ret

    # fall back to GTK+
    chooser = Gtk.FileChooserDialog(
        transient_for=parent, title=title, action=Gtk.FileChooserAction.SELECT_FOLDER
    )
    chooser.add_buttons(
        _("_Cancel"), Gtk.ResponseType.CANCEL, stock_button, Gtk.ResponseType.OK
    )
    chooser.set_default_response(Gtk.ResponseType.OK)
    chooser.set_select_multiple(multiple)
    chooser.set_current_folder(expanduser("~"))
    resp = chooser.run()
    if multiple:
        ret = chooser.get_filenames()
    else:
        ret = chooser.get_filename()
    chooser.hide()
    chooser.destroy()
    if Gtk.ResponseType.OK != resp:
        # user cancelled
        return None
    return ret
# Buggy code
def browse_file(parent, title):
    """Prompt user to select a single file"""

    if "nt" == os.name and None == os.getenv("BB_NATIVE"):
        return Windows.browse_file(parent.window.handle, title)

    chooser = Gtk.FileChooserDialog(
        title=title, transient_for=parent, action=Gtk.FileChooserAction.OPEN
    )
    chooser.add_buttons(
        _("_Cancel"), Gtk.ResponseType.CANCEL, _("_Open"), Gtk.ResponseType.OK
    )
    chooser.set_default_response(Gtk.ResponseType.OK)
    chooser.set_current_folder(expanduser("~"))
    resp = chooser.run()
    path = chooser.get_filename()
    chooser.destroy()

    if Gtk.ResponseType.OK != resp:
        # user cancelled
        return None

    return path


# Traceback (AttributeError)
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 124, in cb_shred_file
File "bleachbit\GuiBasic.pyo", line 94, in browse_files
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 135, in cb_shred_folder
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 173, in cb_wipe_free_space
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
```

# Fixed code
def browse_file(parent, title):
    """Prompt user to select a single file"""

    if "nt" == os.name and None == os.getenv("BB_NATIVE"):
        return Windows.browse_file(parent, title)

    chooser = Gtk.FileChooserDialog(
        title=title, transient_for=parent, action=Gtk.FileChooserAction.OPEN
    )
    chooser.add_buttons(
        _("_Cancel"), Gtk.ResponseType.CANCEL, _("_Open"), Gtk.ResponseType.OK
    )
    chooser.set_default_response(Gtk.ResponseType.OK)
    chooser.set_current_folder(expanduser("~"))
    resp = chooser.run()
    path = chooser.get_filename()
    chooser.destroy()

    if Gtk.ResponseType.OK != resp:
        # user cancelled
        return None

    return path
# Buggy code
def browse_files(parent, title):
    """Prompt user to select multiple files to delete"""

    if "nt" == os.name and None == os.getenv("BB_NATIVE"):
        return Windows.browse_files(parent.window.handle, title)

    chooser = Gtk.FileChooserDialog(
        title=title, transient_for=parent, action=Gtk.FileChooserAction.OPEN
    )
    chooser.add_buttons(
        _("_Cancel"), Gtk.ResponseType.CANCEL, _("_Delete"), Gtk.ResponseType.OK
    )
    chooser.set_default_response(Gtk.ResponseType.OK)
    chooser.set_select_multiple(True)
    chooser.set_current_folder(expanduser("~"))
    resp = chooser.run()
    paths = chooser.get_filenames()
    chooser.destroy()

    if Gtk.ResponseType.OK != resp:
        # user cancelled
        return None

    return paths


# Traceback (AttributeError)
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 124, in cb_shred_file
File "bleachbit\GuiBasic.pyo", line 94, in browse_files
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 135, in cb_shred_folder
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 173, in cb_wipe_free_space
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
```

# Fixed code
def browse_files(parent, title):
    """Prompt user to select multiple files to delete"""

    if "nt" == os.name and None == os.getenv("BB_NATIVE"):
        return Windows.browse_files(parent, title)

    chooser = Gtk.FileChooserDialog(
        title=title, transient_for=parent, action=Gtk.FileChooserAction.OPEN
    )
    chooser.add_buttons(
        _("_Cancel"), Gtk.ResponseType.CANCEL, _("_Delete"), Gtk.ResponseType.OK
    )
    chooser.set_default_response(Gtk.ResponseType.OK)
    chooser.set_select_multiple(True)
    chooser.set_current_folder(expanduser("~"))
    resp = chooser.run()
    paths = chooser.get_filenames()
    chooser.destroy()

    if Gtk.ResponseType.OK != resp:
        # user cancelled
        return None

    return paths
# Buggy code
def browse_folder(hwnd, title):
    """Ask the user to select a folder.  Return full path."""
    pidl = shell.SHBrowseForFolder(hwnd, None, title)[0]
    if pidl is None:
        # user cancelled
        return None
    fullpath = shell.SHGetPathFromIDList(pidl)
    return fullpath


# Traceback (AttributeError)
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 124, in cb_shred_file
File "bleachbit\GuiBasic.pyo", line 94, in browse_files
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 135, in cb_shred_folder
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
Traceback (most recent call last):
File "bleachbit\GUI.pyo", line 173, in cb_wipe_free_space
File "bleachbit\GuiBasic.pyo", line 43, in browse_folder
AttributeError: 'GUI' object has no attribute 'window'
```

# Fixed code
def browse_folder(_, title):
    """Ask the user to select a folder.  Return full path."""
    pidl = shell.SHBrowseForFolder(None, None, title)[0]
    if pidl is None:
        # user cancelled
        return None
    fullpath = shell.SHGetPathFromIDList(pidl)
    return fullpath
# Buggy code
def __toggle_callback(self, cell, path):
    """Callback function to toggle option"""
    options.toggle(path)
    if online_update_notification_enabled:
        self.cb_beta.set_sensitive(options.get("check_online_updates"))
        if "nt" == os.name:
            self.cb_winapp2.set_sensitive(options.get("check_online_updates"))
    if "auto_hide" == path:
        self.cb_refresh_operations()
    if "auto_start" == path:
        if "nt" == os.name:
            swc = Windows.start_with_computer
        if "posix" == os.name:
            swc = Unix.start_with_computer
        try:
            swc(options.get(path))
        except:
            traceback.print_exc()
            dlg = Gtk.MessageDialog(
                self.parent,
                type=Gtk.MessageType.ERROR,
                buttons=Gtk.ButtonsType.OK,
                message_format=str(sys.exc_info()[1]),
            )
            dlg.run()
            dlg.destroy()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/bleachbit/bleachbit/GUI.py", line 186, in cb_preferences_dialog
pref = PreferencesDialog(self._window, self._window.cb_refresh_operations)
File "/bleachbit/bleachbit/GuiPreferences.py", line 65, in __init__
notebook.append_page(self.__general_page(), Gtk.Label(label=_("General")))
File "/bleachbit/bleachbit/GuiPreferences.py", line 107, in __general_page
swcc = Unix.start_with_computer_check
AttributeError: 'module' object has no attribute 'start_with_computer_check'

# Fixed code
def __toggle_callback(self, cell, path):
    """Callback function to toggle option"""
    options.toggle(path)
    if online_update_notification_enabled:
        self.cb_beta.set_sensitive(options.get("check_online_updates"))
        if "nt" == os.name:
            self.cb_winapp2.set_sensitive(options.get("check_online_updates"))
    if "auto_hide" == path:
        self.cb_refresh_operations()
# Buggy code
def start_with_computer(enabled):
    """If enabled, create shortcut to start application with computer.
    If disabled, then delete the shortcut."""
    if not enabled:
        # User requests to not automatically start BleachBit
        if os.path.lexists(bleachbit.autostart_path):
            # Delete the shortcut
            FileUtilities.delete(bleachbit.autostart_path)
        return
    # User requests to automatically start BleachBit
    if os.path.lexists(bleachbit.autostart_path):
        # Already automatic, so exit
        return
    if not os.path.exists(bleachbit.launcher_path):
        logger.error("%s does not exist: ", bleachbit.launcher_path)
        return
    import shutil

    General.makedirs(os.path.dirname(bleachbit.autostart_path))
    shutil.copy(bleachbit.launcher_path, bleachbit.autostart_path)
    os.chmod(bleachbit.autostart_path, 0o755)
    if General.sudo_mode():
        General.chownself(bleachbit.autostart_path)


# Traceback (AssertionError)
FAIL: test_start_with_computer (tests.TestUnix.UnixTestCase)
Unit test for start_with_computer*
----------------------------------------------------------------------

Traceback (most recent call last):
File "/home/travis/build/bleachbit/bleachbit/tests/TestUnix.py", line 216, in test_start_with_computer
self.assertNotEqual(b, two_b)
AssertionError: False == False

# Fixed code
def start_with_computer(enabled):
    """If enabled, create shortcut to start application with computer.
    If disabled, then delete the shortcut."""
    if not enabled:
        # User requests to not automatically start BleachBit
        if os.path.lexists(bleachbit.autostart_path):
            # Delete the shortcut
            FileUtilities.delete(bleachbit.autostart_path)
        return
    # User requests to automatically start BleachBit
    if os.path.lexists(bleachbit.autostart_path):
        # Already automatic, so exit
        return
    if not os.path.exists(bleachbit.launcher_path):
        logger.error("%s does not exist: ", bleachbit.launcher_path)
        return
    autostart_dir = os.path.dirname(bleachbit.autostart_path)
    if not os.path.exists(autostart_dir):
        General.makedirs(autostart_dir)
    import shutil

    shutil.copy(bleachbit.launcher_path, bleachbit.autostart_path)
    os.chmod(bleachbit.autostart_path, 0o755)
    if General.sudo_mode():
        General.chownself(bleachbit.autostart_path)
# Buggy code
def updateStartOnLogon(self):
    """
    Configure Bitmessage to start on startup (or remove the
    configuration) based on the setting in the keys.dat file
    """
    startonlogon = BMConfigParser().safeGetBoolean("bitmessagesettings", "startonlogon")
    if "win32" in sys.platform or "win64" in sys.platform:
        # Auto-startup for Windows
        RUN_PATH = (
            "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
        )
        settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat)
        # In case the user moves the program and the registry entry is
        # no longer valid, this will delete the old registry entry.
        if startonlogon:
            settings.setValue("PyBitmessage", sys.argv[0])
        else:
            settings.remove("PyBitmessage")
    elif self.desktop:
        self.desktop.adjust_startonlogon(startonlogon)


# Traceback (NameError)
$ Documents/Software/PyBitmessage/src/bitmessagemain.py
2021-02-13 20:05:18,826 - WARNING - Using default logger configuration
2021-02-13 20:05:23,429 - WARNING - /home/*****/.namecoin/namecoin.conf unreadable or missing, Namecoin support deactivated
2021-02-13 20:05:23,435 - WARNING - There was a problem testing for a Namecoin daemon. Hiding the Fetch Namecoin ID button
2021-02-13 20:05:23,436 - CRITICAL - Unhandled exception
Traceback (most recent call last):
File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 487, in <module>
File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 483, in main
File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 356, in start
File "/home/*****/Documents/Software/PyBitmessage/src/bitmessageqt/__init__.py", line 4188, in run
myapp = MyForm()
File "/home/*****/Documents/Software/PyBitmessage/src/bitmessageqt/__init__.py", line 825, in __init__
self.indicatorInit()
File "/home/*****/Documents/Software/PyBitmessage/src/bitmessageqt/__init__.py", line 1435, in indicatorInit
self.desktop = get_plugin('desktop')()
NameError: global name 'get_plugin' is not defined

# Fixed code
def updateStartOnLogon(self):
    """
    Configure Bitmessage to start on startup (or remove the
    configuration) based on the setting in the keys.dat file
    """
    startonlogon = BMConfigParser().safeGetBoolean("bitmessagesettings", "startonlogon")
    if sys.platform.startswith("win"):  # Auto-startup for Windows
        RUN_PATH = (
            "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
        )
        settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat)
        # In case the user moves the program and the registry entry is
        # no longer valid, this will delete the old registry entry.
        if startonlogon:
            settings.setValue("PyBitmessage", sys.argv[0])
        else:
            settings.remove("PyBitmessage")
    else:
        try:  # get desktop plugin if any
            self.desktop = get_plugin("desktop")()
            self.desktop.adjust_startonlogon(startonlogon)
        except (NameError, TypeError):
            self.desktop = False
# Buggy code
def indicatorInit(self):
    """
    Try init the distro specific appindicator,
    for example the Ubuntu MessagingMenu
    """

    def _noop_update(*args, **kwargs):
        pass

    # get desktop plugin if any
    if "win" not in sys.platform:
        try:
            self.desktop = get_plugin("desktop")()
        except TypeError:
            self.desktop = False

    try:
        self.indicatorUpdate = get_plugin("indicator")(self)
    except (NameError, TypeError):
        logger.warning("No indicator plugin found")
        self.indicatorUpdate = _noop_update


# Traceback (NameError)
$ Documents/Software/PyBitmessage/src/bitmessagemain.py
2021-02-13 20:05:18,826 - WARNING - Using default logger configuration
2021-02-13 20:05:23,429 - WARNING - /home/*****/.namecoin/namecoin.conf unreadable or missing, Namecoin support deactivated
2021-02-13 20:05:23,435 - WARNING - There was a problem testing for a Namecoin daemon. Hiding the Fetch Namecoin ID button
2021-02-13 20:05:23,436 - CRITICAL - Unhandled exception
Traceback (most recent call last):
File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 487, in <module>
File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 483, in main
File "Documents/Software/PyBitmessage/src/bitmessagemain.py", line 356, in start
File "/home/*****/Documents/Software/PyBitmessage/src/bitmessageqt/__init__.py", line 4188, in run
myapp = MyForm()
File "/home/*****/Documents/Software/PyBitmessage/src/bitmessageqt/__init__.py", line 825, in __init__
self.indicatorInit()
File "/home/*****/Documents/Software/PyBitmessage/src/bitmessageqt/__init__.py", line 1435, in indicatorInit
self.desktop = get_plugin('desktop')()
NameError: global name 'get_plugin' is not defined

# Fixed code
def indicatorInit(self):
    """
    Try init the distro specific appindicator,
    for example the Ubuntu MessagingMenu
    """

    def _noop_update(*args, **kwargs):
        pass

    try:
        self.indicatorUpdate = get_plugin("indicator")(self)
    except (NameError, TypeError):
        logger.warning("No indicator plugin found")
        self.indicatorUpdate = _noop_update