gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __getattr__(self, attr):
    # reminder: getattr is called after the normal lookups
    if attr in self._kwds:
        return self._kwds[attr]
    else:
        try:
            _getattr = super(SchemaBase, self).__getattr__
        except AttributeError:
            _getattr = super(SchemaBase, self).__getattribute__
        return _getattr(attr)


# Traceback (RecursionError)
(py36) C:\Develop\plab>python sandbox\test_altair_pickle.py
Traceback (most recent call last):
File "sandbox\test_altair_pickle.py", line 15, in <module>
pch = pickle.load(fid)
File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__
if attr in self._kwds:
File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__
if attr in self._kwds:
File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__
if attr in self._kwds:
[Previous line repeated 330 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object                           ```

# Fixed code
def __getattr__(self, attr):
    # reminder: getattr is called after the normal lookups
    if attr == "_kwds":
        raise AttributeError()
    if attr in self._kwds:
        return self._kwds[attr]
    else:
        try:
            _getattr = super(SchemaBase, self).__getattr__
        except AttributeError:
            _getattr = super(SchemaBase, self).__getattribute__
        return _getattr(attr)
# Buggy code
def _subclasses(cls):
    """Breadth-first sequence of classes which inherit from cls."""
    seen = set()
    current_set = {cls}
    while current_set:
        seen |= current_set
        current_set = set.union(*(set(cls.__subclasses__()) for cls in current_set))
        for cls in current_set - seen:
            yield cls


# Traceback (RecursionError)
(py36) C:\Develop\plab>python sandbox\test_altair_pickle.py
Traceback (most recent call last):
File "sandbox\test_altair_pickle.py", line 15, in <module>
pch = pickle.load(fid)
File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__
if attr in self._kwds:
File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__
if attr in self._kwds:
File "C:\opt\Anaconda3\envs\py36\lib\site-packages\altair\utils\schemapi.py", line 213, in __getattr__
if attr in self._kwds:
[Previous line repeated 330 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object                           ```

# Fixed code
def _subclasses(cls):
    """Breadth-first sequence of all classes which inherit from cls."""
    seen = set()
    current_set = {cls}
    while current_set:
        seen |= current_set
        current_set = set.union(*(set(cls.__subclasses__()) for cls in current_set))
        for cls in current_set - seen:
            yield cls
# Buggy code
def windowWillClose_(self, notification):
    # Delete the closed instance from the dict
    i = BrowserView.get_instance("window", notification.object())
    del BrowserView.instances[i.uid]


# Traceback (KeyError)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "ui_pywebview.py", line 23, in create_second_window
second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi)
File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window
background_color, debug, js_api, text_select, _webview_ready)
File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window
BrowserView.instances['master'].Invoke(Func[Type](create))
KeyError: 'master'

# Fixed code
def windowWillClose_(self, notification):
    # Delete the closed instance from the dict
    i = BrowserView.get_instance("window", notification.object())
    del BrowserView.instances[i.uid]

    if BrowserView.instances == {}:
        AppHelper.callAfter(BrowserView.app.stop_, self)
# Buggy code
def webView_didFinishLoadForFrame_(self, webview, frame):
    # Add the webview to the window if it's not yet the contentView
    i = BrowserView.get_instance("webkit", webview)

    if not webview.window():
        i.window.setContentView_(webview)
        i.window.makeFirstResponder_(webview)

        if i.js_bridge:
            i._set_js_api()

        if not i.text_select:
            i.webkit.windowScriptObject().evaluateWebScript_(disable_text_select)

        i.loaded.set()


# Traceback (KeyError)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "ui_pywebview.py", line 23, in create_second_window
second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi)
File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window
background_color, debug, js_api, text_select, _webview_ready)
File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window
BrowserView.instances['master'].Invoke(Func[Type](create))
KeyError: 'master'

# Fixed code
def webView_didFinishLoadForFrame_(self, webview, frame):
    # Add the webview to the window if it's not yet the contentView
    i = BrowserView.get_instance("webkit", webview)

    if i and not webview.window():
        i.window.setContentView_(webview)
        i.window.makeFirstResponder_(webview)

        if i.js_bridge:
            i._set_js_api()

        if not i.text_select:
            i.webkit.windowScriptObject().evaluateWebScript_(disable_text_select)

        i.loaded.set()
# Buggy code
def on_inspect_webview(self, inspector, webview):
    title = "Web Inspector - {}".format(self.window.get_title())
    uid = self.uid + "-inspector"

    inspector = BrowserView(
        uid,
        title,
        "",
        700,
        500,
        True,
        False,
        (300, 200),
        False,
        "#fff",
        False,
        None,
        self.webview_ready,
    )
    inspector.show()
    return inspector.webview


# Traceback (KeyError)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "ui_pywebview.py", line 23, in create_second_window
second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi)
File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window
background_color, debug, js_api, text_select, _webview_ready)
File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window
BrowserView.instances['master'].Invoke(Func[Type](create))
KeyError: 'master'

