gurudesh/pytracebugs huggingface dataset:
# Buggy code
def symlink_to(orig, dest):
    if is_python2 and is_windows:
        import subprocess

        subprocess.call(["mklink", "/d", path2str(orig), path2str(dest)], shell=True)
    else:
        orig.symlink_to(dest)


# Traceback (OSError)
(venv) C:\g\py\spacy> python -m spacy link en_core_web_sm en
C:\Program Files\Python37\lib\importlib\_bootstrap.py:219: RuntimeWarning: cymem.cymem.Pool size changed, may indicate binary incompatibility. Expected 48 from C header, got 64 from PyObject
return f(*args, **kwds)
C:\Program Files\Python37\lib\importlib\_bootstrap.py:219: RuntimeWarning: cymem.cymem.Address size changed, may indicate binary incompatibility. Expected 24 from C header, got 40 from PyObject
return f(*args, **kwds)

Error: Couldn't link model to 'en'
Creating a symlink in spacy/data failed. Make sure you have the required
permissions and try re-running the command as admin, or use a
virtualenv. You can still import the model as a module and call its
load() method, or create the symlink manually.

C:\g\py\spacy\venv\lib\site-packages\en_core_web_sm -->
C:\g\py\spacy\venv\lib\site-packages\spacy\data\en

Traceback (most recent call last):
File "C:\Program Files\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Program Files\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\g\py\spacy\venv\lib\site-packages\spacy\__main__.py", line 31, in <module>
plac.call(commands[command], sys.argv[1:])
File "C:\g\py\spacy\venv\lib\site-packages\plac_core.py", line 328, in call
cmd, result = parser.consume(arglist)
File "C:\g\py\spacy\venv\lib\site-packages\plac_core.py", line 207, in consume
return cmd, self.func(*(args + varargs + extraopts), **kwargs)
File "C:\g\py\spacy\venv\lib\site-packages\spacy\cli\link.py", line 48, in link
symlink_to(link_path, model_path)
File "C:\g\py\spacy\venv\lib\site-packages\spacy\compat.py", line 87, in symlink_to
orig.symlink_to(dest)
File "C:\Program Files\Python37\lib\pathlib.py", line 1320, in symlink_to
self._accessor.symlink(target, self, target_is_directory)
OSError: symbolic link privilege not held

# Fixed code
def symlink_to(orig, dest):
    if is_windows:
        import subprocess

        subprocess.call(["mklink", "/d", path2str(orig), path2str(dest)], shell=True)
    else:
        orig.symlink_to(dest)
# Buggy code
def load_model_from_link(name, **overrides):
    """Load a model from a shortcut link, or directory in spaCy data path."""
    init_file = get_data_path() / name / "__init__.py"
    spec = importlib.util.spec_from_file_location(name, init_file)
    try:
        cls = importlib.util.module_from_spec(spec)
    except AttributeError:
        raise IOError(
            "Cant' load '%s'. If you're using a shortcut link, make sure it "
            "points to a valid model package (not just a data directory)." % name
        )
    spec.loader.exec_module(cls)
    return cls.load(**overrides)


# Traceback (AttributeError)
In [2]: en = spacy.load('en')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-a732401aeb32> in <module>()
----> 1 en = spacy.load('en')

/src/spaCy/spacy/__init__.py in load(name, **overrides)
11 def load(name, **overrides):
12     name = resolve_load_name(name, **overrides)
---> 13     return util.load_model(name, **overrides)
14
15

/src/spaCy/spacy/util.py in load_model(name, **overrides)
101     if isinstance(name, basestring_):
102         if name in set([d.name for d in data_path.iterdir()]): # in data dir / shortcut
--> 103             return load_model_from_link(name, **overrides)
104         if is_package(name): # installed as package
105             return load_model_from_package(name, **overrides)

/src/spaCy/spacy/util.py in load_model_from_link(name, **overrides)
114     """Load a model from a shortcut link, or directory in spaCy data path."""
115     init_file = get_data_path() / name / '__init__.py'
--> 116     spec = importlib.util.spec_from_file_location(name, init_file)
117     try:
118         cls = importlib.util.module_from_spec(spec)

/usr/lib/python3.5/importlib/_bootstrap_external.py in spec_from_file_location(name, location, loader, submodule_search_locations)

AttributeError: 'PosixPath' object has no attribute 'endswith'

# Fixed code
def load_model_from_link(name, **overrides):
    """Load a model from a shortcut link, or directory in spaCy data path."""
    init_file = get_data_path() / name / "__init__.py"
    spec = importlib.util.spec_from_file_location(name, str(init_file))
    try:
        cls = importlib.util.module_from_spec(spec)
    except AttributeError:
        raise IOError(
            "Cant' load '%s'. If you're using a shortcut link, make sure it "
            "points to a valid model package (not just a data directory)." % name
        )
    spec.loader.exec_module(cls)
    return cls.load(**overrides)
# Buggy code
def get_json(url, desc):
    r = requests.get(url)
    if r.status_code != 200:
        prints(
            "Couldn't fetch %s. Please find a model for your spaCy installation "
            "(v%s), and download it manually." % (desc, about.__version__),
            about.__docs__,
            title="Server error (%d)" % r.status_code,
            exits=True,
        )
    return r.json()


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "spacy/tokens/doc.pyx", line 434, in __get__ (spacy/tokens/doc.cpp:9664)
ValueError: sentence boundary detection requires the dependency parse, which requires data to be installed. If you haven't done so, run:
python -m spacy download es
to install the data

