gurudesh/pytracebugs huggingface dataset:
# Buggy code
def decode_stdout(self, stdout):
    fallback_encoding = self.savvy_settings.get("fallback_encoding")
    silent_fallback = self.savvy_settings.get("silent_fallback")
    try:
        return stdout.decode()
    except UnicodeDecodeError as unicode_err:
        try:
            return stdout.decode("latin-1")
        except UnicodeDecodeError as unicode_err:
            if silent_fallback or sublime.ok_cancel_dialog(
                UTF8_PARSE_ERROR_MSG, "Fallback?"
            ):
                try:
                    return stdout.decode(fallback_encoding)
                except UnicodeDecodeError as fallback_err:
                    sublime.error_message(FALLBACK_PARSE_ERROR_MSG)
                    raise fallback_err
            raise unicode_err


# Traceback (UnicodeDecodeError)
'utf-8' codec can't decode byte 0x8a in position 16: invalid start byte

Traceback (most recent call last):
File "[...]Sublime\Data\Installed Packages\GitSavvy.sublime-package\core/git_command.py", line 215, in git
stdout, stderr = self.decode_stdout(stdout), stderr.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 16: invalid start byte

# Fixed code
def decode_stdout(self, stdout):
    fallback_encoding = self.savvy_settings.get("fallback_encoding")
    silent_fallback = self.savvy_settings.get("silent_fallback")
    try:
        return stdout.decode()
    except UnicodeDecodeError:
        try:
            return stdout.decode("latin-1")
        except UnicodeDecodeError as unicode_err:
            if silent_fallback or sublime.ok_cancel_dialog(
                UTF8_PARSE_ERROR_MSG, "Fallback?"
            ):
                try:
                    return stdout.decode(fallback_encoding)
                except UnicodeDecodeError as fallback_err:
                    sublime.error_message(FALLBACK_PARSE_ERROR_MSG)
                    raise fallback_err
            raise unicode_err
# Buggy code
def do_action(self, commit_hash, **kwargs):
    self.git("cherry-pick", commit_hash)
    self.view.window().status_message(
        "Commit %s cherry-picked successfully." % commit_hash
    )
    util.view.refresh_gitsavvy(self.window.active_view())


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/koenlageveen/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package/core/ui_mixins/quick_panel.py", line 526, in <lambda>
File "/Users/koenlageveen/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package/core/ui_mixins/quick_panel.py", line 530, in on_selection_async
File "/Users/koenlageveen/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package/core/commands/log.py", line 32, in <lambda>
File "/Users/koenlageveen/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package/core/commands/log.py", line 37, in on_done
File "/Users/koenlageveen/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package/core/commands/cherry_pick.py", line 17, in do_action
AttributeError: 'GsCherryPickCommand' object has no attribute 'view'

# Fixed code
def do_action(self, commit_hash, **kwargs):
    self.git("cherry-pick", commit_hash)
    sublime.active_window().status_message(
        "Commit %s cherry-picked successfully." % commit_hash
    )
    util.view.refresh_gitsavvy(self.window.active_view())
# Buggy code
def refresh_gitsavvy(
    view, refresh_sidebar=False, refresh_status_bar=True, interface_reset_cursor=False
):
    """
    Called after GitSavvy action was taken that may have effected the
    state of the Git repo.
    """
    if view is None:
        return

    if view.settings().get("git_savvy.interface") is not None:
        view.run_command(
            "gs_interface_refresh", {"nuke_cursors": interface_reset_cursor}
        )

    if view.settings().get("git_savvy.log_graph_view", False):
        view.run_command("gs_log_graph_refresh")

    if refresh_status_bar:
        view.run_command("gs_update_status_bar")

    if view.window() and refresh_sidebar:
        view.window().run_command("refresh_folder_list")


# Traceback (RuntimeError)
Traceback (most recent call last):
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 103, in git
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 297, in repo_path
RuntimeError: Window does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "core.commands.commit in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 142, in <lambda>
File "core.commands.commit in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 162, in run_async
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 106, in git
File "core.exceptions in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 7, in __init__
TypeError: GitSavvyError does not take keyword arguments

# Fixed code
def refresh_gitsavvy(
    view, refresh_sidebar=False, refresh_status_bar=True, interface_reset_cursor=False
):
    """
    Called after GitSavvy action was taken that may have effected the
    state of the Git repo.
    """
    if view is None:
        return

    if view.settings().get("git_savvy.interface") is not None:
        view.run_command(
            "gs_interface_refresh", {"nuke_cursors": interface_reset_cursor}
        )

    if view.settings().get("git_savvy.log_graph_view", False):
        view.run_command("gs_log_graph_refresh")

    if view.window() and refresh_status_bar:
        view.run_command("gs_update_status_bar")

    if view.window() and refresh_sidebar:
        view.window().run_command("refresh_folder_list")
# Buggy code
def run(self, edit, message=None):
    sublime.set_timeout_async(lambda: self.run_async(commit_message=message), 0)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 103, in git
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 297, in repo_path
RuntimeError: Window does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "core.commands.commit in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 142, in <lambda>
File "core.commands.commit in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 162, in run_async
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 106, in git
File "core.exceptions in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 7, in __init__
TypeError: GitSavvyError does not take keyword arguments