# Fixed code
def on_inspect_webview(self, inspector, webview):
    title = "Web Inspector - {}".format(self.window.get_title())
    uid = self.uid + "-inspector"

    inspector = BrowserView(
        uid,
        title,
        "",
        700,
        500,
        True,
        False,
        (300, 200),
        False,
        "#fff",
        False,
        None,
        True,
        self.webview_ready,
    )
    inspector.show()
    return inspector.webview
# Buggy code
def evaluate_js(self, script):
    def _evaluate_js():
        self.webview.execute_script(code)
        result_semaphore.release()

    self.eval_js_lock.acquire()
    result_semaphore = Semaphore(0)
    self.js_result_semaphores.append(result_semaphore)
    # Backup the doc title and store the result in it with a custom prefix
    unique_id = uuid1().hex
    code = "window.oldTitle{0} = document.title; document.title = {1};".format(
        unique_id, script
    )

    self.load_event.wait()
    glib.idle_add(_evaluate_js)
    result_semaphore.acquire()

    if not gtk.main_level():
        # Webview has been closed, don't proceed
        return None

    result = self.webview.get_title()
    result = (
        None
        if result == "undefined" or result == "null"
        else result
        if result == ""
        else json.loads(result)
    )

    # Restore document title and return
    code = "document.title = window.oldTitle{0}".format(unique_id)
    glib.idle_add(_evaluate_js)
    self.js_result_semaphores.remove(result_semaphore)
    self.eval_js_lock.release()

    return result


# Traceback (KeyError)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "ui_pywebview.py", line 23, in create_second_window
second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi)
File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window
background_color, debug, js_api, text_select, _webview_ready)
File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window
BrowserView.instances['master'].Invoke(Func[Type](create))
KeyError: 'master'

# Fixed code
def evaluate_js(self, script):
    def _evaluate_js():
        self.webview.execute_script(code)
        result_semaphore.release()

    self.eval_js_lock.acquire()
    result_semaphore = Semaphore(0)
    self.js_result_semaphores.append(result_semaphore)
    # Backup the doc title and store the result in it with a custom prefix
    unique_id = uuid1().hex
    code = "window.oldTitle{0} = document.title; document.title = {1};".format(
        unique_id, script
    )

    self.load_event.wait()
    glib.idle_add(_evaluate_js)
    result_semaphore.acquire()

    if not gtk.main_level():
        # Webview has been closed, don't proceed
        return None

    result = self.webview.get_title()
    result = (
        None
        if result == "undefined" or result == "null" or result is None
        else result
        if result == ""
        else json.loads(result)
    )

    # Restore document title and return
    code = "document.title = window.oldTitle{0}".format(unique_id)
    glib.idle_add(_evaluate_js)
    self.js_result_semaphores.remove(result_semaphore)
    self.eval_js_lock.release()

    return result
# Buggy code
def show_inspector(self):
    uid = self.parent().uid + "-inspector"
    try:
        # If inspector already exists, bring it to the front
        BrowserView.instances[uid].raise_()
        BrowserView.instances[uid].activateWindow()
    except KeyError:
        title = "Web Inspector - {}".format(self.parent().title)
        url = "http://localhost:{}".format(BrowserView.inspector_port)

        inspector = BrowserView(
            uid,
            title,
            url,
            700,
            500,
            True,
            False,
            (300, 200),
            False,
            "#fff",
            False,
            None,
            self.parent().webview_ready,
        )
        inspector.show()


# Traceback (KeyError)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "ui_pywebview.py", line 23, in create_second_window
second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi)
File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window
background_color, debug, js_api, text_select, _webview_ready)
File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window
BrowserView.instances['master'].Invoke(Func[Type](create))
KeyError: 'master'

# Fixed code
def show_inspector(self):
    uid = self.parent().uid + "-inspector"
    try:
        # If inspector already exists, bring it to the front
        BrowserView.instances[uid].raise_()
        BrowserView.instances[uid].activateWindow()
    except KeyError:
        title = "Web Inspector - {}".format(self.parent().title)
        url = "http://localhost:{}".format(BrowserView.inspector_port)

        inspector = BrowserView(
            uid,
            title,
            url,
            700,
            500,
            True,
            False,
            (300, 200),
            False,
            "#fff",
            False,
            None,
            True,
            self.parent().webview_ready,
        )
        inspector.show()
# Buggy code
def closeEvent(self, event):
    if self.confirm_quit:
        reply = QMessageBox.question(
            self,
            self.title,
            localization["global.quitConfirmation"],
            QMessageBox.Yes,
            QMessageBox.No,
        )

        if reply == QMessageBox.No:
            event.ignore()
            return

    event.accept()
    del BrowserView.instances[self.uid]

    try:  # Close inpsector if open
        BrowserView.instances[self.uid + "-inspector"].close()
        del BrowserView.instances[self.uid + "-inspector"]
    except KeyError:
        pass


# Traceback (KeyError)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "ui_pywebview.py", line 23, in create_second_window
second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi)
File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window
background_color, debug, js_api, text_select, _webview_ready)
File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window
BrowserView.instances['master'].Invoke(Func[Type](create))
KeyError: 'master'