# Fixed code
def get_json(url, desc):
    r = requests.get(url)
    if r.status_code != 200:
        prints(
            "Couldn't fetch %s. Please find a model for your spaCy installation "
            "(v%s), and download it manually." % (desc, about.__version__),
            about.__docs_models__,
            title="Server error (%d)" % r.status_code,
            exits=True,
        )
    return r.json()
# Buggy code
def depr_model_download(lang):
    """
    Replace download modules within en and de with deprecation warning and
    download default language model (using shortcut).
    """
    prints(
        "The spacy.%s.download command is now deprecated. Please use "
        "python -m spacy download [model name or shortcut] instead. For "
        "more info, see the docs: %s." % (lang, about.__docs__),
        "Downloading default '%s' model now..." % lang,
        title="Warning: deprecated command",
    )
    download(lang)


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "spacy/tokens/doc.pyx", line 434, in __get__ (spacy/tokens/doc.cpp:9664)
ValueError: sentence boundary detection requires the dependency parse, which requires data to be installed. If you haven't done so, run:
python -m spacy download es
to install the data

# Fixed code
def depr_model_download(lang):
    """
    Replace download modules within en and de with deprecation warning and
    download default language model (using shortcut).
    """
    prints(
        "The spacy.%s.download command is now deprecated. Please use "
        "python -m spacy download [model name or shortcut] instead. For "
        "more info, see the documentation:" % lang,
        about.__docs_models__,
        "Downloading default '%s' model now..." % lang,
        title="Warning: deprecated command",
    )
    download(lang)
# Buggy code
def __init__(self, ax, raster_source, **kwargs):
    self.raster_source = raster_source
    super(SlippyImageArtist, self).__init__(ax, **kwargs)
    self.cache = []

    ax.figure.canvas.mpl_connect("button_press_event", self.on_press)
    ax.figure.canvas.mpl_connect("button_release_event", self.on_release)

    self.on_release()


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3319, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-8-7607f9c8266c>", line 59, in <module>
plt.show()
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/pyplot.py", line 269, in show
return _show(*args, **kw)
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 27, in __call__
manager.show(**kwargs)
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 99, in show
self.canvas.show()
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend/backend_interagg.py", line 64, in show
self.figure.tight_layout()
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/figure.py", line 2476, in tight_layout
pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/tight_layout.py", line 362, in get_tight_layout_figure
pad=pad, h_pad=h_pad, w_pad=w_pad)
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/tight_layout.py", line 111, in auto_adjust_subplotpars
tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/tight_layout.py", line 112, in <listcomp>
if ax.get_visible()])
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 4393, in get_tightbbox
bbox = a.get_tightbbox(renderer)
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/artist.py", line 284, in get_tightbbox
bbox = self.get_window_extent(renderer)
File "/home/dwells/anaconda3/envs/kando/lib/python3.7/site-packages/matplotlib/image.py", line 868, in get_window_extent
x0, x1, y0, y1 = self._extent
TypeError: cannot unpack non-iterable NoneType object

# Fixed code
def __init__(self, ax, raster_source, **kwargs):
    self.raster_source = raster_source
    if matplotlib.__version__ >= "3":
        # This artist fills the Axes, so should not influence layout.
        kwargs.setdefault("in_layout", False)
    super(SlippyImageArtist, self).__init__(ax, **kwargs)
    self.cache = []

    ax.figure.canvas.mpl_connect("button_press_event", self.on_press)
    ax.figure.canvas.mpl_connect("button_release_event", self.on_release)

    self.on_release()
# Buggy code
def _repr_html_(self):
    import cgi

    try:
        # As matplotlib is not a core cartopy dependency, don't error
        # if it's not available.
        import matplotlib.pyplot as plt
    except ImportError:
        # We can't return an SVG of the CRS, so let Jupyter fall back to
        # a default repr by returning None.
        return None

    # Produce a visual repr of the Projection instance.
    fig, ax = plt.subplots(figsize=(5, 3), subplot_kw={"projection": self})
    ax.set_global()
    ax.coastlines("auto")
    ax.gridlines()
    buf = six.StringIO()
    fig.savefig(buf, format="svg", bbox_inches="tight")
    plt.close(fig)
    # "Rewind" the buffer to the start and return it as an svg string.
    buf.seek(0)
    svg = buf.read()
    return "{}<pre>{}</pre>".format(svg, cgi.escape(repr(self)))


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~/miniconda3/envs/py38/lib/python3.8/site-packages/IPython/core/formatters.py in __call__(self, obj)
343             method = get_real_method(obj, self.print_method)
344             if method is not None:
--> 345                 return method()
346             return None
347         else:

~/miniconda3/envs/py38/lib/python3.8/site-packages/cartopy/crs.py in _repr_html_(self)
180         buf.seek(0)
181         svg = buf.read()
--> 182         return '{}<pre>{}</pre>'.format(svg, cgi.escape(repr(self)))
183
184     def _as_mpl_axes(self):

AttributeError: module 'cgi' has no attribute 'escape'