# Fixed code
def run(self, edit, message=None):
    self.commit_on_close = self.view.settings().get("git_savvy.commit_on_close")
    if self.commit_on_close:
        # make sure the view would not be closed by commiting synchronously
        self.run_async(commit_message=message)
    else:
        sublime.set_timeout_async(lambda: self.run_async(commit_message=message), 0)
# Buggy code
def run(self, edit):
    savvy_settings = sublime.load_settings("GitSavvy.sublime-settings")
    if savvy_settings.get("commit_on_close"):
        view_text = self.view.substr(sublime.Region(0, self.view.size()))
        help_text = self.view.settings().get("git_savvy.commit_view.help_text")
        message_txt = view_text.split(help_text)[0] if help_text in view_text else ""
        message_txt = message_txt.strip()

        if message_txt:
            self.view.run_command("gs_commit_view_do_commit", {"message": message_txt})


# Traceback (RuntimeError)
Traceback (most recent call last):
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 103, in git
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 297, in repo_path
RuntimeError: Window does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "core.commands.commit in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 142, in <lambda>
File "core.commands.commit in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 162, in run_async
File "core.git_command in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 106, in git
File "core.exceptions in /Users/user/Library/Application Support/Sublime Text 3/Installed Packages/GitSavvy.sublime-package", line 7, in __init__
TypeError: GitSavvyError does not take keyword arguments

# Fixed code
def run(self, edit):
    if self.view.settings().get("git_savvy.commit_on_close"):
        view_text = self.view.substr(sublime.Region(0, self.view.size()))
        help_text = self.view.settings().get("git_savvy.commit_view.help_text")
        message_txt = view_text.split(help_text)[0] if help_text in view_text else ""
        message_txt = message_txt.strip()

        if message_txt:
            self.view.run_command("gs_commit_view_do_commit", {"message": message_txt})
# Buggy code
def add_ignore(self, path_or_pattern):
    """
    Add the provided relative path or pattern to the repo's `.gitignore` file.
    """
    global linesep

    if not linesep:
        # Use native line ending on Windows only when `autocrlf` is set to `true`.
        if os.name == "nt":
            autocrlf = (
                self.git(
                    "config", "--global", "core.autocrlf", throw_on_stderr=False
                ).strip()
                == "true"
            )
            linesep = os.linesep if autocrlf else "\n"
        else:
            linesep = os.linesep

    with util.file.safe_open(
        os.path.join(self.repo_path, ".gitignore"), "at"
    ) as ignore_file:
        ignore_file.write(linesep + path_or_pattern + linesep)


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "/Applications/Sublime Text.app/Contents/MacOS/sublime_plugin.py", line 574, in run_
return self.run(edit)
File "/Users/alextegelid/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/interfaces/status.py", line 566, in run
self.add_ignore(os.path.join("/", fpath))
File "/Users/alextegelid/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/git_mixins/ignore.py", line 24, in add_ignore
ignore_file.write(linesep + path_or_pattern + linesep)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 4: ordinal not in range(128)

# Fixed code
def add_ignore(self, path_or_pattern):
    """
    Add the provided relative path or pattern to the repo's `.gitignore` file.
    """
    global linesep

    if not linesep:
        # Use native line ending on Windows only when `autocrlf` is set to `true`.
        if os.name == "nt":
            autocrlf = (
                self.git(
                    "config", "--global", "core.autocrlf", throw_on_stderr=False
                ).strip()
                == "true"
            )
            linesep = os.linesep if autocrlf else "\n"
        else:
            linesep = os.linesep

    gitignore = os.path.join(self.repo_path, ".gitignore")
    with util.file.safe_open(gitignore, "at", encoding="utf-8") as ignore_file:
        ignore_file.write(linesep + path_or_pattern + linesep)
# Buggy code
def do_clone(self):
    sublime.status_message("Start cloning {}".format(self.git_url))
    self.git("clone", self.git_url, self.suggested_git_root)
    sublime.status_message("Cloned repo successfully.")
    self.open_folder()
    util.view.refresh_gitsavvy(self.window.active_view())


# Traceback (ValueError)
Traceback (most recent call last):
File "/Users/pavel/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/git_command.py", line 126, in git
cwd=working_dir or self.repo_path,
File "/Users/pavel/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/git_command.py", line 213, in repo_path
return self._repo_path()
File "/Users/pavel/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/git_command.py", line 246, in _repo_path
return invalid_repo()
File "/Users/pavel/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/git_command.py", line 230, in invalid_repo
raise ValueError("Unable to determine Git repo path.")
ValueError: Unable to determine Git repo path.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/pavel/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/commands/init.py", line 131, in do_clone
self.git("clone", self.git_url, self.suggested_git_root)
File "/Users/pavel/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/git_command.py", line 134, in git
raise_error(e)
File "/Users/pavel/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/git_command.py", line 112, in raise_error
raise GitSavvyError(msg)
GitSavvy.core.exceptions.GitSavvyError: Unable to determine Git repo path.