# Fixed code
def closeEvent(self, event):
    if self.confirm_quit:
        reply = QMessageBox.question(
            self,
            self.title,
            localization["global.quitConfirmation"],
            QMessageBox.Yes,
            QMessageBox.No,
        )

        if reply == QMessageBox.No:
            event.ignore()
            return

    event.accept()
    del BrowserView.instances[self.uid]

    try:  # Close inspector if open
        BrowserView.instances[self.uid + "-inspector"].close()
        del BrowserView.instances[self.uid + "-inspector"]
    except KeyError:
        pass

    if len(BrowserView.instances) == 0:
        _app.exit()
# Buggy code
def create_window(
    uid,
    title,
    url,
    width,
    height,
    resizable,
    fullscreen,
    min_size,
    confirm_quit,
    background_color,
    debug,
    js_api,
    text_select,
    webview_ready,
):
    app = QApplication.instance() or QApplication([])

    def _create():
        browser = BrowserView(
            uid,
            title,
            url,
            width,
            height,
            resizable,
            fullscreen,
            min_size,
            confirm_quit,
            background_color,
            debug,
            js_api,
            text_select,
            webview_ready,
        )
        browser.show()

    if uid == "master":
        _create()
        app.exec_()
    else:
        i = list(BrowserView.instances.values())[0]  # arbitrary instance
        i.create_window_trigger.emit(_create)


# Traceback (KeyError)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "ui_pywebview.py", line 23, in create_second_window
second_window = webview.create_window("Window 2", os.path.abspath("web\\window2.html"), js_api=SecondWindowApi)
File "C:\Program Files\Python36\lib\site-packages\webview\__init__.py", line 183, in create_window
background_color, debug, js_api, text_select, _webview_ready)
File "C:\Program Files\Python36\lib\site-packages\webview\winforms.py", line 252, in create_window
BrowserView.instances['master'].Invoke(Func[Type](create))
KeyError: 'master'

# Fixed code
def create_window(
    uid,
    title,
    url,
    width,
    height,
    resizable,
    fullscreen,
    min_size,
    confirm_quit,
    background_color,
    debug,
    js_api,
    text_select,
    webview_ready,
):
    global _app
    _app = QApplication.instance() or QApplication([])

    def _create():
        browser = BrowserView(
            uid,
            title,
            url,
            width,
            height,
            resizable,
            fullscreen,
            min_size,
            confirm_quit,
            background_color,
            debug,
            js_api,
            text_select,
            webview_ready,
        )
        browser.show()

    if uid == "master":
        _create()
        _app.exec_()
    else:
        i = list(BrowserView.instances.values())[0]  # arbitrary instance
        i.create_window_trigger.emit(_create)
# Buggy code
def _switch(self, chara, charb):
    if self._isdigit(chara):
        return 0, not self._isdigit(charb)

    if self._isletter(chara):
        return 1, not self._isletter(charb)

    if self._isnonword(chara):
        return 2, not self._isnonword(charb)

    return "", True


# Traceback (TypeError)
dateparser.parse('Oct 1 2018 4:40 PM EST —')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "dateparser/conf.py", line 82, in wrapper
return f(*args, **kwargs)
File "dateparser/__init__.py", line 53, in parse
data = parser.get_date_data(date_string, date_formats)
File "dateparser/date.py", line 417, in get_date_data
locale, date_string, date_formats, settings=self._settings)
File "dateparser/date.py", line 189, in parse
return instance._parse()
File "dateparser/date.py", line 199, in _parse
date_obj = parser()
File "dateparser/date.py", line 222, in _try_parser
self._get_translated_date(), settings=self._settings)
File "dateparser/conf.py", line 82, in wrapper
return f(*args, **kwargs)
File "dateparser/date_parser.py", line 26, in parse
date_obj, period = parse(date_string, settings=settings)
File "dateparser/parser.py", line 70, in parse
raise exceptions.pop(-1)
File "dateparser/parser.py", line 64, in parse
res = parser(datestring, settings)
File "dateparser/parser.py", line 446, in parse
po = cls(tokens.tokenize(), settings)
File "dateparser/parser.py", line 192, in __init__
self.filtered_tokens = [t for t in self.tokens if t[1] <= 1]
File "dateparser/parser.py", line 192, in <listcomp>
self.filtered_tokens = [t for t in self.tokens if t[1] <= 1]
TypeError: '<=' not supported between instances of 'str' and 'int'

# Fixed code
def _switch(self, chara, charb):
    if self._isdigit(chara):
        return 0, not self._isdigit(charb)

    if self._isletter(chara):
        return 1, not self._isletter(charb)

    return 2, self._isdigit(charb) or self._isletter(charb)
# Buggy code
def get(key):
    result = None
    for sect in cnf:
        if sect in sections and key in cnf[sect]:
            result = cnf[sect][key]
    return result


