gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __mod__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x % y, self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __mod__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x % y, self, other)
# Buggy code
def __div__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__div__(y), self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __div__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__div__(y), self, other)
# Buggy code
def __rdiv__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__div__(y), other, self)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __rdiv__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__div__(y), other, self)
# Buggy code
def __truediv__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__truediv__(y), self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __truediv__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__truediv__(y), self, other)
# Buggy code
def __rtruediv__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__truediv__(y), other, self)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __rtruediv__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x.__truediv__(y), other, self)
# Buggy code
def __floordiv__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x // y, self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __floordiv__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x // y, self, other)
# Buggy code
def __getitem__(self, index: Any) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x: x[index], self)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __getitem__(self, index: Any):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x: x[index], self)
# Buggy code
def _close(self, engine):
    self.pbar.close()
    self.pbar = None


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-36-b4ac10e6ccc4> in <module>
----> 1 trainer.run(train_ab_loader, max_epochs=200)

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in run(self, data, max_epochs)
357         except BaseException as e:
358             self._logger.error("Engine run is terminating due to exception: %s.", str(e))
--> 359             self._handle_exception(e)
360
361         return self.state

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _handle_exception(self, e)
322             self._fire_event(Events.EXCEPTION_RAISED, e)
323         else:
--> 324             raise e
325
326     def run(self, data, max_epochs=1):

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in run(self, data, max_epochs)
350                 self._fire_event(Events.EPOCH_COMPLETED)
351
--> 352             self._fire_event(Events.COMPLETED)
353             time_taken = time.time() - start_time
354             hours, mins, secs = _to_hours_mins_secs(time_taken)

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs)
257             for func, args, kwargs in self._event_handlers[event_name]:
258                 kwargs.update(event_kwargs)
--> 259                 func(self, *(event_args + args), **kwargs)
260
261     def fire_event(self, event_name):

/opt/conda/lib/python3.7/site-packages/ignite/contrib/handlers/tqdm_logger.py in _close(self, engine)
115
116     def _close(self, engine):
--> 117         self.pbar.close()
118         self.pbar = None
119

AttributeError: 'NoneType' object has no attribute 'close'

# Fixed code
def _close(self, engine):
    if self.pbar:
        self.pbar.close()
    self.pbar = None
# Buggy code
def _save(self, obj, path):
    if not self._atomic:
        torch.save(obj, path)

    else:
        tmp = tempfile.NamedTemporaryFile(delete=False)

        try:
            torch.save(obj, tmp.file)

        except BaseException:
            tmp.close()
            os.remove(tmp.name)
            raise

        else:
            tmp.close()
            os.rename(tmp.name, path)


# Traceback (OSError)
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/trainer.py", line 53, in run
self._handle_exception(state, e)
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 138, in _handle_exception
raise e
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/trainer.py", line 40, in run
hours, mins, secs = self._run_once_on_dataset(state)
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 132, in _run_once_on_dataset
self._handle_exception(state, e)
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 138, in _handle_exception
raise e
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 123, in _run_once_on_dataset
self._fire_event(Events.ITERATION_COMPLETED, state)
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 106, in _fire_event
func(self, state, *(event_args + args), **kwargs)
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/handlers/checkpoint.py", line 147, in __call__
self._save(obj=obj, path=path)
File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/handlers/checkpoint.py", line 124, in _save
os.rename(tmp.name, path)
OSError: [Errno 18] Invalid cross-device link: '/tmp/tmpe7shyxri' -> '/home/user/output/weights/_SSD300_1.pth'

# Fixed code
def _save(self, obj, path):
    if not self._atomic:
        torch.save(obj, path)

    else:
        tmp = tempfile.NamedTemporaryFile(delete=False, dir=self._dirname)

        try:
            torch.save(obj, tmp.file)

        except BaseException:
            tmp.close()
            os.remove(tmp.name)
            raise

        else:
            tmp.close()
            os.rename(tmp.name, path)
# Buggy code
def init():
    logger = logging.getLogger(__name__)
    global __HTTP
    proxy_url = os.getenv("http_proxy")
    if proxy_url and len(proxy_url) > 0:
        logger.info(
            "Rally connects via proxy URL [%s] to the Internet (picked up from the environment variable [http_proxy]).",
            proxy_url,
        )
        __HTTP = urllib3.ProxyManager(
            proxy_url, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()
        )
    else:
        logger.info("Rally connects directly to the Internet (no proxy support).")
        __HTTP = urllib3.PoolManager(
            cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()
        )