# Fixed code
def do_clone(self):
    sublime.status_message("Start cloning {}".format(self.git_url))
    self.git("clone", self.git_url, self.suggested_git_root, working_dir=".")
    sublime.status_message("Cloned repo successfully.")
    self.open_folder()
    util.view.refresh_gitsavvy(self.window.active_view())
# Buggy code
def run_async(self):
    log, cursor = self.interface.get_log()
    if log is None or cursor is None or cursor == -1:
        return

    branch_name, ref = self.interface.get_branch_state()

    current = log[cursor]
    if current["branch_name"] != branch_name:
        sublime.error_message("Current branch does not match expected. Cannot undo.")
        return

    try:
        self.checkout_ref(current["ref_before"])
        self.git("branch", "-f", branch_name, "HEAD")
        cursor -= 1

    except Exception as e:
        sublime.error_message("Error encountered. Cannot undo.")
        raise e

    finally:
        self.checkout_ref(branch_name)
        self.interface.set_log(log, cursor)
        util.view.refresh_gitsavvy(self.view)


# Traceback (ValueError)
Traceback (most recent call last):
File "/Users/kyank/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/interfaces/rebase.py", line 353, in run_async
branch_name, ref = self.interface.get_branch_state()
ValueError: too many values to unpack (expected 2)

# Fixed code
def run_async(self):
    log, cursor = self.interface.get_log()
    if log is None or cursor is None or cursor == -1:
        return

    branch_name, ref, _ = self.interface.get_branch_state()

    current = log[cursor]
    if current["branch_name"] != branch_name:
        sublime.error_message("Current branch does not match expected. Cannot undo.")
        return

    try:
        self.checkout_ref(current["ref_before"])
        self.git("branch", "-f", branch_name, "HEAD")
        cursor -= 1

    except Exception as e:
        sublime.error_message("Error encountered. Cannot undo.")
        raise e

    finally:
        self.checkout_ref(branch_name)
        self.interface.set_log(log, cursor)
        util.view.refresh_gitsavvy(self.view)
# Buggy code
def run_async(self):
    log, cursor = self.interface.get_log()
    if log is None or cursor is None or cursor == len(log) - 1:
        return

    branch_name, ref = self.interface.get_branch_state()

    undone_action = log[cursor + 1]
    if undone_action["branch_name"] != branch_name:
        sublime.error_message("Current branch does not match expected. Cannot redo.")
        return

    try:
        self.checkout_ref(undone_action["ref_after"])
        self.git("branch", "-f", branch_name, "HEAD")
        cursor += 1

    except Exception as e:
        sublime.error_message("Error encountered. Cannot redo.")
        raise e

    finally:
        self.checkout_ref(branch_name)
        self.interface.set_log(log, cursor)
        util.view.refresh_gitsavvy(self.view)


# Traceback (ValueError)
Traceback (most recent call last):
File "/Users/kyank/Library/Application Support/Sublime Text 3/Packages/GitSavvy/core/interfaces/rebase.py", line 353, in run_async
branch_name, ref = self.interface.get_branch_state()
ValueError: too many values to unpack (expected 2)

# Fixed code
def run_async(self):
    log, cursor = self.interface.get_log()
    if log is None or cursor is None or cursor == len(log) - 1:
        return

    branch_name, ref, _ = self.interface.get_branch_state()

    undone_action = log[cursor + 1]
    if undone_action["branch_name"] != branch_name:
        sublime.error_message("Current branch does not match expected. Cannot redo.")
        return

    try:
        self.checkout_ref(undone_action["ref_after"])
        self.git("branch", "-f", branch_name, "HEAD")
        cursor += 1

    except Exception as e:
        sublime.error_message("Error encountered. Cannot redo.")
        raise e

    finally:
        self.checkout_ref(branch_name)
        self.interface.set_log(log, cursor)
        util.view.refresh_gitsavvy(self.view)
# Buggy code
def search_user_directory(self, term: str) -> List[User]:
    """
    Search user directory for a given term, returning a list of users
    Args:
        term: term to be searched for
    Returns:
        user_list: list of users returned by server-side search
    """
    response = self.api._send("POST", "/user_directory/search", {"search_term": term})
    try:
        return [
            User(self.api, _user["user_id"], _user["display_name"])
            for _user in response["results"]
        ]
    except KeyError:
        return []


# Traceback (matrix_client.errors.MatrixRequestError)
Traceback (most recent call last):
File "raiden/ui/cli.py", line 617, in run
File "raiden/ui/runners.py", line 21, in run_services
File "raiden/ui/app.py", line 446, in run_app
File "raiden/app.py", line 90, in start
File "raiden/raiden_service.py", line 444, in start
File "raiden/raiden_service.py", line 552, in _start_transport
File "raiden/network/transport/matrix/transport.py", line 449, in start
File "raiden/network/transport/matrix/utils.py", line 711, in login
File "raiden/network/transport/matrix/utils.py", line 623, in first_login
File "matrix_client/client.py", line 270, in login
File "matrix_client/api.py", line 160, in login
File "raiden/network/transport/matrix/client.py", line 180, in _send
File "matrix_client/api.py", line 691, in _send
matrix_client.errors.MatrixRequestError: 500: {"errcode":"M_UNKNOWN","error":"Internal server error"}
``