# Traceback (TypeError)
2018-07-22 01:30:33,368 (48024/MainThread) mycli.main ERROR - traceback: 'Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/mycli/main.py", line 445, in connect
_connect()
File "/usr/local/lib/python3.7/site-packages/mycli/main.py", line 398, in _connect
socket, charset, local_infile, ssl)
File "/usr/local/lib/python3.7/site-packages/mycli/sqlexecute.py", line 52, in __init__
self.connect()
File "/usr/local/lib/python3.7/site-packages/mycli/sqlexecute.py", line 88, in connect
conv=conv, ssl=ssl)
File "/usr/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__
self.connect()
File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 598, in connect
self._request_authentication()
File "/usr/local/lib/python3.7/site-packages/pymysql/connections.py", line 808, in _request_authentication
authresp = _auth.scramble_native_password(self.password, self.salt)
File "/usr/local/lib/python3.7/site-packages/pymysql/_auth.py", line 31, in scramble_native_password
stage1 = sha1_new(password).digest()
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/hashlib.py", line 149, in __hash_new
return _hashlib.new(name, data)
TypeError: object supporting the buffer API required
'

# Fixed code
def get(key):
    result = None
    for sect in cnf:
        if sect in sections and key in cnf[sect]:
            result = cnf[sect][key]
    # HACK: if result is a list, then ConfigObj() probably decoded from
    # string by splitting on comma, so reconstruct string by joining on
    # comma.
    if isinstance(result, list):
        result = ",".join(result)
    return result
# Buggy code
def render_node(self, node):
    nodename = node.__class__.__name__
    methname = "render_" + nodename
    try:
        return getattr(self, methname)(node)
    except AttributeError:
        raise
        raise SyntaxError("Unknown syntax: " + nodename)


# Traceback (IndexError)
BrianObjectException: Original error and traceback:
Traceback (most recent call last):
File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run
exec(self.compiled_code, self.namespace)
File "(string)", line 19, in <module>
File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func
return values[timestep, i]
IndexError: arrays used as indices must be of integer (or boolean) type

Error encountered with object named "neurongroup".
Object was created here (most recent call only, full details in debug log):
File "<ipython-input-6-321ca0774a4a>", line 18, in <module>
method='euler')

An exception occured during the execution of code object neurongroup_stateupdater_codeobject.
The error was raised in the following line:
_v = (_lio_1 * I(t, 2.0 + i)) + v
IndexError: arrays used as indices must be of integer (or boolean) type
(See above for original error message and traceback.)

# Fixed code
def render_node(self, node):
    nodename = node.__class__.__name__
    methname = "render_" + nodename
    try:
        return getattr(self, methname)(node)
    except AttributeError:
        raise SyntaxError("Unknown syntax: " + nodename)
# Buggy code
def render_Num(self, node):
    return sympy.Float(node.n)


# Traceback (IndexError)
BrianObjectException: Original error and traceback:
Traceback (most recent call last):
File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/codegen/runtime/numpy_rt/numpy_rt.py", line 246, in run
exec(self.compiled_code, self.namespace)
File "(string)", line 19, in <module>
File "miniconda2/envs/brian/lib/python2.7/site-packages/brian2/input/timedarray.py", line 230, in unitless_timed_array_func
return values[timestep, i]
IndexError: arrays used as indices must be of integer (or boolean) type

Error encountered with object named "neurongroup".
Object was created here (most recent call only, full details in debug log):
File "<ipython-input-6-321ca0774a4a>", line 18, in <module>
method='euler')

An exception occured during the execution of code object neurongroup_stateupdater_codeobject.
The error was raised in the following line:
_v = (_lio_1 * I(t, 2.0 + i)) + v
IndexError: arrays used as indices must be of integer (or boolean) type
(See above for original error message and traceback.)

# Fixed code
def render_Num(self, node):
    if isinstance(node.n, numbers.Integral):
        return sympy.Integer(node.n)
    else:
        return sympy.Float(node.n)
# Buggy code
def conditional_write(
    self, line, stmt, variables, conditional_write_vars, created_vars
):
    if stmt.var in conditional_write_vars:
        subs = {}
        index = conditional_write_vars[stmt.var]
        # we replace all var with var[index], but actually we use this repl_string first because
        # we don't want to end up with lines like x[not_refractory[not_refractory]] when
        # multiple substitution passes are invoked
        repl_string = (
            "#$(@#&$@$*U#@)$@(#"  # this string shouldn't occur anywhere I hope! :)
        )
        for varname, var in variables.items():
            if isinstance(var, ArrayVariable) and not var.scalar:
                subs[varname] = varname + "[" + repl_string + "]"
        # all newly created vars are arrays and will need indexing
        for varname in created_vars:
            subs[varname] = varname + "[" + repl_string + "]"
        line = word_substitute(line, subs)
        line = line.replace(repl_string, index)
    return line


# Traceback (ValueError)
BrianObjectException: Original error and traceback:
Traceback (most recent call last):
File "E:\Dan\programming\brian2\brian2\codegen\runtime\numpy_rt\numpy_rt.py", line 122, in run
exec self.compiled_code in self.namespace
File "(string)", line 13, in <module>
ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,)

Error encountered with object named "neurongroup_1".
Object was created here (most recent call only, full details in debug log):
File "<ipython-input-2-ff5506ac93b4>", line 9, in <module>
G = NeuronGroup(100, eqs, reset='v=0', threshold='v>1', refractory=1*ms)