# Fixed code
def _repr_html_(self):
    if not six.PY2:
        from html import escape
    else:
        from cgi import escape
    try:
        # As matplotlib is not a core cartopy dependency, don't error
        # if it's not available.
        import matplotlib.pyplot as plt
    except ImportError:
        # We can't return an SVG of the CRS, so let Jupyter fall back to
        # a default repr by returning None.
        return None

    # Produce a visual repr of the Projection instance.
    fig, ax = plt.subplots(figsize=(5, 3), subplot_kw={"projection": self})
    ax.set_global()
    ax.coastlines("auto")
    ax.gridlines()
    buf = six.StringIO()
    fig.savefig(buf, format="svg", bbox_inches="tight")
    plt.close(fig)
    # "Rewind" the buffer to the start and return it as an svg string.
    buf.seek(0)
    svg = buf.read()
    return "{}<pre>{}</pre>".format(svg, escape(repr(self)))
# Buggy code
def __init__(self, *args, **kwargs):
    """
    Parameters
    ----------
    token  : str, required. Discord token
        [default: ${TQDM_DISCORD_TOKEN}].
    channel_id  : int, required. Discord channel ID
        [default: ${TQDM_DISCORD_CHANNEL_ID}].
    mininterval  : float, optional.
      Minimum of [default: 1.5] to avoid rate limit.

    See `tqdm.auto.tqdm.__init__` for other parameters.
    """
    kwargs = kwargs.copy()
    logging.getLogger("HTTPClient").setLevel(logging.WARNING)
    self.dio = DiscordIO(
        kwargs.pop("token", getenv("TQDM_DISCORD_TOKEN")),
        kwargs.pop("channel_id", getenv("TQDM_DISCORD_CHANNEL_ID")),
    )

    kwargs["mininterval"] = max(1.5, kwargs.get("mininterval", 1.5))
    super(tqdm_discord, self).__init__(*args, **kwargs)


# Traceback (AttributeError)
haendel:~/projects/telekom/trunk/sandbox/tqdm> python3
Python 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import tqdm, sys
print(tqdm.__version__, sys.version, sys.platform)
4.56.0 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] darwin
t = tqdm.tqdm(total=10, disable=True)
t.reset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/projects/telekom/trunk/sandbox/tqdm/tqdm/std.py", line 1348, in reset
self.last_print_t = self.start_t = self._time()
AttributeError: 'tqdm' object has no attribute '_time'

# Fixed code
def __init__(self, *args, **kwargs):
    """
    Parameters
    ----------
    token  : str, required. Discord token
        [default: ${TQDM_DISCORD_TOKEN}].
    channel_id  : int, required. Discord channel ID
        [default: ${TQDM_DISCORD_CHANNEL_ID}].
    mininterval  : float, optional.
      Minimum of [default: 1.5] to avoid rate limit.

    See `tqdm.auto.tqdm.__init__` for other parameters.
    """
    if not kwargs.get("disable"):
        kwargs = kwargs.copy()
        logging.getLogger("HTTPClient").setLevel(logging.WARNING)
        self.dio = DiscordIO(
            kwargs.pop("token", getenv("TQDM_DISCORD_TOKEN")),
            kwargs.pop("channel_id", getenv("TQDM_DISCORD_CHANNEL_ID")),
        )
        kwargs["mininterval"] = max(1.5, kwargs.get("mininterval", 1.5))
    super(tqdm_discord, self).__init__(*args, **kwargs)
# Buggy code
def clear(self, *args, **kwargs):
    super(tqdm_discord, self).clear(*args, **kwargs)
    self.dio.write("")


# Traceback (AttributeError)
haendel:~/projects/telekom/trunk/sandbox/tqdm> python3
Python 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import tqdm, sys
print(tqdm.__version__, sys.version, sys.platform)
4.56.0 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] darwin
t = tqdm.tqdm(total=10, disable=True)
t.reset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/projects/telekom/trunk/sandbox/tqdm/tqdm/std.py", line 1348, in reset
self.last_print_t = self.start_t = self._time()
AttributeError: 'tqdm' object has no attribute '_time'

# Fixed code
def clear(self, *args, **kwargs):
    super(tqdm_discord, self).clear(*args, **kwargs)
    if not self.disable:
        self.dio.write("")
# Buggy code
def __init__(self, *args, **kwargs):
    """
    Parameters
    ----------
    token  : str, required. Telegram token
        [default: ${TQDM_TELEGRAM_TOKEN}].
    chat_id  : str, required. Telegram chat ID
        [default: ${TQDM_TELEGRAM_CHAT_ID}].

    See `tqdm.auto.tqdm.__init__` for other parameters.
    """
    kwargs = kwargs.copy()
    self.tgio = TelegramIO(
        kwargs.pop("token", getenv("TQDM_TELEGRAM_TOKEN")),
        kwargs.pop("chat_id", getenv("TQDM_TELEGRAM_CHAT_ID")),
    )
    super(tqdm_telegram, self).__init__(*args, **kwargs)


# Traceback (AttributeError)
haendel:~/projects/telekom/trunk/sandbox/tqdm> python3
Python 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import tqdm, sys
print(tqdm.__version__, sys.version, sys.platform)
4.56.0 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] darwin
t = tqdm.tqdm(total=10, disable=True)
t.reset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/projects/telekom/trunk/sandbox/tqdm/tqdm/std.py", line 1348, in reset
self.last_print_t = self.start_t = self._time()
AttributeError: 'tqdm' object has no attribute '_time'