# Fixed code
def search_user_directory(self, term: str) -> List[User]:
    """
    Search user directory for a given term, returning a list of users
    Args:
        term: term to be searched for
    Returns:
        user_list: list of users returned by server-side search
    """
    try:
        response = self.api._send(
            "POST", "/user_directory/search", {"search_term": term}
        )
    except MatrixRequestError as ex:
        if ex.code >= 500:
            log.error(
                "Ignoring Matrix error in `search_user_directory`",
                exc_info=ex,
                term=term,
            )
            return list()
        else:
            raise ex
    try:
        return [
            User(self.api, _user["user_id"], _user["display_name"])
            for _user in response["results"]
        ]
    except KeyError:
        return list()
# Buggy code
def get(
    self, token_address: TokenAddress = None, target_address: Address = None
) -> Response:
    kwargs = validate_query_params(self.get_schema)
    return self.rest_api.get_raiden_events_payment_history_with_timestamps(
        registry_address=self.rest_api.raiden_api.raiden.default_registry.address,
        token_address=token_address,
        target_address=target_address,
        **kwargs,
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 854, in gevent._greenlet.Greenlet.run
File "raiden/api/rest.py", line 409, in _run
File "gevent/baseserver.py", line 389, in serve_forever
File "src/gevent/event.py", line 133, in gevent._event.Event.wait
File "src/gevent/_abstract_linkable.py", line 208, in gevent.__abstract_linkable.AbstractLinkable._wait
File "src/gevent/_abstract_linkable.py", line 178, in gevent.__abstract_linkable.AbstractLinkable._wait_core
File "src/gevent/_abstract_linkable.py", line 196, in gevent.__abstract_linkable.AbstractLinkable._wait_core
File "src/gevent/_abstract_linkable.py", line 182, in gevent.__abstract_linkable.AbstractLinkable._wait_core
File "src/gevent/_greenlet_primitives.py", line 61, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
File "src/gevent/_greenlet_primitives.py", line 61, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
File "src/gevent/_greenlet_primitives.py", line 65, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
File "src/gevent/__greenlet_primitives.pxd", line 35, in gevent.__greenlet_primitives._greenlet_switch
TypeError: post() missing 1 required positional argument: 'target_address'
2020-06-02T08:47:33Z <Greenlet "APIServer|Greenlet-0" at 0x7f885b0175f0: _run> failed with TypeError

# Fixed code
def get(self, token_address: TokenAddress, target_address: Address) -> Response:
    kwargs = validate_query_params(self.get_schema)
    return self.rest_api.get_raiden_events_payment_history_with_timestamps(
        registry_address=self.rest_api.raiden_api.raiden.default_registry.address,
        token_address=token_address,
        target_address=target_address,
        **kwargs,
    )
# Buggy code
def check_handler(self) -> None:
    """Check handler executed after the poll backend returns.

    Note:
    - For each of the watchers in the ready state there will be a callback,
      which will do work related to the watcher (e.g. read from a socket).
      This time must not be accounted for in the Idle timeout, therefore
      this handler must have a high priority.
    """
    curr_time = time.time()

    # It is possible for the check_handler to be executed before the
    # prepare_handler, this happens when the watchers are installed by a
    # greenlet that was switched onto because of IO (IOW, Idle.enable is
    # called while the event loop is executing watchers, after the `poll`)
    if self.before_poll is not None:
        self.measurements.append(  # pylint: disable=no-member
            IdleMeasurement(self.before_poll, curr_time)
        )

        while curr_time - self.measurements_start > self.measurement_interval:
            self.measurements.pop()  # pylint: disable=no-member

    if curr_time - self.last_print >= self.measurement_interval:
        self.log()
        self.last_print = curr_time


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/raiden/utils/debugging.py", line 123, in check_handler
while curr_time - self.measurements_start > self.measurement_interval:
File "/usr/local/lib/python3.7/site-packages/raiden/utils/debugging.py", line 137, in measurements_start
return self.measurements[0].before_poll
IndexError: list index out of range
2020-01-23T05:20:56Z <check at 0x7ff9417d3978 active callback=<bound method Idle.check_handler of Idle(measurement_interval=10, before_poll=1579756855.8080018, last_print=1579756845.8452065, measurements=[])> args=()> failed with IndexError

# Fixed code
def check_handler(self) -> None:
    """Check handler executed after the poll backend returns.

    Note:
    - For each of the watchers in the ready state there will be a callback,
      which will do work related to the watcher (e.g. read from a socket).
      This time must not be accounted for in the Idle timeout, therefore
      this handler must have a high priority.
    """
    curr_time = time.time()

    # It is possible for the check_handler to be executed before the
    # prepare_handler, this happens when the watchers are installed by a
    # greenlet that was switched onto because of IO (IOW, Idle.enable is
    # called while the event loop is executing watchers, after the `poll`)
    if self.before_poll is not None:
        self.measurements.append(  # pylint: disable=no-member
            IdleMeasurement(self.before_poll, curr_time)
        )

        while (
            self.measurements
            and curr_time - self.measurements_start > self.measurement_interval
        ):
            self.measurements.pop()  # pylint: disable=no-member

    if curr_time - self.last_print >= self.measurement_interval:
        self.log()
        self.last_print = curr_time
# Buggy code
def log(self) -> None:
    log.debug(
        "Idle",
        start=self.measurements_start,
        context_switches=self.context_switches,
        idled=self.idled,
        interval=self.running_interval,
        idle_pct=self.idled_pct,
        measurements=self.measurements,
    )


# Traceback (IndexError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/raiden/utils/debugging.py", line 123, in check_handler
while curr_time - self.measurements_start > self.measurement_interval:
File "/usr/local/lib/python3.7/site-packages/raiden/utils/debugging.py", line 137, in measurements_start
return self.measurements[0].before_poll
IndexError: list index out of range
2020-01-23T05:20:56Z <check at 0x7ff9417d3978 active callback=<bound method Idle.check_handler of Idle(measurement_interval=10, before_poll=1579756855.8080018, last_print=1579756845.8452065, measurements=[])> args=()> failed with IndexError

# Fixed code
def log(self) -> None:
    if not self.measurements:
        log.debug(
            "Idle",
            context_switches=self.context_switches,
            measurements=self.measurements,
        )
        return
    log.debug(
        "Idle",
        start=self.measurements_start,
        context_switches=self.context_switches,
        idled=self.idled,
        interval=self.running_interval,
        idle_pct=self.idled_pct,
        measurements=self.measurements,
    )
# Buggy code
def __init__(self, ta, stats, run_obj="runtime"):
    """
    Constructor

    Parameters
    ----------
        ta : list
            target algorithm command line as list of arguments
        stats: Stats()
             stats object to collect statistics about runtime and so on
        run_obj: str
            run objective of SMAC
    """
    self.ta = ta
    self.stats = stats
    self.logger = logging.getLogger("ExecuteTARun")

    self._supports_memory_limit = False


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/lindauer/git/SMAC3/scripts/smac", line 20, in <module>
smac.main_cli()
File "/home/lindauer/git/SMAC3/smac/smac_cli.py", line 47, in main_cli
smbo.run(max_iters=args_.max_iterations)
File "/home/lindauer/git/SMAC3/smac/smbo/smbo.py", line 282, in run
self.incumbent = self.run_initial_design()
File "/home/lindauer/git/SMAC3/smac/smbo/smbo.py", line 239, in run_initial_design
instance_specific=self.scenario.instance_specific.get(rand_inst, "0"))
File "/home/lindauer/git/SMAC3/smac/tae/execute_ta_run.py", line 103, in start
if self._supports_memory_limit is True:
AttributeError: 'ExecuteTARunOld' object has no attribute '_supports_memory_limit'