An exception occured during the execution of code object poissoninput_1_codeobject.
The error was raised in the following line:
v[not_refractory] += 0.1 * poissoninput_binomial_1(_vectorisation_idx)
ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,)
(See above for original error message and traceback.)

# Fixed code
def conditional_write(
    self, line, stmt, variables, conditional_write_vars, created_vars
):
    if stmt.var in conditional_write_vars:
        subs = {}
        index = conditional_write_vars[stmt.var]
        # we replace all var with var[index], but actually we use this repl_string first because
        # we don't want to end up with lines like x[not_refractory[not_refractory]] when
        # multiple substitution passes are invoked
        repl_string = (
            "#$(@#&$@$*U#@)$@(#"  # this string shouldn't occur anywhere I hope! :)
        )
        for varname, var in variables.items():
            if isinstance(var, ArrayVariable) and not var.scalar:
                subs[varname] = varname + "[" + repl_string + "]"
        # all newly created vars are arrays and will need indexing
        for varname in created_vars:
            subs[varname] = varname + "[" + repl_string + "]"
        # Also index _vectorisation_idx so that e.g. rand() works correctly
        subs["_vectorisation_idx"] = "_vectorisation_idx" + "[" + repl_string + "]"

        line = word_substitute(line, subs)
        line = line.replace(repl_string, index)
    return line
# Buggy code
def randn_func(vectorisation_idx):
    try:
        N = len(vectorisation_idx)
    except TypeError:
        N = int(vectorisation_idx)

    numbers = np.random.randn(N)
    if N == 1:
        return numbers[0]
    else:
        return numbers


# Traceback (ValueError)
BrianObjectException: Original error and traceback:
Traceback (most recent call last):
File "E:\Dan\programming\brian2\brian2\codegen\runtime\numpy_rt\numpy_rt.py", line 122, in run
exec self.compiled_code in self.namespace
File "(string)", line 13, in <module>
ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,)

Error encountered with object named "neurongroup_1".
Object was created here (most recent call only, full details in debug log):
File "<ipython-input-2-ff5506ac93b4>", line 9, in <module>
G = NeuronGroup(100, eqs, reset='v=0', threshold='v>1', refractory=1*ms)

An exception occured during the execution of code object poissoninput_1_codeobject.
The error was raised in the following line:
v[not_refractory] += 0.1 * poissoninput_binomial_1(_vectorisation_idx)
ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,)
(See above for original error message and traceback.)

# Fixed code
def randn_func(vectorisation_idx):
    try:
        N = len(vectorisation_idx)
        return np.random.randn(N)
    except TypeError:
        # scalar value
        return np.random.randn()
# Buggy code
def rand_func(vectorisation_idx):
    try:
        N = len(vectorisation_idx)
    except TypeError:
        N = int(vectorisation_idx)

    numbers = np.random.rand(N)
    if N == 1:
        return numbers[0]
    else:
        return numbers


# Traceback (ValueError)
BrianObjectException: Original error and traceback:
Traceback (most recent call last):
File "E:\Dan\programming\brian2\brian2\codegen\runtime\numpy_rt\numpy_rt.py", line 122, in run
exec self.compiled_code in self.namespace
File "(string)", line 13, in <module>
ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,)

Error encountered with object named "neurongroup_1".
Object was created here (most recent call only, full details in debug log):
File "<ipython-input-2-ff5506ac93b4>", line 9, in <module>
G = NeuronGroup(100, eqs, reset='v=0', threshold='v>1', refractory=1*ms)

An exception occured during the execution of code object poissoninput_1_codeobject.
The error was raised in the following line:
v[not_refractory] += 0.1 * poissoninput_binomial_1(_vectorisation_idx)
ValueError: operands could not be broadcast together with shapes (99,) (100,) (99,)
(See above for original error message and traceback.)

# Fixed code
def rand_func(vectorisation_idx):
    try:
        N = len(vectorisation_idx)
        return np.random.rand(N)
    except TypeError:
        # scalar value
        return np.random.rand()
# Buggy code
def push(self, sources):
    """
    Push spikes to the queue.

    Parameters
    ----------
    sources : ndarray of int
        The indices of the neurons that spiked.
    """
    if len(sources):
        start = self._source_start
        stop = self._source_end
        if start > 0:
            start_idx = bisect.bisect_left(sources, start)
        else:
            start_idx = 0
        if stop <= sources[-1]:
            stop_idx = bisect.bisect_left(sources, stop, lo=start_idx)
        else:
            stop_idx = len(self._neurons_to_synapses)
        sources = sources[start_idx:stop_idx]
        if len(sources) == 0:
            return
        synapse_indices = self._neurons_to_synapses
        indices = np.concatenate(
            [synapse_indices[source - start] for source in sources]
        ).astype(np.int32)
        if self._homogeneous:  # homogeneous delays
            self._insert_homogeneous(self._delays[0], indices)
        elif self._offsets is None:  # vectorise over synaptic events
            # there are no precomputed offsets, this is the case
            # (in particular) when there are dynamic delays
            self._insert(self._delays[indices], indices)
        else:  # offsets are precomputed
            self._insert(self._delays[indices], indices, self._offsets[indices])