# Fixed code
def __init__(self, *args, **kwargs):
    """
    Parameters
    ----------
    token  : str, required. Telegram token
        [default: ${TQDM_TELEGRAM_TOKEN}].
    chat_id  : str, required. Telegram chat ID
        [default: ${TQDM_TELEGRAM_CHAT_ID}].

    See `tqdm.auto.tqdm.__init__` for other parameters.
    """
    if not kwargs.get("disable"):
        kwargs = kwargs.copy()
        self.tgio = TelegramIO(
            kwargs.pop("token", getenv("TQDM_TELEGRAM_TOKEN")),
            kwargs.pop("chat_id", getenv("TQDM_TELEGRAM_CHAT_ID")),
        )
    super(tqdm_telegram, self).__init__(*args, **kwargs)
# Buggy code
def clear(self, *args, **kwargs):
    super(tqdm_telegram, self).clear(*args, **kwargs)
    self.tgio.write("")


# Traceback (AttributeError)
haendel:~/projects/telekom/trunk/sandbox/tqdm> python3
Python 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import tqdm, sys
print(tqdm.__version__, sys.version, sys.platform)
4.56.0 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] darwin
t = tqdm.tqdm(total=10, disable=True)
t.reset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/projects/telekom/trunk/sandbox/tqdm/tqdm/std.py", line 1348, in reset
self.last_print_t = self.start_t = self._time()
AttributeError: 'tqdm' object has no attribute '_time'

# Fixed code
def clear(self, *args, **kwargs):
    super(tqdm_telegram, self).clear(*args, **kwargs)
    if not self.disable:
        self.tgio.write("")
# Buggy code
def reset(self, total=None):
    """
    Resets to 0 iterations for repeated use.

    Consider combining with `leave=True`.

    Parameters
    ----------
    total  : int or float, optional. Total to use for the new bar.
    """
    _, pbar, _ = self.container.children
    pbar.bar_style = ""
    if total is not None:
        pbar.max = total
        if not self.total and self.ncols is None:  # no longer unknown total
            pbar.layout.width = None  # reset width
    return super(tqdm_notebook, self).reset(total=total)


# Traceback (AttributeError)
haendel:~/projects/telekom/trunk/sandbox/tqdm> python3
Python 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import tqdm, sys
print(tqdm.__version__, sys.version, sys.platform)
4.56.0 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] darwin
t = tqdm.tqdm(total=10, disable=True)
t.reset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/projects/telekom/trunk/sandbox/tqdm/tqdm/std.py", line 1348, in reset
self.last_print_t = self.start_t = self._time()
AttributeError: 'tqdm' object has no attribute '_time'

# Fixed code
def reset(self, total=None):
    """
    Resets to 0 iterations for repeated use.

    Consider combining with `leave=True`.

    Parameters
    ----------
    total  : int or float, optional. Total to use for the new bar.
    """
    if self.disable:
        return super(tqdm_notebook, self).reset(total=total)
    _, pbar, _ = self.container.children
    pbar.bar_style = ""
    if total is not None:
        pbar.max = total
        if not self.total and self.ncols is None:  # no longer unknown total
            pbar.layout.width = None  # reset width
    return super(tqdm_notebook, self).reset(total=total)
# Buggy code
def unpause(self):
    """Restart tqdm timer from last print time."""
    cur_t = self._time()
    self.start_t += cur_t - self.last_print_t
    self.last_print_t = cur_t


# Traceback (AttributeError)
haendel:~/projects/telekom/trunk/sandbox/tqdm> python3
Python 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import tqdm, sys
print(tqdm.__version__, sys.version, sys.platform)
4.56.0 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] darwin
t = tqdm.tqdm(total=10, disable=True)
t.reset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/projects/telekom/trunk/sandbox/tqdm/tqdm/std.py", line 1348, in reset
self.last_print_t = self.start_t = self._time()
AttributeError: 'tqdm' object has no attribute '_time'

# Fixed code
def unpause(self):
    """Restart tqdm timer from last print time."""
    if self.disable:
        return
    cur_t = self._time()
    self.start_t += cur_t - self.last_print_t
    self.last_print_t = cur_t
# Buggy code
def reset(self, total=None):
    """
    Resets to 0 iterations for repeated use.

    Consider combining with `leave=True`.

    Parameters
    ----------
    total  : int or float, optional. Total to use for the new bar.
    """
    self.last_print_n = self.n = 0
    self.last_print_t = self.start_t = self._time()
    self._ema_dn = EMA(self.smoothing)
    self._ema_dt = EMA(self.smoothing)
    self._ema_miniters = EMA(self.smoothing)
    if total is not None:
        self.total = total
    self.refresh()


# Traceback (AttributeError)
haendel:~/projects/telekom/trunk/sandbox/tqdm> python3
Python 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import tqdm, sys
print(tqdm.__version__, sys.version, sys.platform)
4.56.0 3.9.1 (default, Jan  8 2021, 17:17:43)
[Clang 12.0.0 (clang-1200.0.32.28)] darwin
t = tqdm.tqdm(total=10, disable=True)
t.reset()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Volumes/projects/telekom/trunk/sandbox/tqdm/tqdm/std.py", line 1348, in reset
self.last_print_t = self.start_t = self._time()
AttributeError: 'tqdm' object has no attribute '_time'