# Fixed code
def __init__(self, ta, stats, run_obj="runtime", par_factor=1):
    """
    Constructor

    Parameters
    ----------
        ta : list
            target algorithm command line as list of arguments
        stats: Stats()
             stats object to collect statistics about runtime and so on
        run_obj: str
            run objective of SMAC
    """
    self.ta = ta
    self.stats = stats
    self.run_obj = run_obj
    self.par_factor = par_factor

    self.logger = logging.getLogger(self.__class__.__name__)
    self._supports_memory_limit = False
# Buggy code
def update_cost(self, config, cost):
    config_id = self.config_ids[config.__repr__()]
    self.cost_per_config[config_id] = cost


# Traceback (KeyError)
KeyError                                  Traceback (most recent call last)
<ipython-input-10-a9f6024df581> in <module>()
38 smbo = SMBO(scenario=scenario, rng=1, tae_runner=taf)
39 Stats.scenario = scenario
---> 40 smbo.run(max_iters=100)
41
42 print("Final Incumbent: %s" % (smbo.incumbent))

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/smbo.pyc in run(self, max_iters)
291                 run_history=self.runhistory,
292                 objective=self.objective,
--> 293                 time_bound=max(0.01, time_spend))
294
295             # TODO: Write run history into database

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/intensification.pyc in intensify(self, challengers, incumbent, run_history, objective, time_bound)
226                 chall_inst_seeds = set(map(lambda x: (
227                     x.instance, x.seed), run_history.get_runs_for_config(challenger)))
--> 228                 chal_perf = objective(challenger, run_history, chall_inst_seeds)
229                 run_history.update_cost(challenger, chal_perf)
230

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/objective.pyc in average_cost(config, run_history, instance_seed_pairs)
116     float
117     """
--> 118     return np.mean(_cost(config, run_history, instance_seed_pairs))
119
120 def sum_cost(config, run_history, instance_seed_pairs=None):

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/objective.pyc in _cost(config, run_history, instance_seed_pairs)
93     for i, r in instance_seed_pairs:
94         k = run_history.RunKey(id_, i, r)
---> 95         costs.append(run_history.data[k].cost)
96     return costs
97

KeyError: RunKey(config_id=36, instance_id='2', seed=931243971)

# Fixed code
def update_cost(self, config, cost):
    config_id = self.config_ids[config]
    self.cost_per_config[config_id] = cost
# Buggy code
def get_cost(self, config):
    config_id = self.config_ids[config.__repr__()]
    return self.cost_per_config[config_id]


# Traceback (KeyError)
KeyError                                  Traceback (most recent call last)
<ipython-input-10-a9f6024df581> in <module>()
38 smbo = SMBO(scenario=scenario, rng=1, tae_runner=taf)
39 Stats.scenario = scenario
---> 40 smbo.run(max_iters=100)
41
42 print("Final Incumbent: %s" % (smbo.incumbent))

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/smbo.pyc in run(self, max_iters)
291                 run_history=self.runhistory,
292                 objective=self.objective,
--> 293                 time_bound=max(0.01, time_spend))
294
295             # TODO: Write run history into database

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/intensification.pyc in intensify(self, challengers, incumbent, run_history, objective, time_bound)
226                 chall_inst_seeds = set(map(lambda x: (
227                     x.instance, x.seed), run_history.get_runs_for_config(challenger)))
--> 228                 chal_perf = objective(challenger, run_history, chall_inst_seeds)
229                 run_history.update_cost(challenger, chal_perf)
230

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/objective.pyc in average_cost(config, run_history, instance_seed_pairs)
116     float
117     """
--> 118     return np.mean(_cost(config, run_history, instance_seed_pairs))
119
120 def sum_cost(config, run_history, instance_seed_pairs=None):

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/objective.pyc in _cost(config, run_history, instance_seed_pairs)
93     for i, r in instance_seed_pairs:
94         k = run_history.RunKey(id_, i, r)
---> 95         costs.append(run_history.data[k].cost)
96     return costs
97