# Traceback (IndexError)
SG = SpikeGeneratorGroup(1, [0], [0*ms])
G = NeuronGroup(1, 'v:1')
S = Synapses(SG, G, pre='v+=1')
run(0.1*ms)
Traceback (most recent call last):
...
File "/home/marcel/programming/brian2/brian2/synapses/spikequeue.py", line 254, in push
self._insert_homogeneous(self._delays[0], indices)
IndexError: index 0 is out of bounds for axis 0 with size 0

# Fixed code
def push(self, sources):
    """
    Push spikes to the queue.

    Parameters
    ----------
    sources : ndarray of int
        The indices of the neurons that spiked.
    """
    if len(sources) and len(self._delays):
        start = self._source_start
        stop = self._source_end
        if start > 0:
            start_idx = bisect.bisect_left(sources, start)
        else:
            start_idx = 0
        if stop <= sources[-1]:
            stop_idx = bisect.bisect_left(sources, stop, lo=start_idx)
        else:
            stop_idx = len(self._neurons_to_synapses)
        sources = sources[start_idx:stop_idx]
        if len(sources) == 0:
            return
        synapse_indices = self._neurons_to_synapses
        indices = np.concatenate(
            [synapse_indices[source - start] for source in sources]
        ).astype(np.int32)
        if self._homogeneous:  # homogeneous delays
            self._insert_homogeneous(self._delays[0], indices)
        elif self._offsets is None:  # vectorise over synaptic events
            # there are no precomputed offsets, this is the case
            # (in particular) when there are dynamic delays
            self._insert(self._delays[indices], indices)
        else:  # offsets are precomputed
            self._insert(self._delays[indices], indices, self._offsets[indices])
# Buggy code
def __call__(self, engine: Engine) -> None:
    """
    This method assumes self.batch_transform will extract metadata from the input batch.

    Args:
        engine: Ignite Engine, it can be a trainer, validator or evaluator.
    """
    _meta_data = self.batch_transform(engine.state.batch)
    if Key.FILENAME_OR_OBJ in _meta_data:
        # all gather filenames across ranks
        _meta_data[Key.FILENAME_OR_OBJ] = string_list_all_gather(
            _meta_data[Key.FILENAME_OR_OBJ]
        )
    # all gather predictions across ranks
    _engine_output = evenly_divisible_all_gather(
        self.output_transform(engine.state.output)
    )

    if self._expected_rank:
        self.saver.save_batch(_engine_output, _meta_data)


# Traceback (IndexError)
2021-02-09 02:12:24,253 - ignite.engine.engine.SupervisedEvaluator - INFO - Engine run resuming from iteration 0, epoch 0 until 1 epochs
2021-02-09 02:12:24,436 - ignite.engine.engine.SupervisedEvaluator - INFO - Restored all variables from /home/madil/dlmed/problems/pt_mmars/classification_chestxray_ea2/commands/../models/model.pt
2021-02-09 02:12:29,927 - ignite.engine.engine.SupervisedEvaluator - ERROR - Current run is terminating due to exception: list index out of range.
2021-02-09 02:12:29,928 - ignite.engine.engine.SupervisedEvaluator - ERROR - Exception: list index out of range
Traceback (most recent call last):
File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 812, in _run_once_on_dataset
self._fire_event(Events.ITERATION_COMPLETED)
File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 423, in _fire_event
func(*first, *(event_args + others), **kwargs)
File "/opt/monai/monai/handlers/classification_saver.py", line 97, in __call__
self.saver.save_batch(_engine_output, _meta_data)
File "/opt/monai/monai/data/csv_saver.py", line 95, in save_batch
self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None)
File "/opt/monai/monai/data/csv_saver.py", line 95, in <dictcomp>
self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None)
IndexError: list index out of range

# Fixed code
def __call__(self, engine: Engine) -> None:
    """
    This method assumes self.batch_transform will extract metadata from the input batch.

    Args:
        engine: Ignite Engine, it can be a trainer, validator or evaluator.
    """
    _meta_data = self.batch_transform(engine.state.batch)
    if Key.FILENAME_OR_OBJ in _meta_data:
        # all gather filenames across ranks, only filenames are necessary
        _meta_data = {
            Key.FILENAME_OR_OBJ: string_list_all_gather(_meta_data[Key.FILENAME_OR_OBJ])
        }
    # all gather predictions across ranks
    _engine_output = evenly_divisible_all_gather(
        self.output_transform(engine.state.output)
    )

    if self._expected_rank:
        self.saver.save_batch(_engine_output, _meta_data)