# Fixed code
def reset(self, total=None):
    """
    Resets to 0 iterations for repeated use.

    Consider combining with `leave=True`.

    Parameters
    ----------
    total  : int or float, optional. Total to use for the new bar.
    """
    self.n = 0
    if total is not None:
        self.total = total
    if self.disable:
        return
    self.last_print_n = 0
    self.last_print_t = self.start_t = self._time()
    self._ema_dn = EMA(self.smoothing)
    self._ema_dt = EMA(self.smoothing)
    self._ema_miniters = EMA(self.smoothing)
    self.refresh()
# Buggy code
def __new__(cls, *_, **__):
    # Create a new instance
    instance = object.__new__(cls)
    # Construct the lock if it does not exist
    with cls.get_lock():
        # Add to the list of instances
        if not hasattr(cls, "_instances"):
            cls._instances = WeakSet()
        cls._instances.add(instance)
        # Create the monitoring thread
        if cls.monitor_interval and (cls.monitor is None or not cls.monitor.report()):
            try:
                cls.monitor = TMonitor(cls, cls.monitor_interval)
            except Exception as e:  # pragma: nocover
                warn(
                    "tqdm:disabling monitor support"
                    " (monitor_interval = 0) due to:\n" + str(e),
                    TqdmMonitorWarning,
                    stacklevel=2,
                )
                cls.monitor_interval = 0
    # Return the instance
    return instance


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<timed exec> in <module>