# Traceback (OSError)
2019-01-23 15:19:43,262 -not-actor-/PID:16740 esrally.utils.net INFO Rally connects via proxy URL [http://username:pw@1.2.3.4:8080] to the Internet (picked up from the environment variable [http_proxy]).
2019-01-23 15:19:43,263 -not-actor-/PID:16740 esrally.utils.net DEBUG Checking for internet connection against [https://github.com/]
2019-01-23 15:19:43,347 -not-actor-/PID:16740 esrally.utils.net DEBUG Could not detect a working Internet connection
Traceback (most recent call last):
File "/usr/local/python3/lib/python3.6/site-packages/urllib3/connectionpool.py", line 595, in urlopen
self._prepare_proxy(conn)
File "/usr/local/python3/lib/python3.6/site-packages/urllib3/connectionpool.py", line 816, in _prepare_proxy
conn.connect()
File "/usr/local/python3/lib/python3.6/site-packages/urllib3/connection.py", line 294, in connect
self._tunnel()
File "/usr/local/python3/lib/python3.6/http/client.py", line 919, in _tunnel
message.strip()))
OSError: Tunnel connection failed: 407 Proxy Authentication Required

# Fixed code
def init():
    logger = logging.getLogger(__name__)
    global __HTTP
    proxy_url = os.getenv("http_proxy")
    if proxy_url and len(proxy_url) > 0:
        parsed_url = urllib3.util.parse_url(proxy_url)
        logger.info(
            "Connecting via proxy URL [%s] to the Internet (picked up from the env variable [http_proxy]).",
            proxy_url,
        )
        __HTTP = urllib3.ProxyManager(
            proxy_url,
            cert_reqs="CERT_REQUIRED",
            ca_certs=certifi.where(),
            # appropriate headers will only be set if there is auth info
            proxy_headers=urllib3.make_headers(proxy_basic_auth=parsed_url.auth),
        )
    else:
        logger.info("Connecting directly to the Internet (no proxy support).")
        __HTTP = urllib3.PoolManager(
            cert_reqs="CERT_REQUIRED", ca_certs=certifi.where()
        )
# Buggy code
def load(self, interpolation=configparser.ExtendedInterpolation()):
    config = configparser.ConfigParser(interpolation=interpolation)
    config.read(self.location, encoding="utf-8")
    return config


# Traceback (esrally.config.ConfigError)
Traceback (most recent call last):
File "/usr/local/bin/esrally", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 588, in main
ensure_configuration_present(cfg, args, sub_command)
File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 428, in ensure_configuration_present
cfg.load_config(auto_upgrade=True)
File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 206, in load_config
self.migrate_config()
File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 239, in migrate_config
migrate(self.config_file, self._stored_config_version(), Config.CURRENT_CONFIG_VERSION)
File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 588, in migrate
.format(config_file.location, PROGRAM_NAME))
esrally.config.ConfigError: ('The config file in /home/ubuntu/.rally/rally.ini is too old. Please delete it and reconfigure Rally from scratch with esrally configure.', None)

# Fixed code
def load(self):
    config = configparser.ConfigParser()
    config.read(self.location, encoding="utf-8")
    return config
# Buggy code
def __init__(self, ledger):
    self.ledger = ledger


# Traceback (ImportError)
python3
Python 3.7.3 (default, Dec 20 2019, 18:57:59)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
from fava.ext import FavaExtensionBase
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/tbm/.local/lib/python3.7/site-packages/fava/ext/__init__.py", line 11, in <module>
from fava.core.helpers import BeancountError
File "/home/tbm/.local/lib/python3.7/site-packages/fava/core/__init__.py", line 47, in <module>
from fava.core.extensions import ExtensionModule
File "/home/tbm/.local/lib/python3.7/site-packages/fava/core/extensions.py", line 12, in <module>
from fava.ext import FavaExtensionBase
ImportError: cannot import name 'FavaExtensionBase' from 'fava.ext' (/home/tbm/.local/lib/python3.7/site-packages/fava/ext/__init__.py)
from fava.ext import FavaExtensionBase