# Buggy code
def string_list_all_gather(strings: List[str], delimiter: str = "\t") -> List[str]:
    """
    Utility function for distributed data parallel to all gather a list of strings.

    Args:
        strings: a list of strings to all gather.
        delimiter: use the delimiter to join the string list to be a long string,
            then all gather across ranks and split to a list. default to "\t".

    """
    if idist.get_world_size() <= 1:
        return strings

    _joined = delimiter.join(strings)
    if get_torch_version_tuple() > (1, 6, 0):
        # all gather across all ranks
        _joined = delimiter.join(idist.all_gather(_joined))
    else:
        raise RuntimeError(
            "MetricsSaver can not save metric details in distributed mode with PyTorch < 1.7.0."
        )

    return _joined.split(delimiter)


# Traceback (IndexError)
2021-02-09 02:12:24,253 - ignite.engine.engine.SupervisedEvaluator - INFO - Engine run resuming from iteration 0, epoch 0 until 1 epochs
2021-02-09 02:12:24,436 - ignite.engine.engine.SupervisedEvaluator - INFO - Restored all variables from /home/madil/dlmed/problems/pt_mmars/classification_chestxray_ea2/commands/../models/model.pt
2021-02-09 02:12:29,927 - ignite.engine.engine.SupervisedEvaluator - ERROR - Current run is terminating due to exception: list index out of range.
2021-02-09 02:12:29,928 - ignite.engine.engine.SupervisedEvaluator - ERROR - Exception: list index out of range
Traceback (most recent call last):
File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 812, in _run_once_on_dataset
self._fire_event(Events.ITERATION_COMPLETED)
File "/opt/conda/lib/python3.6/site-packages/ignite/engine/engine.py", line 423, in _fire_event
func(*first, *(event_args + others), **kwargs)
File "/opt/monai/monai/handlers/classification_saver.py", line 97, in __call__
self.saver.save_batch(_engine_output, _meta_data)
File "/opt/monai/monai/data/csv_saver.py", line 95, in save_batch
self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None)
File "/opt/monai/monai/data/csv_saver.py", line 95, in <dictcomp>
self.save(data, {k: meta_data[k][i] for k in meta_data} if meta_data else None)
IndexError: list index out of range

# Fixed code
def string_list_all_gather(strings: List[str], delimiter: str = "\t") -> List[str]:
    """
    Utility function for distributed data parallel to all gather a list of strings.

    Args:
        strings: a list of strings to all gather.
        delimiter: use the delimiter to join the string list to be a long string,
            then all gather across ranks and split to a list. default to "\t".

    """
    if idist.get_world_size() <= 1:
        return strings

    _joined = delimiter.join(strings)
    if get_torch_version_tuple() > (1, 6, 0):
        # all gather across all ranks
        _joined = delimiter.join(idist.all_gather(_joined))
    else:
        raise RuntimeError("string all_gather can not be supported in PyTorch < 1.7.0.")

    return _joined.split(delimiter)
# Buggy code
def __call__(self, data):
    """
    Raises:
        KeyError: When a key in ``self.names`` already exists in ``data``.

    """
    d = dict(data)
    for key, new_key in zip(self.keys * self.times, self.names):
        if new_key in d:
            raise KeyError(f"Key {new_key} already exists in data.")
        d[new_key] = copy.deepcopy(d[key])
    return d


# Traceback (RuntimeError)
ERROR - Exception: Applying transform <monai.transforms.compose.Compose object at 0x7f0700e9deb8>.
Traceback (most recent call last):
File "/home/madil/dlmed/code/MONAI/monai/transforms/utils.py", line 309, in apply_transform
return transform(data)
File "/home/madil/dlmed/code/MONAI/monai/transforms/utility/dictionary.py", line 406, in __call__
d[new_key] = copy.deepcopy(d[key])
File "/opt/conda/lib/python3.6/copy.py", line 161, in deepcopy
y = copier(memo)
File "/opt/conda/lib/python3.6/site-packages/torch/tensor.py", line 38, in __deepcopy__
raise RuntimeError("Only Tensors created explicitly by the user "
RuntimeError: Only Tensors created explicitly by the user (graph leaves) support the deepcopy protocol at the moment

# Fixed code
def __call__(self, data):
    """
    Raises:
        KeyError: When a key in ``self.names`` already exists in ``data``.

    """
    d = dict(data)
    for key, new_key in zip(self.keys * self.times, self.names):
        if new_key in d:
            raise KeyError(f"Key {new_key} already exists in data.")
        if type(d[key]) == torch.Tensor:
            d[new_key] = d[key].detach().clone()
        else:
            d[new_key] = copy.deepcopy(d[key])
    return d
# Buggy code
def __init__(
    self,
    angle: Union[Sequence[float], float],
    keep_size: bool = True,
    mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR,
    padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER,
    align_corners: bool = False,
) -> None:
    self.angle = angle
    self.keep_size = keep_size
    self.mode: GridSampleMode = GridSampleMode(mode)
    self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode)
    self.align_corners = align_corners


# Traceback (AssertionError)
======================================================================
FAIL: test_training (__main__.IntegrationSegmentation3D)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests/test_integration_segmentation_3d.py", line 257, in test_training
rtol=1e-3,
File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose
verbose=verbose, header=header, equal_nan=equal_nan)
File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Not equal to tolerance rtol=0.001, atol=0