KeyError: RunKey(config_id=36, instance_id='2', seed=931243971)

# Fixed code
def get_cost(self, config):
    config_id = self.config_ids[config]
    return self.cost_per_config[config_id]
# Buggy code
def save_json(self, fn="runhistory.json"):
    """
    saves runhistory on disk

    Parameters
    ----------
    fn : str
        file name
    """

    id_vec = dict(
        [(id_, conf.get_array().tolist()) for id_, conf in self.ids_config.items()]
    )

    data = [
        (
            [
                int(k.config_id),
                str(k.instance_id) if k.instance_id is not None else None,
                int(k.seed),
            ],
            list(v),
        )
        for k, v in self.data.items()
    ]

    with open(fn, "w") as fp:
        json.dump({"data": data, "id_config": id_vec}, fp)


# Traceback (KeyError)
KeyError                                  Traceback (most recent call last)
<ipython-input-10-a9f6024df581> in <module>()
38 smbo = SMBO(scenario=scenario, rng=1, tae_runner=taf)
39 Stats.scenario = scenario
---> 40 smbo.run(max_iters=100)
41
42 print("Final Incumbent: %s" % (smbo.incumbent))

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/smbo.pyc in run(self, max_iters)
291                 run_history=self.runhistory,
292                 objective=self.objective,
--> 293                 time_bound=max(0.01, time_spend))
294
295             # TODO: Write run history into database

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/intensification.pyc in intensify(self, challengers, incumbent, run_history, objective, time_bound)
226                 chall_inst_seeds = set(map(lambda x: (
227                     x.instance, x.seed), run_history.get_runs_for_config(challenger)))
--> 228                 chal_perf = objective(challenger, run_history, chall_inst_seeds)
229                 run_history.update_cost(challenger, chal_perf)
230

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/objective.pyc in average_cost(config, run_history, instance_seed_pairs)
116     float
117     """
--> 118     return np.mean(_cost(config, run_history, instance_seed_pairs))
119
120 def sum_cost(config, run_history, instance_seed_pairs=None):

/home/feurerm/virtualenvs/ml2016/local/lib/python2.7/site-packages/smac/smbo/objective.pyc in _cost(config, run_history, instance_seed_pairs)
93     for i, r in instance_seed_pairs:
94         k = run_history.RunKey(id_, i, r)
---> 95         costs.append(run_history.data[k].cost)
96     return costs
97

KeyError: RunKey(config_id=36, instance_id='2', seed=931243971)

# Fixed code
def save_json(self, fn="runhistory.json"):
    """
    saves runhistory on disk

    Parameters
    ----------
    fn : str
        file name
    """

    configs = {id_: conf.get_dictionary() for id_, conf in self.ids_config.items()}

    data = [
        (
            [
                int(k.config_id),
                str(k.instance_id) if k.instance_id is not None else None,
                int(k.seed),
            ],
            list(v),
        )
        for k, v in self.data.items()
    ]

    with open(fn, "w") as fp:
        json.dump({"data": data, "configs": configs}, fp)
# Buggy code
def _update_package_cache(self):
    if (
        not self.package_caching
        or not config.cache_packages_path
        or not config.write_package_cache
    ):
        return

    # see PackageCache.add_variants_async
    if not system.is_production_rez_install:
        return

    pkgcache = PackageCache(config.cache_packages_path)
    pkgcache.add_variants_async(self.resolved_packages)


# Traceback (TypeError)
Traceback (most recent call last):
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/bin/rez/rez", line 8, in <module>
sys.exit(run_rez())
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/lib/python2.7/site-packages/rez/cli/_entry_points.py", line 64, in run_rez
return run()
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/lib/python2.7/site-packages/rez/cli/_main.py", line 160, in run
returncode = run_cmd()
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/lib/python2.7/site-packages/rez/cli/_main.py", line 152, in run_cmd
return func(opts, opts.parser, extra_arg_groups)
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/lib/python2.7/site-packages/rez/cli/env.py", line 211, in command
package_caching=(not opts.no_pkg_cache)
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/lib/python2.7/site-packages/rez/resolved_context.py", line 316, in __init__
self._update_package_cache()
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/lib/python2.7/site-packages/rez/resolved_context.py", line 1572, in _update_package_cache
pkgcache.add_variants_async(self.resolved_packages)
File "/library/rez/user_packages/rez-pre-release/rez/2.61.0.pr/os-CentOS-7/python-2.7/lib/python2.7/site-packages/rez/package_cache.py", line 379, in add_variants_async
for variant in variants:
TypeError: 'NoneType' object is not iterable

# Fixed code
def _update_package_cache(self):
    if (
        not self.package_caching
        or not config.cache_packages_path
        or not config.write_package_cache
        or not self.success
    ):
        return

    # see PackageCache.add_variants_async
    if not system.is_production_rez_install:
        return

    pkgcache = PackageCache(config.cache_packages_path)
    pkgcache.add_variants_async(self.resolved_packages)
# Buggy code
def load_resource(self, item):
    resource = super(ConfigTable, self).load_resource(item)
    resource["CreationDateTime"] = datetime.fromtimestamp(
        resource["CreationDateTime"] / 1000.0
    )
    if (
        "BillingModeSummary" in resource
        and "LastUpdateToPayPerRequestDateTime" in resource["BillingModeSummary"]
    ):
        resource["BillingModeSummary"]["LastUpdateToPayPerRequestDateTime"] = (
            datetime.fromtimestamp(
                resource["BillingModeSummary"]["LastUpdateToPayPerRequestDateTime"]
                / 1000.0
            )
        )

    sse_info = resource.pop("Ssedescription", None)
    if sse_info is None:
        return resource
    resource["SSEDescription"] = sse_info
    for k, r in (("KmsmasterKeyArn", "KMSMasterKeyArn"), ("Ssetype", "SSEType")):
        if k in sse_info:
            sse_info[r] = sse_info.pop(k)
    return resource


# Traceback (TypeError)
[ERROR] TypeError: unsupported operand type(s) for /: 'datetime.datetime' and 'float'
Traceback (most recent call last):
File "/var/task/custodian_policy.py", line 4, in run
return handler.dispatch_event(event, context)
File "/var/task/c7n/handler.py", line 165, in dispatch_event
p.push(event, context)
File "/var/task/c7n/policy.py", line 1140, in push
return mode.run(event, lambda_ctx)
File "/var/task/c7n/policy.py", line 853, in run
resources = super(ConfigRuleMode, self).run(event, lambda_context)
File "/var/task/c7n/policy.py", line 437, in run
resources = self.resolve_resources(event)
File "/var/task/c7n/policy.py", line 835, in resolve_resources
return [source.load_resource(self.cfg_event['configurationItem'])]
File "/var/task/c7n/resources/dynamodb.py", line 23, in load_resource
resource['CreationDateTime'] = datetime.fromtimestamp(resource['CreationDateTime'] / 1000.0)

# Fixed code
def load_resource(self, item):
    resource = super(ConfigTable, self).load_resource(item)
    sse_info = resource.pop("Ssedescription", None)
    if sse_info is None:
        return resource
    resource["SSEDescription"] = sse_info
    for k, r in (("KmsmasterKeyArn", "KMSMasterKeyArn"), ("Ssetype", "SSEType")):
        if k in sse_info:
            sse_info[r] = sse_info.pop(k)
    return resource
# Buggy code
def get_mailer_requirements():
    deps = [
        "azure-keyvault",
        "azure-storage-queue",
        "azure-storage-blob",
        "sendgrid",
    ] + list(CORE_DEPS)
    requirements = generate_requirements(
        deps, ignore=["boto3", "botocore", "pywin32"], include_self=True
    )
    return requirements


# Traceback (ModuleNotFoundError)
root@8b79684d85a3:/# c7n-mailer
Traceback (most recent call last):
File "/usr/local/bin/c7n-mailer", line 5, in <module>
from c7n_mailer.cli import main
File "/usr/local/lib/python3.8/dist-packages/c7n_mailer/cli.py", line 9, in <module>
from c7n_mailer import deploy, utils
File "/usr/local/lib/python3.8/dist-packages/c7n_mailer/deploy.py", line 19, in <module>
from c7n.mu import (
ModuleNotFoundError: No module named 'c7n'

# Fixed code
def get_mailer_requirements():
    deps = [
        "azure-keyvault",
        "azure-storage-queue",
        "azure-storage-blob",
        "sendgrid",
    ] + list(CORE_DEPS)
    requirements = generate_requirements(
        deps,
        ignore=["boto3", "botocore", "pywin32"],
        exclude=["pkg_resources"],
        include_self=True,
    )
    return requirements
# Buggy code
def __init__(self, policy, data):
    self.policy = policy
    self.data = data
    self.filters = self.data.get("conditions", [])
    # for value_from usage / we use the conditions class
    # to mimic a resource manager interface. we can't use
    # the actual resource manager as we're overriding block
    # filters which work w/ resource type metadata and our
    # resource here is effectively the execution variables.
    self.config = self.policy.options
    rm = self.policy.resource_manager
    self._cache = rm._cache
    self.session_factory = rm.session_factory
    # used by c7n-org to extend evaluation conditions
    self.env_vars = {}


# Traceback (AttributeError)
custodian run ~/Projects/policies/policy.yaml -v -s ~/Projects/policies/.custodian
2020-10-15 16:44:26,694: custodian.commands:DEBUG Loaded file /Users/kevinkessels/Projects/policies/policy.yaml. Contains 1 policies
Traceback (most recent call last):
File "/Users/kevinkessels/Projects/custodian/venv/bin/custodian", line 8, in <module>
sys.exit(main())
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/cli.py", line 352, in main
command(config)
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/commands.py", line 124, in _load_policies
p.validate()
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/policy.py", line 1046, in validate
self.conditions.validate()
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/policy.py", line 929, in validate
self.filters = self.filter_registry.parse(self.filters, self)
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/filters/core.py", line 122, in parse
results.append(self.factory(d, manager))
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/filters/core.py", line 146, in factory
filter_type = data.get('type')
AttributeError: 'ValueFilter' object has no attribute 'get'

# Fixed code
def __init__(self, policy, data):
    self.policy = policy
    self.data = data
    self.filters = self.data.get("conditions", [])
    # for value_from usage / we use the conditions class
    # to mimic a resource manager interface. we can't use
    # the actual resource manager as we're overriding block
    # filters which work w/ resource type metadata and our
    # resource here is effectively the execution variables.
    self.config = self.policy.options
    rm = self.policy.resource_manager
    self._cache = rm._cache
    self.session_factory = rm.session_factory
    # used by c7n-org to extend evaluation conditions
    self.env_vars = {}
    self.initialized = False
# Buggy code
def validate(self):
    self.filters.extend(self.convert_deprecated())
    self.filters = self.filter_registry.parse(self.filters, self)


# Traceback (AttributeError)
custodian run ~/Projects/policies/policy.yaml -v -s ~/Projects/policies/.custodian
2020-10-15 16:44:26,694: custodian.commands:DEBUG Loaded file /Users/kevinkessels/Projects/policies/policy.yaml. Contains 1 policies
Traceback (most recent call last):
File "/Users/kevinkessels/Projects/custodian/venv/bin/custodian", line 8, in <module>
sys.exit(main())
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/cli.py", line 352, in main
command(config)
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/commands.py", line 124, in _load_policies
p.validate()
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/policy.py", line 1046, in validate
self.conditions.validate()
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/policy.py", line 929, in validate
self.filters = self.filter_registry.parse(self.filters, self)
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/filters/core.py", line 122, in parse
results.append(self.factory(d, manager))
File "/Users/kevinkessels/Projects/custodian/venv/lib/python3.8/site-packages/c7n/filters/core.py", line 146, in factory
filter_type = data.get('type')
AttributeError: 'ValueFilter' object has no attribute 'get'

# Fixed code
def validate(self):
    if not self.initialized:
        self.filters.extend(self.convert_deprecated())
        self.filters = self.filter_registry.parse(self.filters, self)
        self.initialized = True
# Buggy code
def augment(self, resources):
    for r in resources:
        r["Tags"] = r.pop("TagSet", [])
    return resources


# Traceback (KeyError)
2020-09-25 19:37:54,488: custodian.output:ERROR Error while executing policy
Traceback (most recent call last):
File "/Users/rgopala1/custodian/lib/python3.7/site-packages/c7n/policy.py", line 291, in run
resources = self.policy.resource_manager.resources()
File "/Users/rgopala1/custodian/lib/python3.7/site-packages/c7n/query.py", line 509, in resources
resources = self.filter_resources(resources)
File "/Users/rgopala1/custodian/lib/python3.7/site-packages/c7n/manager.py", line 121, in filter_resources
resources = f.process(resources, event)
File "/Users/rgopala1/custodian/lib/python3.7/site-packages/c7n/resources/shield.py", line 87, in process
for arn, r in zip(self.manager.get_arns(resources), resources):
File "/Users/rgopala1/custodian/lib/python3.7/site-packages/c7n/query.py", line 588, in get_arns
_id = r[id_key]
KeyError: 'AllocationId'

# Fixed code
def augment(self, resources):
    return [r for r in resources if self.manager.resource_type.id in r]