# Fixed code
def __init__(self, message: str) -> None:
    super().__init__()
    self.message = message
# Buggy code
def index(path):
    """
    Render the template for the onionshare landing page.
    """
    self.web.add_request(self.web.REQUEST_LOAD, request.path)

    # Deny new downloads if "Stop sharing after files have been sent" is checked and there is
    # currently a download
    deny_download = (
        self.web.settings.get("share", "autostop_sharing") and self.download_in_progress
    )
    if deny_download:
        r = make_response(
            render_template("denied.html"),
            static_url_path=self.web.static_url_path,
        )
        return self.web.add_security_headers(r)

    # If download is allowed to continue, serve download page
    if self.should_use_gzip():
        self.filesize = self.gzip_filesize
    else:
        self.filesize = self.download_filesize

    return self.render_logic(path)


# Traceback (TypeError)
[2020-11-25 11:14:20,333] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/user/code/onionshare/cli/onionshare_cli/web/share_mode.py", line 64, in index
r = make_response(
TypeError: make_response() got an unexpected keyword argument 'static_url_path'

# Fixed code
def index(path):
    """
    Render the template for the onionshare landing page.
    """
    self.web.add_request(self.web.REQUEST_LOAD, request.path)

    # Deny new downloads if "Stop sharing after files have been sent" is checked and there is
    # currently a download
    deny_download = (
        self.web.settings.get("share", "autostop_sharing") and self.download_in_progress
    )
    if deny_download:
        r = make_response(render_template("denied.html"))
        return self.web.add_security_headers(r)

    # If download is allowed to continue, serve download page
    if self.should_use_gzip():
        self.filesize = self.gzip_filesize
    else:
        self.filesize = self.download_filesize

    return self.render_logic(path)
# Buggy code
def __call__(self, environ, start_response):
    environ["web"] = self.web
    return self.app(environ, start_response)


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def __call__(self, environ, start_response):
    environ["web"] = self.web
    environ["stop_q"] = self.web.stop_q
    return self.app(environ, start_response)
# Buggy code
def __init__(self, filename, write_func, close_func):
    self.onionshare_filename = filename
    self.onionshare_write_func = write_func
    self.onionshare_close_func = close_func

    # Create a temporary file
    self.f = tempfile.TemporaryFile("wb+")

    # Make all the file-like methods and attributes actually access the
    # TemporaryFile, except for write
    attrs = [
        "closed",
        "detach",
        "fileno",
        "flush",
        "isatty",
        "mode",
        "name",
        "peek",
        "raw",
        "read",
        "read1",
        "readable",
        "readinto",
        "readinto1",
        "readline",
        "readlines",
        "seek",
        "seekable",
        "tell",
        "truncate",
        "writable",
        "writelines",
    ]
    for attr in attrs:
        setattr(self, attr, getattr(self.f, attr))


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def __init__(self, request, filename, write_func, close_func):
    self.onionshare_request = request
    self.onionshare_filename = filename
    self.onionshare_write_func = write_func
    self.onionshare_close_func = close_func

    # Create a temporary file
    self.f = tempfile.TemporaryFile("wb+")

    # Make all the file-like methods and attributes actually access the
    # TemporaryFile, except for write
    attrs = [
        "closed",
        "detach",
        "fileno",
        "flush",
        "isatty",
        "mode",
        "name",
        "peek",
        "raw",
        "read",
        "read1",
        "readable",
        "readinto",
        "readinto1",
        "readline",
        "readlines",
        "seek",
        "seekable",
        "tell",
        "truncate",
        "writable",
        "writelines",
    ]
    for attr in attrs:
        setattr(self, attr, getattr(self.f, attr))
# Buggy code
def write(self, b):
    """
    Custom write method that calls out to onionshare_write_func
    """
    bytes_written = self.f.write(b)
    self.onionshare_write_func(self.onionshare_filename, bytes_written)


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def write(self, b):
    """
    Custom write method that calls out to onionshare_write_func
    """
    if not self.onionshare_request.stop_q.empty():
        self.close()
        self.onionshare_request.close()
        return

    bytes_written = self.f.write(b)
    self.onionshare_write_func(self.onionshare_filename, bytes_written)
# Buggy code
def _get_file_stream(
    self, total_content_length, content_type, filename=None, content_length=None
):
    """
    This gets called for each file that gets uploaded, and returns an file-like
    writable stream.
    """
    if self.upload_request:
        if not self.told_gui_about_request:
            # Tell the GUI about the request
            self.web.add_request(
                self.web.REQUEST_STARTED,
                self.path,
                {"id": self.upload_id, "content_length": self.content_length},
            )
            self.web.receive_mode.uploads_in_progress.append(self.upload_id)

            self.told_gui_about_request = True

        self.progress[filename] = {"uploaded_bytes": 0, "complete": False}

    return ReceiveModeTemporaryFile(
        filename, self.file_write_func, self.file_close_func
    )


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def _get_file_stream(
    self, total_content_length, content_type, filename=None, content_length=None
):
    """
    This gets called for each file that gets uploaded, and returns an file-like
    writable stream.
    """
    if self.upload_request:
        if not self.told_gui_about_request:
            # Tell the GUI about the request
            self.web.add_request(
                self.web.REQUEST_STARTED,
                self.path,
                {"id": self.upload_id, "content_length": self.content_length},
            )
            self.web.receive_mode.uploads_in_progress.append(self.upload_id)

            self.told_gui_about_request = True

        self.progress[filename] = {"uploaded_bytes": 0, "complete": False}

    return ReceiveModeTemporaryFile(
        self, filename, self.file_write_func, self.file_close_func
    )
# Buggy code
def close(self):
    """
    Closing the request.
    """
    super(ReceiveModeRequest, self).close()
    try:
        if self.told_gui_about_request:
            upload_id = self.upload_id
            # Inform the GUI that the upload has finished
            self.web.add_request(
                self.web.REQUEST_UPLOAD_FINISHED, self.path, {"id": upload_id}
            )
            self.web.receive_mode.uploads_in_progress.remove(upload_id)
    except AttributeError:
        pass


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def close(self):
    """
    Closing the request.
    """
    super(ReceiveModeRequest, self).close()

    # Prevent calling this method more than once per request
    if self.closed:
        return
    self.closed = True

    self.web.common.log("ReceiveModeRequest", "close")

    try:
        if self.told_gui_about_request:
            upload_id = self.upload_id

            if not self.web.stop_q.empty():
                # Inform the GUI that the upload has canceled
                self.web.add_request(
                    self.web.REQUEST_UPLOAD_CANCELED, self.path, {"id": upload_id}
                )
            else:
                # Inform the GUI that the upload has finished
                self.web.add_request(
                    self.web.REQUEST_UPLOAD_FINISHED, self.path, {"id": upload_id}
                )
            self.web.receive_mode.uploads_in_progress.remove(upload_id)

    except AttributeError:
        pass
# Buggy code
def file_write_func(self, filename, length):
    """
    This function gets called when a specific file is written to.
    """
    if self.upload_request:
        self.progress[filename]["uploaded_bytes"] += length

        if self.previous_file != filename:
            if self.previous_file is not None:
                print("")
            self.previous_file = filename

        print(
            "\r=> {:15s} {}".format(
                self.web.common.human_readable_filesize(
                    self.progress[filename]["uploaded_bytes"]
                ),
                filename,
            ),
            end="",
        )

        # Update the GUI on the upload progress
        if self.told_gui_about_request:
            self.web.add_request(
                self.web.REQUEST_PROGRESS,
                self.path,
                {"id": self.upload_id, "progress": self.progress},
            )


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def file_write_func(self, filename, length):
    """
    This function gets called when a specific file is written to.
    """
    if self.closed:
        return

    if self.upload_request:
        self.progress[filename]["uploaded_bytes"] += length

        if self.previous_file != filename:
            if self.previous_file is not None:
                print("")
            self.previous_file = filename

        print(
            "\r=> {:15s} {}".format(
                self.web.common.human_readable_filesize(
                    self.progress[filename]["uploaded_bytes"]
                ),
                filename,
            ),
            end="",
        )

        # Update the GUI on the upload progress
        if self.told_gui_about_request:
            self.web.add_request(
                self.web.REQUEST_PROGRESS,
                self.path,
                {"id": self.upload_id, "progress": self.progress},
            )
# Buggy code
def __init__(self, common, web):
    self.common = common
    self.common.log("ShareModeWeb", "__init__")

    self.web = web

    # Information about the file to be shared
    self.file_info = []
    self.is_zipped = False
    self.download_filename = None
    self.download_filesize = None
    self.gzip_filename = None
    self.gzip_filesize = None
    self.zip_writer = None

    self.download_count = 0

    # If "Stop After First Download" is checked (stay_open == False), only allow
    # one download at a time.
    self.download_in_progress = False

    # If the client closes the OnionShare window while a download is in progress,
    # it should immediately stop serving the file. The client_cancel global is
    # used to tell the download function that the client is canceling the download.
    self.client_cancel = False

    self.define_routes()


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def __init__(self, common, web):
    self.common = common
    self.common.log("ShareModeWeb", "__init__")

    self.web = web

    # Information about the file to be shared
    self.file_info = []
    self.is_zipped = False
    self.download_filename = None
    self.download_filesize = None
    self.gzip_filename = None
    self.gzip_filesize = None
    self.zip_writer = None

    self.download_count = 0

    # If "Stop After First Download" is checked (stay_open == False), only allow
    # one download at a time.
    self.download_in_progress = False

    self.define_routes()
# Buggy code
def start(self, port, stay_open=False, public_mode=False, persistent_slug=None):
    """
    Start the flask web server.
    """
    self.common.log(
        "Web",
        "start",
        "port={}, stay_open={}, public_mode={}, persistent_slug={}".format(
            port, stay_open, public_mode, persistent_slug
        ),
    )
    if not public_mode:
        self.generate_slug(persistent_slug)

    self.stay_open = stay_open

    # In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220)
    if os.path.exists("/usr/share/anon-ws-base-files/workstation"):
        host = "0.0.0.0"
    else:
        host = "127.0.0.1"

    self.running = True
    self.app.run(host=host, port=port, threaded=True)


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def start(self, port, stay_open=False, public_mode=False, persistent_slug=None):
    """
    Start the flask web server.
    """
    self.common.log(
        "Web",
        "start",
        "port={}, stay_open={}, public_mode={}, persistent_slug={}".format(
            port, stay_open, public_mode, persistent_slug
        ),
    )
    if not public_mode:
        self.generate_slug(persistent_slug)

    self.stay_open = stay_open

    # Make sure the stop_q is empty when starting a new server
    while not self.stop_q.empty():
        try:
            self.stop_q.get(block=False)
        except queue.Empty:
            pass

    # In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220)
    if os.path.exists("/usr/share/anon-ws-base-files/workstation"):
        host = "0.0.0.0"
    else:
        host = "127.0.0.1"

    self.running = True
    self.app.run(host=host, port=port, threaded=True)
# Buggy code
def stop(self, port):
    """
    Stop the flask web server by loading /shutdown.
    """

    if self.mode == "share":
        # If the user cancels the download, let the download function know to stop
        # serving the file
        self.share_mode.client_cancel = True

    # To stop flask, load http://127.0.0.1:<port>/<shutdown_slug>/shutdown
    if self.running:
        try:
            s = socket.socket()
            s.connect(("127.0.0.1", port))
            s.sendall("GET /{0:s}/shutdown HTTP/1.1\r\n\r\n".format(self.shutdown_slug))
        except:
            try:
                urlopen(
                    "http://127.0.0.1:{0:d}/{1:s}/shutdown".format(
                        port, self.shutdown_slug
                    )
                ).read()
            except:
                pass


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def stop(self, port):
    """
    Stop the flask web server by loading /shutdown.
    """
    self.common.log("Web", "stop", "stopping server")

    # Let the mode know that the user stopped the server
    self.stop_q.put(True)

    # To stop flask, load http://127.0.0.1:<port>/<shutdown_slug>/shutdown
    if self.running:
        try:
            s = socket.socket()
            s.connect(("127.0.0.1", port))
            s.sendall("GET /{0:s}/shutdown HTTP/1.1\r\n\r\n".format(self.shutdown_slug))
        except:
            try:
                urlopen(
                    "http://127.0.0.1:{0:d}/{1:s}/shutdown".format(
                        port, self.shutdown_slug
                    )
                ).read()
            except:
                pass
# Buggy code
def get_finished_label_text(self, started):
    """
    When an item finishes, returns a string displaying the start/end datetime range.
    started is a datetime object.
    """
    ended = datetime.now()
    if (
        started.year == ended.year
        and started.month == ended.month
        and started.day == ended.day
    ):
        if started.hour == ended.hour and started.minute == ended.minute:
            text = strings._("gui_all_modes_transfer_finished").format(
                started.strftime("%b %d, %I:%M%p")
            )
        else:
            text = strings._("gui_all_modes_transfer_finished_range").format(
                started.strftime("%b %d, %I:%M%p"), ended.strftime("%I:%M%p")
            )
    else:
        text = strings._("gui_all_modes_transfer_finished_range").format(
            started.strftime("%b %d, %I:%M%p"), ended.strftime("%b %d, %I:%M%p")
        )
    return text


# Traceback (KeyError)
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd
=> 2.4 MiB         video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action
Traceback (most recent call last):
File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback
mode.handle_request_progress(event)
File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress
'progress': event["data"]["progress"]
File "onionshare_gui/mode/history.py", line 451, in update
self.item_list.update(id, data)
File "onionshare_gui/mode/history.py", line 347, in update
self.items[id].update(data)
KeyError: 0
=> 2.4 MiB         video 1.movAbort trap: 6

# Fixed code
def get_finished_label_text(self, started):
    """
    When an item finishes, returns a string displaying the start/end datetime range.
    started is a datetime object.
    """
    return self._get_label_text(
        "gui_all_modes_transfer_finished",
        "gui_all_modes_transfer_finished_range",
        started,
    )
# Buggy code
def build_data_dir(self):
    """
    Returns the path of the OnionShare data directory.
    """
    if self.platform == "Windows":
        try:
            appdata = os.environ["APPDATA"]
            return "{}\\OnionShare".format(appdata)
        except:
            # If for some reason we don't have the 'APPDATA' environment variable
            # (like running tests in Linux while pretending to be in Windows)
            return os.path.expanduser("~/.config/onionshare")
    elif self.platform == "Darwin":
        return os.path.expanduser("~/Library/Application Support/OnionShare")
    else:
        return os.path.expanduser("~/.config/onionshare")


# Traceback (FileNotFoundError)
OnionShare 2.0.dev1 | https://onionshare.org/
[Dec 19 2018 03:36:17 PM] Onion.__init__
[Dec 19 2018 03:36:17 PM] OnionShare.__init__
[Dec 19 2018 03:36:17 PM] OnionShareGui.__init__
[Dec 19 2018 03:36:18 PM] Web.__init__: is_gui=True, mode=share
Traceback (most recent call last):
File "./dev_scripts/onionshare-gui", line 28, in <module>
onionshare_gui.main()
File "/home/kevin/dev/onionshare/onionshare_gui/__init__.py", line 126, in main
gui = OnionShareGui(common, onion, qtapp, app, filenames, config, local_only)
File "/home/kevin/dev/onionshare/onionshare_gui/onionshare_gui.py", line 127, in __init__
self.share_mode.init()
File "/home/kevin/dev/onionshare/onionshare_gui/mode/share_mode/__init__.py", line 47, in init
self.web = Web(self.common, True, 'share')
File "/home/kevin/dev/onionshare/onionshare/web/web.py", line 56, in __init__
self.debug_mode()
File "/home/kevin/dev/onionshare/onionshare/web/web.py", line 188, in debug_mode
log_handler = logging.FileHandler(flask_debug_filename)
File "/usr/lib/python3.7/logging/__init__.py", line 1092, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python3.7/logging/__init__.py", line 1121, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/home/kevin/.config/onionshare/flask_debug.log'```

# Fixed code
def build_data_dir(self):
    """
    Returns the path of the OnionShare data directory.
    """
    if self.platform == "Windows":
        try:
            appdata = os.environ["APPDATA"]
            onionshare_data_dir = "{}\\OnionShare".format(appdata)
        except:
            # If for some reason we don't have the 'APPDATA' environment variable
            # (like running tests in Linux while pretending to be in Windows)
            onionshare_data_dir = "~/.config/onionshare"
    elif self.platform == "Darwin":
        onionshare_data_dir = "~/Library/Application Support/OnionShare"
    else:
        onionshare_data_dir = "~/.config/onionshare"

    os.makedirs(onionshare_data_dir, 0o700, True)
    return onionshare_data_dir
# Buggy code
def cancel(self):
    self.mode.common.log("CompressThread", "cancel")

    # Let the Web and ZipWriter objects know that we're canceling compression early
    self.mode.web.cancel_compression = True
    if self.mode.web.zip_writer:
        self.mode.web.zip_writer.cancel_compression = True


# Traceback (AttributeError)
[Sep 24 2018 23:15:34] Web.check_shutdown_slug_candidate: slug_candidate=ymf5eposfwver2gpegmic5drki
127.0.0.1 - - [24/Sep/2018 23:15:34] "GET /ymf5eposfwver2gpegmic5drki/shutdown HTTP/1.1" 200 -
[Sep 24 2018 23:15:34] OnionShare.cleanup
[Sep 24 2018 23:15:34] Onion.cleanup
[Sep 24 2018 23:15:34] Onion.cleanup: trying to remove onion dfi5lhiakae2ztq2t4qd7xh2khrnddsfwldkeczafznfoitua7wbj5yd
[Sep 24 2018 23:15:34] CompressThread.cancel
Traceback (most recent call last):
File "onionshare_gui/share_mode/threads.py", line 59, in cancel
AttributeError: 'Web' object has no attribute 'zip_writer'
Abort trap: 6

# Fixed code
def cancel(self):
    self.mode.common.log("CompressThread", "cancel")

    # Let the Web and ZipWriter objects know that we're canceling compression early
    self.mode.web.cancel_compression = True
    try:
        self.mode.web.zip_writer.cancel_compression = True
    except AttributeError:
        # we never made it as far as creating a ZipWriter object
        pass
# Buggy code
def _initSystemTray(self):
    menu = QtWidgets.QMenu()
    self.settingsAction = menu.addAction(strings._("gui_settings_window_title", True))
    self.settingsAction.triggered.connect(self.open_settings)
    self.helpAction = menu.addAction(strings._("gui_settings_button_help", True))
    self.helpAction.triggered.connect(SettingsDialog.help_clicked)
    self.exitAction = menu.addAction(strings._("systray_menu_exit", True))
    self.exitAction.triggered.connect(self.close)

    self.systemTray = QtWidgets.QSystemTrayIcon(self)
    # The convention is Mac systray icons are always grayscale
    if self.common.platform == "Darwin":
        self.systemTray.setIcon(
            QtGui.QIcon(self.common.get_resource_path("images/logo_grayscale.png"))
        )
    else:
        self.systemTray.setIcon(
            QtGui.QIcon(self.common.get_resource_path("images/logo.png"))
        )
    self.systemTray.setContextMenu(menu)
    self.systemTray.show()


# Traceback (AttributeError)
OnionShare.app/Contents/MacOS/onionshare-gui
OnionShare 1.3 | https://onionshare.org/
Traceback (most recent call last):
File "onionshare_gui/settings_dialog.py", line 795, in help_clicked
self.common.log('SettingsDialog', 'help_clicked')
AttributeError: 'bool' object has no attribute 'common'
Abort trap: 6

# Fixed code
def _initSystemTray(self):
    menu = QtWidgets.QMenu()
    self.settingsAction = menu.addAction(strings._("gui_settings_window_title", True))
    self.settingsAction.triggered.connect(self.open_settings)
    self.helpAction = menu.addAction(strings._("gui_settings_button_help", True))
    self.helpAction.triggered.connect(lambda: SettingsDialog.help_clicked(self))
    self.exitAction = menu.addAction(strings._("systray_menu_exit", True))
    self.exitAction.triggered.connect(self.close)

    self.systemTray = QtWidgets.QSystemTrayIcon(self)
    # The convention is Mac systray icons are always grayscale
    if self.common.platform == "Darwin":
        self.systemTray.setIcon(
            QtGui.QIcon(self.common.get_resource_path("images/logo_grayscale.png"))
        )
    else:
        self.systemTray.setIcon(
            QtGui.QIcon(self.common.get_resource_path("images/logo.png"))
        )
    self.systemTray.setContextMenu(menu)
    self.systemTray.show()