Mismatched elements: 6 / 6 (100%)
Max absolute difference: 0.01720129
Max relative difference: 0.04047175
x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818])
y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ])

----------------------------------------------------------------------
Ran 1 test in 92.377s

FAILED (failures=1)

# Fixed code
def __init__(
    self,
    angle: Union[Sequence[float], float],
    keep_size: bool = True,
    mode: Union[GridSampleMode, str] = GridSampleMode.BILINEAR,
    padding_mode: Union[GridSamplePadMode, str] = GridSamplePadMode.BORDER,
    align_corners: bool = False,
    dtype: Optional[np.dtype] = np.float64,
) -> None:
    self.angle = angle
    self.keep_size = keep_size
    self.mode: GridSampleMode = GridSampleMode(mode)
    self.padding_mode: GridSamplePadMode = GridSamplePadMode(padding_mode)
    self.align_corners = align_corners
    self.dtype = dtype
# Buggy code
def __call__(self, data):
    d = dict(data)
    for idx, key in enumerate(self.keys):
        meta_data = d[f"{key}_{self.meta_key_postfix}"]
        # resample array of each corresponding key
        # using affine fetched from d[affine_key]
        d[key], _, new_affine = self.spacing_transform(
            data_array=d[key],
            affine=meta_data["affine"],
            mode=self.mode[idx],
            padding_mode=self.padding_mode[idx],
            dtype=self.dtype[idx],
        )
        # set the 'affine' key
        meta_data["affine"] = new_affine
    return d


# Traceback (AssertionError)
======================================================================
FAIL: test_training (__main__.IntegrationSegmentation3D)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests/test_integration_segmentation_3d.py", line 257, in test_training
rtol=1e-3,
File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose
verbose=verbose, header=header, equal_nan=equal_nan)
File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Not equal to tolerance rtol=0.001, atol=0

Mismatched elements: 6 / 6 (100%)
Max absolute difference: 0.01720129
Max relative difference: 0.04047175
x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818])
y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ])

----------------------------------------------------------------------
Ran 1 test in 92.377s

FAILED (failures=1)

# Fixed code
def __call__(self, data):
    d = dict(data)
    for idx, key in enumerate(self.keys):
        meta_data = d[f"{key}_{self.meta_key_postfix}"]
        # resample array of each corresponding key
        # using affine fetched from d[affine_key]
        d[key], _, new_affine = self.spacing_transform(
            data_array=d[key],
            affine=meta_data["affine"],
            mode=self.mode[idx],
            padding_mode=self.padding_mode[idx],
            align_corners=self.align_corners[idx],
            dtype=self.dtype[idx],
        )
        # set the 'affine' key
        meta_data["affine"] = new_affine
    return d
# Buggy code
def __init__(
    self,
    keys: KeysCollection,
    angle: Union[Sequence[float], float],
    keep_size: bool = True,
    mode: GridSampleModeSequence = GridSampleMode.BILINEAR,
    padding_mode: GridSamplePadModeSequence = GridSamplePadMode.BORDER,
    align_corners: Union[Sequence[bool], bool] = False,
) -> None:
    super().__init__(keys)
    self.rotator = Rotate(angle=angle, keep_size=keep_size)

    self.mode = ensure_tuple_rep(mode, len(self.keys))
    self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
    self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))


# Traceback (AssertionError)
======================================================================
FAIL: test_training (__main__.IntegrationSegmentation3D)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests/test_integration_segmentation_3d.py", line 257, in test_training
rtol=1e-3,
File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 1533, in assert_allclose
verbose=verbose, header=header, equal_nan=equal_nan)
File "/opt/conda/lib/python3.6/site-packages/numpy/testing/_private/utils.py", line 846, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Not equal to tolerance rtol=0.001, atol=0

Mismatched elements: 6 / 6 (100%)
Max absolute difference: 0.01720129
Max relative difference: 0.04047175
x: array([0.543151, 0.471052, 0.453605, 0.438546, 0.437794, 0.407818])
y: array([0.544673, 0.475109, 0.444963, 0.427036, 0.433381, 0.42502 ])

----------------------------------------------------------------------
Ran 1 test in 92.377s

FAILED (failures=1)

# Fixed code
def __init__(
    self,
    keys: KeysCollection,
    angle: Union[Sequence[float], float],
    keep_size: bool = True,
    mode: GridSampleModeSequence = GridSampleMode.BILINEAR,
    padding_mode: GridSamplePadModeSequence = GridSamplePadMode.BORDER,
    align_corners: Union[Sequence[bool], bool] = False,
    dtype: Union[Sequence[Optional[np.dtype]], Optional[np.dtype]] = np.float64,
) -> None:
    super().__init__(keys)
    self.rotator = Rotate(angle=angle, keep_size=keep_size)

    self.mode = ensure_tuple_rep(mode, len(self.keys))
    self.padding_mode = ensure_tuple_rep(padding_mode, len(self.keys))
    self.align_corners = ensure_tuple_rep(align_corners, len(self.keys))
    self.dtype = ensure_tuple_rep(dtype, len(self.keys))