/kaggle/usr/lib/nlp_profiler_class/nlp_profiler_class.py in apply_text_profiling(self, dataframe, text_column, params)
94         """
95
---> 96         return nlp_profiler.apply_text_profiling(dataframe, text_column, params)

/opt/conda/lib/python3.7/site-packages/nlp_profiler/core.py in apply_text_profiling(dataframe, text_column, params)
60             actions_mappings.remove(item)
61
---> 62     apply_profiling_progress_bar = get_progress_bar(actions_mappings)
63     for _, (param, action_description, action_function) in \
64             enumerate(apply_profiling_progress_bar):

/opt/conda/lib/python3.7/site-packages/nlp_profiler/generate_features/parallelisation_methods/__init__.py in get_progress_bar(values)
18
19 def get_progress_bar(values: list) -> tqdm:
---> 20     return tqdm(values, ncols=PROGRESS_BAR_WIDTH)
21
22

/opt/conda/lib/python3.7/site-packages/tqdm/asyncio.py in __new__(cls, *args, **kwargs)
64
65     def __new__(cls, *args, **kwargs):
---> 66         return cls.get_new(super(tqdm_asyncio, cls), std_tqdm, *args, **kwargs)
67
68

AttributeError: type object 'tqdm' has no attribute 'get_new'

# Fixed code
def __new__(cls, *_, **__):
    instance = object.__new__(cls)
    with cls.get_lock():  # also constructs lock if non-existent
        cls._instances.add(instance)
        # create monitoring thread
        if cls.monitor_interval and (cls.monitor is None or not cls.monitor.report()):
            try:
                cls.monitor = TMonitor(cls, cls.monitor_interval)
            except Exception as e:  # pragma: nocover
                warn(
                    "tqdm:disabling monitor support"
                    " (monitor_interval = 0) due to:\n" + str(e),
                    TqdmMonitorWarning,
                    stacklevel=2,
                )
                cls.monitor_interval = 0
    return instance
# Buggy code
def status_printer(file):
    """
    Manage the printing and in-place updating of a line of characters.
    Note that if the string is longer than a line, then in-place
    updating may not work (it will print a new line at each refresh).
    """
    fp = file
    fp_flush = getattr(fp, "flush", lambda: None)  # pragma: no cover

    def fp_write(s):
        fp.write(_unicode(s))
        fp_flush()

    last_len = [0]

    def print_status(s):
        len_s = len(s)
        fp_write("\r" + s + (" " * max(last_len[0] - len_s, 0)))
        last_len[0] = len_s

    return print_status


# Traceback (UnicodeEncodeError)
0%|                                                             | 0/20 [00:00<?, ?it/s]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/proj/venv/lib/python2.6/site-packages/tqdm/_tqdm.py", line 483, in __iter__
1 / avg_time if avg_time else None, bar_format))
File "/opt/proj/venv/lib/python2.6/site-packages/tqdm/_tqdm.py", line 95, in print_status
fp.write('\r' + s + (' ' * max(last_printed_len[0] - len_s, 0)))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-16: ordinal not in range(128)

# Fixed code
def status_printer(file):
    """
    Manage the printing and in-place updating of a line of characters.
    Note that if the string is longer than a line, then in-place
    updating may not work (it will print a new line at each refresh).
    """
    fp = _force_encoding(file) if file in (sys.stdout, sys.stderr) else file
    fp_flush = getattr(fp, "flush", lambda: None)  # pragma: no cover

    def fp_write(s):
        fp.write(_unicode(s))
        fp_flush()

    last_len = [0]

    def print_status(s):
        len_s = len(s)
        fp_write("\r" + s + (" " * max(last_len[0] - len_s, 0)))
        last_len[0] = len_s

    return print_status
# Buggy code
def set_postfix(self, ordered_dict=None, refresh=True, **kwargs):
    """
    Set/modify postfix (additional stats)
    with automatic formatting based on datatype.

    Parameters
    ----------
    ordered_dict  : dict or OrderedDict, optional
    refresh  : bool, optional
        Forces refresh [default: True].
    kwargs  : dict, optional
    """
    # Sort in alphabetical order to be more deterministic
    postfix = _OrderedDict([] if ordered_dict is None else ordered_dict)
    for key in sorted(kwargs.keys()):
        postfix[key] = kwargs[key]
    # Preprocess stats according to datatype
    for key in postfix.keys():
        # Number: limit the length of the string
        if isinstance(postfix[key], Number):
            postfix[key] = self.format_num(postfix[key])
        # Else for any other type, try to get the string conversion
        elif not isinstance(postfix[key], _basestring):
            postfix[key] = str(postfix[key])
        # Else if it's a string, don't need to preprocess anything
    # Stitch together to get the final postfix
    self.postfix = ", ".join(key + "=" + postfix[key].strip() for key in postfix.keys())
    if refresh:
        self.refresh()


# Traceback (UnicodeEncodeError)
0%|                                                             | 0/20 [00:00<?, ?it/s]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/proj/venv/lib/python2.6/site-packages/tqdm/_tqdm.py", line 483, in __iter__
1 / avg_time if avg_time else None, bar_format))
File "/opt/proj/venv/lib/python2.6/site-packages/tqdm/_tqdm.py", line 95, in print_status
fp.write('\r' + s + (' ' * max(last_printed_len[0] - len_s, 0)))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-16: ordinal not in range(128)

# Fixed code
def set_postfix(self, ordered_dict=None, refresh=True, **kwargs):
    """
    Set/modify postfix (additional stats)
    with automatic formatting based on datatype.

    Parameters
    ----------
    ordered_dict  : dict or OrderedDict, optional
    refresh  : bool, optional
        Forces refresh [default: True].
    kwargs  : dict, optional
    """
    # Sort in alphabetical order to be more deterministic
    postfix = OrderedDict([] if ordered_dict is None else ordered_dict)
    for key in sorted(kwargs.keys()):
        postfix[key] = kwargs[key]
    # Preprocess stats according to datatype
    for key in postfix.keys():
        # Number: limit the length of the string
        if isinstance(postfix[key], Number):
            postfix[key] = self.format_num(postfix[key])
        # Else for any other type, try to get the string conversion
        elif not isinstance(postfix[key], _basestring):
            postfix[key] = str(postfix[key])
        # Else if it's a string, don't need to preprocess anything
    # Stitch together to get the final postfix
    self.postfix = ", ".join(key + "=" + postfix[key].strip() for key in postfix.keys())
    if refresh:
        self.refresh()
# Buggy code
def __init__(self, *args, **kwds):
    if len(args) > 1:
        raise TypeError("expected at 1 argument, got %d", len(args))
    if not hasattr(self, "_keys"):
        self._keys = []
    self.update(*args, **kwds)


# Traceback (UnicodeEncodeError)
0%|                                                             | 0/20 [00:00<?, ?it/s]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/proj/venv/lib/python2.6/site-packages/tqdm/_tqdm.py", line 483, in __iter__
1 / avg_time if avg_time else None, bar_format))
File "/opt/proj/venv/lib/python2.6/site-packages/tqdm/_tqdm.py", line 95, in print_status
fp.write('\r' + s + (' ' * max(last_printed_len[0] - len_s, 0)))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-16: ordinal not in range(128)

# Fixed code
def __init__(self, callback, stream, method="read"):
    """
    Wrap a given `file`-like object's `read()` or `write()` to report
    lengths to the given `callback`
    """
    super(CallbackIOWrapper, self).__init__(stream)
    func = getattr(stream, method)
    if method == "write":

        @wraps(func)
        def write(data, *args, **kwargs):
            res = func(data, *args, **kwargs)
            callback(len(data))
            return res

        self.wrapper_setattr("write", write)
    elif method == "read":

        @wraps(func)
        def read(*args, **kwargs):
            data = func(*args, **kwargs)
            callback(len(data))
            return data

        self.wrapper_setattr("read", read)
    else:
        raise KeyError("Can only wrap read/write methods")
# Buggy code
def __init__(self):
    # Create global parallelism locks to avoid racing issues with parallel
    # bars works only if fork available (Linux/MacOSX, but not Windows)
    self.create_mp_lock()
    self.create_th_lock()
    cls = type(self)
    self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]


# Traceback (AssertionError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "tqdm_fail.py", line 11, in race_write
tqdm.write("spam")
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 586, in write
fp.write(end)
File "/usr/lib/python3.7/contextlib.py", line 119, in __exit__
next(self.gen)
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 616, in external_write_mode
cls._lock.release()
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 93, in release
lock.release()
AssertionError: attempt to release recursive lock not owned by thread

# Fixed code
def __init__(self):
    # Create global parallelism locks to avoid racing issues with parallel
    # bars works only if fork available (Linux/MacOSX, but not Windows)
    cls = type(self)
    root_lock = cls.th_lock
    if root_lock is not None:
        root_lock.acquire()
    cls.create_mp_lock()
    if root_lock is not None:
        root_lock.release()
    self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]
# Buggy code
def create_mp_lock(cls):
    if not hasattr(cls, "mp_lock"):
        try:
            from multiprocessing import RLock

            cls.mp_lock = RLock()  # multiprocessing lock
        except ImportError:  # pragma: no cover
            cls.mp_lock = None
        except OSError:  # pragma: no cover
            cls.mp_lock = None


# Traceback (AssertionError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "tqdm_fail.py", line 11, in race_write
tqdm.write("spam")
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 586, in write
fp.write(end)
File "/usr/lib/python3.7/contextlib.py", line 119, in __exit__
next(self.gen)
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 616, in external_write_mode
cls._lock.release()
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 93, in release
lock.release()
AssertionError: attempt to release recursive lock not owned by thread

# Fixed code
def create_mp_lock(cls):
    if not hasattr(cls, "mp_lock"):
        try:
            from multiprocessing import RLock

            cls.mp_lock = RLock()
        except (ImportError, OSError):  # pragma: no cover
            cls.mp_lock = None
# Buggy code
def create_th_lock(cls):
    if not hasattr(cls, "th_lock"):
        try:
            cls.th_lock = th.RLock()  # thread lock
        except OSError:  # pragma: no cover
            cls.th_lock = None


# Traceback (AssertionError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "tqdm_fail.py", line 11, in race_write
tqdm.write("spam")
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 586, in write
fp.write(end)
File "/usr/lib/python3.7/contextlib.py", line 119, in __exit__
next(self.gen)
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 616, in external_write_mode
cls._lock.release()
File "/home/duck/.local/lib/python3.7/site-packages/tqdm/std.py", line 93, in release
lock.release()
AssertionError: attempt to release recursive lock not owned by thread

# Fixed code
def create_th_lock(cls):
    assert hasattr(cls, "th_lock")
    warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
# Buggy code
def __init__(self, frac, default_len=10, charset=UTF):
    assert 0 <= frac <= 1
    assert default_len > 0
    self.frac = frac
    self.default_len = default_len
    self.charset = charset


# Traceback (AssertionError)
4.40.0 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31)
[GCC 7.3.0] linux
0%|                                                                                                                                                                  | 0/9.6 [00:00<?, ?it/s\
]Traceback (most recent call last):
File "tqdm_test.py", line 3, in <module>
for i in tqdm.tqdm(iterable=range(10), total=9.6):
File "/home/aronnem/miniconda3/envs/tqdm_test/lib/python3.6/site-packages/tqdm/std.py", line 1150, in __iter__
self.close()
File "/home/aronnem/miniconda3/envs/tqdm_test/lib/python3.6/site-packages/tqdm/std.py", line 1261, in close
self.display(pos=0)
File "/home/aronnem/miniconda3/envs/tqdm_test/lib/python3.6/site-packages/tqdm/std.py", line 1428, in display
self.sp(self.__repr__() if msg is None else msg)
File "/home/aronnem/miniconda3/envs/tqdm_test/lib/python3.6/site-packages/tqdm/std.py", line 1058, in __repr__
return self.format_meter(**self.format_dict)
File "/home/aronnem/miniconda3/envs/tqdm_test/lib/python3.6/site-packages/tqdm/std.py", line 482, in format_meter
charset=Bar.ASCII if ascii is True else ascii or Bar.UTF)
File "/home/aronnem/miniconda3/envs/tqdm_test/lib/python3.6/site-packages/tqdm/std.py", line 146, in __init__
assert 0 <= frac <= 1
AssertionError

# Fixed code
def __init__(self, frac, default_len=10, charset=UTF):
    if not (0 <= frac <= 1):
        warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2)
        frac = max(0, min(1, frac))
    assert default_len > 0
    self.frac = frac
    self.default_len = default_len
    self.charset = charset
# Buggy code
def write(cls, s, file=sys.stdout, end="\n"):
    """
    Print a message via tqdm (without overlap with bars)
    """
    fp = file

    # Clear all bars
    inst_cleared = []
    for inst in getattr(cls, "_instances", []):
        # Clear instance if in the target output file
        # or if write output + tqdm output are both either
        # sys.stdout or sys.stderr (because both are mixed in terminal)
        if inst.fp == fp or all(f in (sys.stdout, sys.stderr) for f in (fp, inst.fp)):
            inst.clear()
            inst_cleared.append(inst)
    # Write the message
    fp.write(s)
    fp.write(end)
    # Force refresh display of bars we cleared
    for inst in inst_cleared:
        inst.refresh()


# Traceback (ZeroDivisionError)
Traceback (most recent call last):
File "x.py", line 273, in train
bar.update(0)
File "C:\Python27\lib\site-packages\tqdm\_tqdm.py", line 808, in update
if self.avg_time is None \
ZeroDivisionError: float division by zero

# Fixed code
def write(cls, s, file=sys.stdout, end="\n"):
    """
    Print a message via tqdm (without overlap with bars)
    """
    fp = file

    # Clear all bars
    inst_cleared = []
    for inst in getattr(cls, "_instances", []):
        # Clear instance if in the target output file
        # or if write output + tqdm output are both either
        # sys.stdout or sys.stderr (because both are mixed in terminal)
        if inst.fp == fp or all(f in (sys.stdout, sys.stderr) for f in (fp, inst.fp)):
            inst.clear()
            inst_cleared.append(inst)
    # Write the message
    fp.write(s)
    fp.write(end)
    # Force refresh display of bars we cleared
    for inst in inst_cleared:
        # Avoid racing conditions by checking that the instance started
        if hasattr(inst, "started") and inst.started:
            inst.refresh()
# Buggy code
def __repr__(self):
    return self.format_meter(
        self.n,
        self.total,
        time() - self.last_print_t,
        self.ncols,
        self.desc,
        self.ascii,
        self.unit,
        self.unit_scale,
        1 / self.avg_time if self.avg_time else None,
        self.bar_format,
    )


# Traceback (ZeroDivisionError)
Traceback (most recent call last):
File "x.py", line 273, in train
bar.update(0)
File "C:\Python27\lib\site-packages\tqdm\_tqdm.py", line 808, in update
if self.avg_time is None \
ZeroDivisionError: float division by zero

# Fixed code
def __repr__(self):
    return self.format_meter(
        self.n,
        self.total,
        self._time() - self.start_t,
        self.ncols,
        self.desc,
        self.ascii,
        self.unit,
        self.unit_scale,
        1 / self.avg_time if self.avg_time else None,
        self.bar_format,
    )
# Buggy code
def validate(cls: Type["Model"], value: Any) -> "Model":
    value = cls._enforce_dict_if_root(value)
    if isinstance(value, dict):
        return cls(**value)
    elif isinstance(value, cls):
        return value.copy() if cls.__config__.copy_on_model_validation else value
    elif cls.__config__.orm_mode:
        return cls.from_orm(value)
    else:
        try:
            value_as_dict = dict(value)
        except (TypeError, ValueError) as e:
            raise DictError() from e
        return cls(**value_as_dict)


# Traceback (ValidationError)
from typing import Generic
from typing import TypeVar
from typing import List
from pydantic.generics import GenericModel
from pydantic import BaseModel

T = TypeVar("T")
class BaseList(GenericModel, Generic[T]):
__root__: List[T]

class Test(BaseModel):
mylist: BaseList[int]

Test(mylist=[1,2,3,4])
# Test(mylist=BaseList[int](__root__=[1, 2, 3, 4]))

Test(mylist=BaseList[int](__root__=[1,2,3,4]))
# ---------------------------------------------------------------------------
# ValidationError                           Traceback (most recent call last)
# <ipython-input-10-c373af038c5b> in <module>
# ----> 1 Test(mylist=BaseList[int](__root__=[1,2,3,4]))
#
# /usr/local/lib/python3.8/dist-packages/pydantic/main.cpython-38-x86_64-linux-gnu.so in pydantic.main.BaseModel.__init__()
#
# ValidationError: 1 validation error for Test
# mylist -> __root__
#   value is not a valid list (type=type_error.list)

# Fixed code
def validate(cls: Type["Model"], value: Any) -> "Model":
    if isinstance(value, cls):
        return value.copy() if cls.__config__.copy_on_model_validation else value

    value = cls._enforce_dict_if_root(value)
    if isinstance(value, dict):
        return cls(**value)
    elif cls.__config__.orm_mode:
        return cls.from_orm(value)
    else:
        try:
            value_as_dict = dict(value)
        except (TypeError, ValueError) as e:
            raise DictError() from e
        return cls(**value_as_dict)
# Buggy code
def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]:
    """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found."""
    if isinstance(v, TypeVar):
        yield v
    elif (
        hasattr(v, "__parameters__")
        and not get_origin(v)
        and lenient_issubclass(v, GenericModel)
    ):
        yield from v.__parameters__
    elif isinstance(v, Iterable):
        for var in v:
            yield from iter_contained_typevars(var)
    else:
        args = get_args(v)
        for arg in args:
            yield from iter_contained_typevars(arg)


# Traceback (RecursionError)
Traceback (most recent call last):
File "scratch_101.py", line 12, in <module>
GModelType = GModel[Fields, str]
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 110, in __class_getitem__
{param: None for param in iter_contained_typevars(typevars_map.values())}
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 110, in <dictcomp>
{param: None for param in iter_contained_typevars(typevars_map.values())}
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
yield from iter_contained_typevars(var)
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 220, in iter_contained_typevars
yield from iter_contained_typevars(arg)
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
yield from iter_contained_typevars(var)
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
yield from iter_contained_typevars(var)
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 216, in iter_contained_typevars
yield from iter_contained_typevars(var)
[Previous line repeated 982 more times]
File "virtualenvs\foobar-HGIuaRl7-py3.9\lib\site-packages\pydantic\generics.py", line 214, in iter_contained_typevars
elif isinstance(v, Iterable):
File "C:\Programs\Python\Python39_x64\lib\typing.py", line 657, in __instancecheck__
return self.__subclasscheck__(type(obj))
File "C:\Programs\Python\Python39_x64\lib\typing.py", line 789, in __subclasscheck__
return issubclass(cls, self.__origin__)
File "C:\Programs\Python\Python39_x64\lib\abc.py", line 102, in __subclasscheck__
return _abc_subclasscheck(cls, subclass)
RecursionError: maximum recursion depth exceeded in comparison

# Fixed code
def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]:
    """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found."""
    if isinstance(v, TypeVar):
        yield v
    elif (
        hasattr(v, "__parameters__")
        and not get_origin(v)
        and lenient_issubclass(v, GenericModel)
    ):
        yield from v.__parameters__
    elif isinstance(v, (DictValues, list)):
        for var in v:
            yield from iter_contained_typevars(var)
    else:
        args = get_args(v)
        for arg in args:
            yield from iter_contained_typevars(arg)