gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __update(self):
    """
    Load the IRQ file and update the internal dict
    """

    self.reset()

    if not os.path.exists(self.IRQ_FILE):
        # Correct issue #947: IRQ file do not exist on OpenVZ container
        return self.stats

    with open(self.IRQ_FILE) as irq_proc:
        time_since_update = getTimeSinceLastUpdate("irq")
        # Read the header
        self.__header(irq_proc.readline())
        # Read the rest of the lines (one line per IRQ)
        for line in irq_proc.readlines():
            irq_line = self.__humanname(line)
            current_irqs = self.__sum(line)
            irq_rate = int(
                current_irqs - self.lasts.get(irq_line)
                if self.lasts.get(irq_line)
                else 0 // time_since_update
            )
            irq_current = {
                "irq_line": irq_line,
                "irq_rate": irq_rate,
                "key": self.get_key(),
                "time_since_update": time_since_update,
            }
            self.stats.append(irq_current)
            self.lasts[irq_line] = current_irqs

    return self.stats


# Traceback (PermissionError)
Traceback (most recent call last):
[...]
File "/home/alessio/py35-glances/lib/python3.5/site-packages/glances/plugins/glances_irq.py", line 66, in update
with open('/proc/interrupts') as irq_proc:
PermissionError: [Errno 13] Permission denied: '/proc/interrupts'

# Fixed code
def __update(self):
    """
    Load the IRQ file and update the internal dict
    """

    self.reset()

    if not os.path.exists(self.IRQ_FILE):
        # Correct issue #947: IRQ file do not exist on OpenVZ container
        return self.stats

    try:
        with open(self.IRQ_FILE) as irq_proc:
            time_since_update = getTimeSinceLastUpdate("irq")
            # Read the header
            self.__header(irq_proc.readline())
            # Read the rest of the lines (one line per IRQ)
            for line in irq_proc.readlines():
                irq_line = self.__humanname(line)
                current_irqs = self.__sum(line)
                irq_rate = int(
                    current_irqs - self.lasts.get(irq_line)
                    if self.lasts.get(irq_line)
                    else 0 // time_since_update
                )
                irq_current = {
                    "irq_line": irq_line,
                    "irq_rate": irq_rate,
                    "key": self.get_key(),
                    "time_since_update": time_since_update,
                }
                self.stats.append(irq_current)
                self.lasts[irq_line] = current_irqs
    except (OSError, IOError):
        pass

    return self.stats
# Buggy code
def msg_curse(self, args=None):
    """Return the dict to display in the curse interface."""
    # Init the return message
    ret = []

    # Only process if stats exist and display plugin enable...
    if not self.stats or args.disable_ip:
        return ret

    # Build the string message
    msg = " - "
    ret.append(self.curse_add_line(msg))
    msg = "IP "
    ret.append(self.curse_add_line(msg, "TITLE"))
    msg = "{0:}/{1}".format(self.stats["address"], self.stats["mask_cidr"])
    ret.append(self.curse_add_line(msg))
    if self.stats["public_address"] is not None:
        msg = " Pub "
        ret.append(self.curse_add_line(msg, "TITLE"))
        msg = "{0:}".format(self.stats["public_address"])
        ret.append(self.curse_add_line(msg))

    return ret


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/bin/glances", line 9, in <module>
load_entry_point('Glances==2.6.1', 'console_scripts', 'glances')()
File "/usr/local/lib/python2.7/site-packages/glances/__init__.py", line 133, in main
standalone.serve_forever()
File "/usr/local/lib/python2.7/site-packages/glances/standalone.py", line 107, in serve_forever
return self.__serve_forever()
File "/usr/local/lib/python2.7/site-packages/glances/standalone.py", line 92, in __serve_forever
self.screen.update(self.stats)
File "/usr/local/lib/python2.7/site-packages/glances/outputs/glances_curses.py", line 975, in update
self.flush(stats, cs_status=cs_status)
File "/usr/local/lib/python2.7/site-packages/glances/outputs/glances_curses.py", line 953, in flush
self.display(stats, cs_status=cs_status)
File "/usr/local/lib/python2.7/site-packages/glances/outputs/glances_curses.py", line 518, in display
stats_ip = stats.get_plugin('ip').get_stats_display(args=self.args)
File "/usr/local/lib/python2.7/site-packages/glances/plugins/glances_plugin.py", line 555, in get_stats_display
'msgdict': self.msg_curse(args),
File "/usr/local/lib/python2.7/site-packages/glances/plugins/glances_ip.py", line 116, in msg_curse
msg = '{0:}/{1}'.format(self.stats['address'], self.stats['mask_cidr'])
KeyError: 'mask_cidr'```

# Fixed code
def msg_curse(self, args=None):
    """Return the dict to display in the curse interface."""
    # Init the return message
    ret = []

    # Only process if stats exist and display plugin enable...
    if not self.stats or args.disable_ip:
        return ret

    # Build the string message
    msg = " - "
    ret.append(self.curse_add_line(msg))
    msg = "IP "
    ret.append(self.curse_add_line(msg, "TITLE"))
    msg = "{0:}".format(self.stats["address"])
    ret.append(self.curse_add_line(msg))
    if "mask_cidr" in self.stats:
        # VPN with no internet access (issue #842)
        msg = "/{0}".format(self.stats["mask_cidr"])
        ret.append(self.curse_add_line(msg))
    if self.stats["public_address"] is not None:
        msg = " Pub "
        ret.append(self.curse_add_line(msg, "TITLE"))
        msg = "{0:}".format(self.stats["public_address"])
        ret.append(self.curse_add_line(msg))

    return ret
# Buggy code
def get_docker_memory(self, container_id, all_stats):
    """Return the container MEMORY.

    Input: id is the full container id
           all_stats is the output of the stats method of the Docker API
    Output: a dict {'rss': 1015808, 'cache': 356352,  'usage': ..., 'max_usage': ...}
    """
    ret = {}
    # Read the stats
    try:
        ret["rss"] = all_stats["memory_stats"]["stats"]["rss"]
        ret["cache"] = all_stats["memory_stats"]["stats"]["cache"]
        ret["usage"] = all_stats["memory_stats"]["usage"]
        ret["max_usage"] = all_stats["memory_stats"]["max_usage"]
    except KeyError as e:
        # all_stats do not have MEM information
        logger.debug(
            "Can not grab MEM usage for container {0} ({1})".format(container_id, e)
        )
    # Return the stats
    return ret


# Traceback (TypeError)
$ glances
Traceback (most recent call last):
File "/usr/local/bin/glances", line 9, in <module>
load_entry_point('Glances==2.6.1', 'console_scripts', 'glances')()
File "/usr/local/lib/python3.4/dist-packages/glances/__init__.py", line 133, in main
standalone.serve_forever()
File "/usr/local/lib/python3.4/dist-packages/glances/standalone.py", line 107, in serve_forever
return self.__serve_forever()
File "/usr/local/lib/python3.4/dist-packages/glances/standalone.py", line 88, in __serve_forever
self.stats.update()
File "/usr/local/lib/python3.4/dist-packages/glances/stats.py", line 154, in update
self._plugins[p].update()
File "/usr/local/lib/python3.4/dist-packages/glances/plugins/glances_plugin.py", line 658, in wrapper
ret = fct(*args, **kw)
File "/usr/local/lib/python3.4/dist-packages/glances/plugins/glances_docker.py", line 226, in update
container['memory'] = self.get_docker_memory(container['Id'], self.thread_list[container['Id']].stats)
File "/usr/local/lib/python3.4/dist-packages/glances/plugins/glances_docker.py", line 297, in get_docker_memory
ret['rss'] = all_stats['memory_stats']['stats']['rss']
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def get_docker_memory(self, container_id, all_stats):
    """Return the container MEMORY.

    Input: id is the full container id
           all_stats is the output of the stats method of the Docker API
    Output: a dict {'rss': 1015808, 'cache': 356352,  'usage': ..., 'max_usage': ...}
    """
    ret = {}
    # Read the stats
    try:
        # Do not exist anymore with Docker 1.11 (issue #848)
        # ret['rss'] = all_stats['memory_stats']['stats']['rss']
        # ret['cache'] = all_stats['memory_stats']['stats']['cache']
        ret["usage"] = all_stats["memory_stats"]["usage"]
        ret["limit"] = all_stats["memory_stats"]["limit"]
        ret["max_usage"] = all_stats["memory_stats"]["max_usage"]
    except (KeyError, TypeError) as e:
        # all_stats do not have MEM information
        logger.debug(
            "Can not grab MEM usage for container {0} ({1})".format(container_id, e)
        )
        logger.debug(all_stats)
    # Return the stats
    return ret
# Buggy code
def __init__(self, config=None, args=None):
    # password_dict is a dict (JSON compliant)
    # {'host': 'password', ... }
    # Load the configuration file
    self._password_dict = self.load(config)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/alessio/venvs/py27-glances/bin/glances", line 11, in <module>
sys.exit(main())
File "/home/alessio/venvs/py27-glances/lib/python2.7/site-packages/glances/__init__.py", line 154, in main
client.serve_forever()
File "/home/alessio/venvs/py27-glances/lib/python2.7/site-packages/glances/core/glances_client_browser.py", line 246, in serve_forever
return self.__serve_forever()
File "/home/alessio/venvs/py27-glances/lib/python2.7/site-packages/glances/core/glances_client_browser.py", line 194, in __serve_forever
self.set_in_selected('password', self.password.sha256_hash(clear_password))
AttributeError: 'GlancesPassword' object has no attribute 'sha256_hash'

# Fixed code
def __init__(self, config=None, args=None):
    super(GlancesPassword, self).__init__()
    # password_dict is a dict (JSON compliant)
    # {'host': 'password', ... }
    # Load the configuration file
    self._password_dict = self.load(config)
# Buggy code
def end(self):
    """End of the Web server."""
    self.web.end()


# Traceback (AttributeError)
$ LANGUAGE=en_US.utf8  ~/glances-venv/bin/python -m glances -w
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/vagrant/dev/glances/glances/__main__.py", line 38, in <module>
glances.main()
File "glances/__init__.py", line 190, in main
args=core.get_args())
File "glances/core/glances_webserver.py", line 42, in __init__
self.stats.update()
File "glances/core/glances_stats.py", line 156, in update
self._plugins[p].update()
File "glances/plugins/glances_plugin.py", line 654, in wrapper
ret = fct(*args, **kw)
File "/home/vagrant/dev/glances/glances/plugins/glances_docker.py", line 205, in update
t = ThreadDockerGrabber(self.docker_client, container['Id'], self.args.time)
AttributeError: 'NoneType' object has no attribute 'time'

# Fixed code
def end(self):
    """End of the Web server."""
    self.web.end()
    self.stats.end()
# Buggy code
def __init__(self, docker_client, container_id, refresh_time=3):
    """Init the class:
    docker_client: instance of Docker-py client
    container_id: Id of the container"""
    logger.debug(
        "docker plugin - Create thread for container {}".format(container_id[:12])
    )
    super(ThreadDockerGrabber, self).__init__()
    # Refresh time for sub thread
    self._refresh_time = refresh_time
    # Event needed to stop properly the thread
    self._stop = threading.Event()
    # The docker-py return stats as a stream
    self._container_id = container_id
    self._stats_stream = docker_client.stats(container_id, decode=True)
    # The class return the stats as a dict
    self._stats = {}


# Traceback (AttributeError)
$ LANGUAGE=en_US.utf8  ~/glances-venv/bin/python -m glances -w
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/vagrant/dev/glances/glances/__main__.py", line 38, in <module>
glances.main()
File "glances/__init__.py", line 190, in main
args=core.get_args())
File "glances/core/glances_webserver.py", line 42, in __init__
self.stats.update()
File "glances/core/glances_stats.py", line 156, in update
self._plugins[p].update()
File "glances/plugins/glances_plugin.py", line 654, in wrapper
ret = fct(*args, **kw)
File "/home/vagrant/dev/glances/glances/plugins/glances_docker.py", line 205, in update
t = ThreadDockerGrabber(self.docker_client, container['Id'], self.args.time)
AttributeError: 'NoneType' object has no attribute 'time'

# Fixed code
def __init__(self, docker_client, container_id):
    """Init the class:
    docker_client: instance of Docker-py client
    container_id: Id of the container"""
    logger.debug(
        "docker plugin - Create thread for container {}".format(container_id[:12])
    )
    super(ThreadDockerGrabber, self).__init__()
    # Event needed to stop properly the thread
    self._stop = threading.Event()
    # The docker-py return stats as a stream
    self._container_id = container_id
    self._stats_stream = docker_client.stats(container_id, decode=True)
    # The class return the stats as a dict
    self._stats = {}
# Buggy code
def run(self):
    """Function called to grab stats.
    Infinite loop, should be stopped by calling the stop() method"""

    for i in self._stats_stream:
        self._stats = i
        # countdown = Timer(self._refresh_time)
        # while not countdown.finished() and not is_stopped:
        #     is_stopped = self.stopped()
        #     time.sleep(0.1)
        # if is_stopped:
        #     break
        time.sleep(0.1)
        if self.stopped():
            break


# Traceback (AttributeError)
$ LANGUAGE=en_US.utf8  ~/glances-venv/bin/python -m glances -w
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/vagrant/dev/glances/glances/__main__.py", line 38, in <module>
glances.main()
File "glances/__init__.py", line 190, in main
args=core.get_args())
File "glances/core/glances_webserver.py", line 42, in __init__
self.stats.update()
File "glances/core/glances_stats.py", line 156, in update
self._plugins[p].update()
File "glances/plugins/glances_plugin.py", line 654, in wrapper
ret = fct(*args, **kw)
File "/home/vagrant/dev/glances/glances/plugins/glances_docker.py", line 205, in update
t = ThreadDockerGrabber(self.docker_client, container['Id'], self.args.time)
AttributeError: 'NoneType' object has no attribute 'time'

# Fixed code
def run(self):
    """Function called to grab stats.
    Infinite loop, should be stopped by calling the stop() method"""

    for i in self._stats_stream:
        self._stats = i
        time.sleep(0.1)
        if self.stopped():
            break
# Buggy code
def __init__(self, config=None, args=None, timeout=7, return_to_browser=False):
    # Store the arg/config
    self.args = args
    self.config = config

    # Client mode:
    self.set_mode()

    # Build the URI
    if args.password != "":
        uri = "http://{0}:{1}@{2}:{3}".format(
            args.username, args.password, args.client, args.port
        )
    else:
        uri = "http://{0}:{1}".format(args.client, args.port)
    logger.debug("Try to connect to {0}".format(uri))

    # Try to connect to the URI
    transport = GlancesClientTransport()
    # Configure the server timeout
    transport.set_timeout(timeout)
    try:
        self.client = ServerProxy(uri, transport=transport)
    except Exception as e:
        msg = "Client couldn't create socket {0}: {1}".format(uri, e)
        if not return_to_browser:
            logger.critical(msg)
            sys.exit(2)
        else:
            logger.error(msg)


# Traceback (AttributeError)
LANGUAGE=en_US.utf8 python -m glances -c frodo.nicolargo.com
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/nicolargo/Dropbox/dev/glances/glances/__main__.py", line 38, in <module>
glances.main()
File "glances/__init__.py", line 146, in main
if not client.login():
File "glances/core/glances_client.py", line 166, in login
self.stats.load_limits(self.config)
AttributeError: 'GlancesClient' object has no attribute 'stats'

# Fixed code
def __init__(self, config=None, args=None, timeout=7, return_to_browser=False):
    # Store the arg/config
    self.args = args
    self.config = config

    # Client mode:
    self.set_mode()

    # Return to browser or exit
    self.return_to_browser = return_to_browser

    # Build the URI
    if args.password != "":
        uri = "http://{0}:{1}@{2}:{3}".format(
            args.username, args.password, args.client, args.port
        )
    else:
        uri = "http://{0}:{1}".format(args.client, args.port)
    logger.debug("Try to connect to {0}".format(uri))

    # Try to connect to the URI
    transport = GlancesClientTransport()
    # Configure the server timeout
    transport.set_timeout(timeout)
    try:
        self.client = ServerProxy(uri, transport=transport)
    except Exception as e:
        self.log_and_exit("Client couldn't create socket {0}: {1}".format(uri, e))
# Buggy code
def serve_forever(self, return_to_browser=False):
    """Main client loop."""

    exitkey = False

    while True and not exitkey:
        # Update the stats
        cs_status = self.update()

        # Update the screen
        exitkey = self.screen.update(
            self.stats, cs_status=cs_status, return_to_browser=return_to_browser
        )

    return self.get_mode()


# Traceback (AttributeError)
LANGUAGE=en_US.utf8 python -m glances -c frodo.nicolargo.com
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/nicolargo/Dropbox/dev/glances/glances/__main__.py", line 38, in <module>
glances.main()
File "glances/__init__.py", line 146, in main
if not client.login():
File "glances/core/glances_client.py", line 166, in login
self.stats.load_limits(self.config)
AttributeError: 'GlancesClient' object has no attribute 'stats'

# Fixed code
def serve_forever(self):
    """Main client loop."""

    exitkey = False

    while True and not exitkey:
        # Update the stats
        cs_status = self.update()

        # Update the screen
        exitkey = self.screen.update(
            self.stats, cs_status=cs_status, return_to_browser=self.return_to_browser
        )

    return self.get_mode()
# Buggy code
def load(self):
    """
    Load a config file from the list of paths, if it exists
    """
    for path in self.get_paths_list():
        if os.path.isfile(path) and os.path.getsize(path) > 0:
            try:
                if sys.version_info >= (3, 2):
                    self.parser.read(path, encoding="utf-8")
                else:
                    self.parser.read(path)
            except UnicodeDecodeError as e:
                print(_("Error decoding config file '%s': %s") % (path, e))
                sys.exit(1)

            break


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/bin/glances", line 9, in <module>
load_entry_point('Glances==1.7.4', 'console_scripts', 'glances')()
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4904, in main
csvoutput.update(stats)
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4164, in update
load['min15']])
TypeError: 'str' does not support the buffer interface

# Fixed code
def load(self):
    """
    Load a config file from the list of paths, if it exists
    """
    for path in self.get_paths_list():
        if os.path.isfile(path) and os.path.getsize(path) > 0:
            try:
                if is_PY3:
                    self.parser.read(path, encoding="utf-8")
                else:
                    self.parser.read(path)
            except UnicodeDecodeError as e:
                print(_("Error decoding config file '%s': %s") % (path, e))
                sys.exit(1)

            break
# Buggy code
def __init__(self, html_path, refresh_time=1):
    html_filename = "glances.html"
    html_template = "default.html"
    self.__refresh_time = refresh_time

    # Set the HTML output file
    self.html_file = os.path.join(html_path, html_filename)

    # Get data path
    data_path = os.path.join(work_path, "data")

    # Set the template path
    template_path = os.path.join(data_path, "html")
    environment = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_path),
        extensions=["jinja2.ext.loopcontrols"],
    )

    # Open the template
    self.template = environment.get_template(html_template)

    # Define the colors list (hash table) for logged stats
    self.__colors_list = {
        "DEFAULT": "bgcdefault fgdefault",
        "OK": "bgcok fgok",
        "CAREFUL": "bgccareful fgcareful",
        "WARNING": "bgcwarning fgcwarning",
        "CRITICAL": "bgcritical fgcritical",
    }


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/bin/glances", line 9, in <module>
load_entry_point('Glances==1.7.4', 'console_scripts', 'glances')()
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4904, in main
csvoutput.update(stats)
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4164, in update
load['min15']])
TypeError: 'str' does not support the buffer interface

# Fixed code
def __init__(self, html_path, refresh_time=1):
    html_filename = "glances.html"
    html_template = "default.html"
    self.__refresh_time = refresh_time

    # Set the HTML output file
    self.html_file = os.path.realpath(os.path.join(html_path, html_filename))

    # Get data path
    data_path = os.path.realpath(os.path.join(work_path, "data"))

    # Set the template path
    template_path = os.path.join(data_path, "html")
    environment = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_path),
        extensions=["jinja2.ext.loopcontrols"],
    )

    # Open the template
    self.template = environment.get_template(html_template)

    # Define the colors list (hash table) for logged stats
    self.__colors_list = {
        "DEFAULT": "bgcdefault fgdefault",
        "OK": "bgcok fgok",
        "CAREFUL": "bgccareful fgcareful",
        "WARNING": "bgcwarning fgcwarning",
        "CRITICAL": "bgcritical fgcritical",
    }
# Buggy code
def __init__(self, cvsfile="./glances.csv", refresh_time=1):
    # Init refresh time
    self.__refresh_time = refresh_time

    # Set the ouput (CSV) path
    try:
        self.__cvsfile_fd = open("%s" % cvsfile, "wb")
        self.__csvfile = csv.writer(self.__cvsfile_fd)
    except IOError as error:
        print("Cannot create the output CSV file: ", error[1])
        sys.exit(0)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/bin/glances", line 9, in <module>
load_entry_point('Glances==1.7.4', 'console_scripts', 'glances')()
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4904, in main
csvoutput.update(stats)
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4164, in update
load['min15']])
TypeError: 'str' does not support the buffer interface

# Fixed code
def __init__(self, csv_path, refresh_time=1):
    csv_filename = "glances.csv"
    self.__refresh_time = refresh_time

    # Set the CSV output file
    csv_file = os.path.realpath(os.path.join(csv_path, csv_filename))

    try:
        if is_PY3:
            self.__csvfile_fd = open(csv_file, "w", newline="")
        else:
            self.__csvfile_fd = open(csv_file, "wb")
        self.__csvfile = csv.writer(self.__csvfile_fd)
    except IOError as error:
        print(_("Cannot create the CSV output file: %s") % error)
        sys.exit(2)
# Buggy code
def exit(self):
    self.__cvsfile_fd.close()


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/bin/glances", line 9, in <module>
load_entry_point('Glances==1.7.4', 'console_scripts', 'glances')()
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4904, in main
csvoutput.update(stats)
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4164, in update
load['min15']])
TypeError: 'str' does not support the buffer interface

# Fixed code
def exit(self):
    self.__csvfile_fd.close()
# Buggy code
def update(self, stats):
    if stats.getCpu():
        # Update CSV with the CPU stats
        cpu = stats.getCpu()
        # Standard CPU stats
        l = ["cpu", cpu["user"], cpu["system"], cpu["nice"]]
        # Extra CPU stats
        for s in ("idle", "iowait", "irq"):
            l.append(cpu[s] if cpu.has_key(s) else None)
        self.__csvfile.writerow(l)
    if stats.getLoad():
        # Update CSV with the LOAD stats
        load = stats.getLoad()
        self.__csvfile.writerow(["load", load["min1"], load["min5"], load["min15"]])
    if stats.getMem() and stats.getMemSwap():
        # Update CSV with the MEM stats
        mem = stats.getMem()
        self.__csvfile.writerow(["mem", mem["total"], mem["used"], mem["free"]])
        memswap = stats.getMemSwap()
        self.__csvfile.writerow(
            ["swap", memswap["total"], memswap["used"], memswap["free"]]
        )
    self.__cvsfile_fd.flush()


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/bin/glances", line 9, in <module>
load_entry_point('Glances==1.7.4', 'console_scripts', 'glances')()
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4904, in main
csvoutput.update(stats)
File "/usr/lib/python3/dist-packages/glances/glances.py", line 4164, in update
load['min15']])
TypeError: 'str' does not support the buffer interface

# Fixed code
def update(self, stats):
    if stats.getCpu():
        # Update CSV with the CPU stats
        cpu = stats.getCpu()
        # Standard CPU stats
        cpu_line = ["cpu", cpu["user"], cpu["system"], cpu["nice"]]
        # Extra CPU stats
        for key in ("idle", "iowait", "irq"):
            cpu_line.append(cpu[key] if key in cpu.keys() else None)
        self.__csvfile.writerow(cpu_line)
    if stats.getLoad():
        # Update CSV with the LOAD stats
        load = stats.getLoad()
        self.__csvfile.writerow(["load", load["min1"], load["min5"], load["min15"]])
    if stats.getMem() and stats.getMemSwap():
        # Update CSV with the MEM stats
        mem = stats.getMem()
        self.__csvfile.writerow(["mem", mem["total"], mem["used"], mem["free"]])
        memswap = stats.getMemSwap()
        self.__csvfile.writerow(
            ["swap", memswap["total"], memswap["used"], memswap["free"]]
        )
    self.__csvfile_fd.flush()
# Buggy code
def getcapacitypercent(self):
    if not self.initok or self.bat_list == []:
        return []
    # Init the bsum (sum of percent) and bcpt (number of batteries)
    # and Loop over batteries (yes a computer could have more than 1 battery)
    bsum = 0
    for bcpt in range(len(self.get())):
        bsum = bsum + int(self.bat_list[bcpt].capacity)
    bcpt = bcpt + 1
    # Return the global percent
    return int(bsum / bcpt)


# Traceback (ValueError)
CRITICAL:batinfo.battery:Can not read file current_now
CRITICAL:batinfo.battery:Can not read file charge_now
CRITICAL:batinfo.battery:Can not read file charge_full
CRITICAL:batinfo.battery:Can not read file capacity
CRITICAL:batinfo.battery:Can not read file status
CRITICAL:batinfo.battery:Can not read file voltage_now
CRITICAL:batinfo.battery:Can not read file uevent
CRITICAL:batinfo.battery:Can not read file model_name
CRITICAL:batinfo.battery:Can not read file manufacturer
CRITICAL:batinfo.battery:Can not read file technology
Traceback (most recent call last):
File "/usr/local/bin/glances", line 9, in <module> load_entry_point('Glances==1.7.1', 'console_scripts', 'glances')()
File "/usr/local/lib/python2.7/dist-packages/glances/glances.py", line 4471, in main stats.update()
File "/usr/local/lib/python2.7/dist-packages/glances/glances.py", line 1492, in update self.__update__(input_stats)
File "/usr/local/lib/python2.7/dist-packages/glances/glances.py", line 1437, in __update__ self.batpercent = self.glancesgrabbat.getcapacitypercent()
File "/usr/local/lib/python2.7/dist-packages/glances/glances.py", line 1115, in getcapacitypercent bsum = bsum + int(self.bat_list[bcpt].capacity) ValueError: invalid literal for int() with base 10: ''

# Fixed code
def getcapacitypercent(self):
    if not self.initok or self.bat_list == []:
        return []
    # Init the bsum (sum of percent) and bcpt (number of batteries)
    # and Loop over batteries (yes a computer could have more than 1 battery)
    bsum = 0
    for bcpt in range(len(self.get())):
        try:
            bsum = bsum + int(self.bat_list[bcpt].capacity)
        except ValueError:
            return []
    bcpt = bcpt + 1
    # Return the global percent
    return int(bsum / bcpt)
# Buggy code
def stop(self):
    self.Terminated = True
    msvcrt.putch(" ")
    while not self.q.empty():
        self.q.get()


# Traceback (TypeError)
Traceback (most recent call last):
File "C:\Python33\Scripts\glances-script.py", line 9, in <module>
load_entry_point('Glances==1.7.1', 'console_scripts', 'glances')()
File "C:\Python33\lib\site-packages\glances-1.7.1-py3.3.egg\glances\glances.py
", line 4626, in main
screen.update(stats)
File "C:\Python33\lib\site-packages\glances-1.7.1-py3.3.egg\glances\glances.py
", line 2470, in update
if self.__catchKey() > -1:
File "C:\Python33\lib\site-packages\glances-1.7.1-py3.3.egg\glances\glances.py
", line 2336, in __catchKey
end()
File "C:\Python33\lib\site-packages\glances-1.7.1-py3.3.egg\glances\glances.py
", line 4298, in end
screen.end()
File "C:\Python33\lib\site-packages\glances-1.7.1-py3.3.egg\glances\glances.py
", line 2400, in end
curses.endwin()
File "C:\Python33\lib\site-packages\glances-1.7.1-py3.3.egg\glances\glances.py
", line 232, in endwin
self.term.listen.stop()
File "C:\Python33\lib\site-packages\glances-1.7.1-py3.3.egg\glances\glances.py
", line 119, in stop
msvcrt.putch(' ')
TypeError: must be a byte string of length 1, not str

# Fixed code
def stop(self):
    self.Terminated = True
    while not self.q.empty():
        self.q.get()
# Buggy code
def _run_command(self, host, command, *args, **kwargs):
    raise NotImplementedError


# Traceback (ValueError)
Traceback (most recent call last):
File "./aws-instances", line 172, in <module>
main()
File "./aws-instances", line 73, in main
facts = remote_facts(ips)
File "./aws-instances", line 146, in remote_facts
out_kern = client.run_command('uname -r')
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 223, in run_command
greenlet_timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 96, in run_command
self.get_output(cmd, output, timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 141, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get(timeout=timeout)
File "src/gevent/greenlet.py", line 709, in gevent._greenlet.Greenlet.get
File "src/gevent/greenlet.py", line 317, in gevent._greenlet.Greenlet._raise_exception
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 237, in _run_command
raise ex
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 233, in _run_command
use_pty=use_pty, encoding=encoding, timeout=timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 442, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 324, in execute
channel = self.open_session() if channel is None else channel
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 297, in open_session
wait_select(self.session)
File "pssh/native/_ssh2.pyx", line 171, in pssh.native._ssh2.wait_select
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/select.py", line 145, in select
sel_results = _original_select(rlist, wlist, xlist, 0)
ValueError: filedescriptor out of range in select()

# Fixed code
def _run_command(self, host_i, host, command, *args, **kwargs):
    raise NotImplementedError
# Buggy code
def _copy_file(self, host, local_file, remote_file, recurse=False):
    """Make sftp client, copy file"""
    try:
        self._make_ssh_client(host)
        return self.host_clients[host].copy_file(
            local_file, remote_file, recurse=recurse
        )
    except Exception as ex:
        ex.host = host
        raise ex


# Traceback (ValueError)
Traceback (most recent call last):
File "./aws-instances", line 172, in <module>
main()
File "./aws-instances", line 73, in main
facts = remote_facts(ips)
File "./aws-instances", line 146, in remote_facts
out_kern = client.run_command('uname -r')
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 223, in run_command
greenlet_timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 96, in run_command
self.get_output(cmd, output, timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 141, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get(timeout=timeout)
File "src/gevent/greenlet.py", line 709, in gevent._greenlet.Greenlet.get
File "src/gevent/greenlet.py", line 317, in gevent._greenlet.Greenlet._raise_exception
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 237, in _run_command
raise ex
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 233, in _run_command
use_pty=use_pty, encoding=encoding, timeout=timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 442, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 324, in execute
channel = self.open_session() if channel is None else channel
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 297, in open_session
wait_select(self.session)
File "pssh/native/_ssh2.pyx", line 171, in pssh.native._ssh2.wait_select
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/select.py", line 145, in select
sel_results = _original_select(rlist, wlist, xlist, 0)
ValueError: filedescriptor out of range in select()

# Fixed code
def _copy_file(self, host_i, host, local_file, remote_file, recurse=False):
    """Make sftp client, copy file"""
    try:
        self._make_ssh_client(host_i, host)
        return self._host_clients[(host_i, host)].copy_file(
            local_file, remote_file, recurse=recurse
        )
    except Exception as ex:
        ex.host = host
        raise ex
# Buggy code
def _copy_remote_file(self, host, remote_file, local_file, recurse, **kwargs):
    """Make sftp client, copy file to local"""
    try:
        self._make_ssh_client(host)
        return self.host_clients[host].copy_remote_file(
            remote_file, local_file, recurse=recurse, **kwargs
        )
    except Exception as ex:
        ex.host = host
        raise ex


# Traceback (ValueError)
Traceback (most recent call last):
File "./aws-instances", line 172, in <module>
main()
File "./aws-instances", line 73, in main
facts = remote_facts(ips)
File "./aws-instances", line 146, in remote_facts
out_kern = client.run_command('uname -r')
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 223, in run_command
greenlet_timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 96, in run_command
self.get_output(cmd, output, timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 141, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get(timeout=timeout)
File "src/gevent/greenlet.py", line 709, in gevent._greenlet.Greenlet.get
File "src/gevent/greenlet.py", line 317, in gevent._greenlet.Greenlet._raise_exception
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 237, in _run_command
raise ex
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 233, in _run_command
use_pty=use_pty, encoding=encoding, timeout=timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 442, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 324, in execute
channel = self.open_session() if channel is None else channel
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 297, in open_session
wait_select(self.session)
File "pssh/native/_ssh2.pyx", line 171, in pssh.native._ssh2.wait_select
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/select.py", line 145, in select
sel_results = _original_select(rlist, wlist, xlist, 0)
ValueError: filedescriptor out of range in select()

# Fixed code
def _copy_remote_file(self, host_i, host, remote_file, local_file, recurse, **kwargs):
    """Make sftp client, copy file to local"""
    try:
        self._make_ssh_client(host_i, host)
        return self._host_clients[(host_i, host)].copy_remote_file(
            remote_file, local_file, recurse=recurse, **kwargs
        )
    except Exception as ex:
        ex.host = host
        raise ex
# Buggy code
def _scp_send(self, host, local_file, remote_file, recurse=False):
    self._make_ssh_client(host)
    return self._handle_greenlet_exc(
        self.host_clients[host].scp_send, host, local_file, remote_file, recurse=recurse
    )


# Traceback (ValueError)
Traceback (most recent call last):
File "./aws-instances", line 172, in <module>
main()
File "./aws-instances", line 73, in main
facts = remote_facts(ips)
File "./aws-instances", line 146, in remote_facts
out_kern = client.run_command('uname -r')
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 223, in run_command
greenlet_timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 96, in run_command
self.get_output(cmd, output, timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 141, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get(timeout=timeout)
File "src/gevent/greenlet.py", line 709, in gevent._greenlet.Greenlet.get
File "src/gevent/greenlet.py", line 317, in gevent._greenlet.Greenlet._raise_exception
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 237, in _run_command
raise ex
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 233, in _run_command
use_pty=use_pty, encoding=encoding, timeout=timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 442, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 324, in execute
channel = self.open_session() if channel is None else channel
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 297, in open_session
wait_select(self.session)
File "pssh/native/_ssh2.pyx", line 171, in pssh.native._ssh2.wait_select
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/select.py", line 145, in select
sel_results = _original_select(rlist, wlist, xlist, 0)
ValueError: filedescriptor out of range in select()

# Fixed code
def _scp_send(self, host_i, host, local_file, remote_file, recurse=False):
    self._make_ssh_client(host_i, host)
    return self._handle_greenlet_exc(
        self._host_clients[(host_i, host)].scp_send,
        host,
        local_file,
        remote_file,
        recurse=recurse,
    )
# Buggy code
def _scp_recv(self, host, remote_file, local_file, recurse=False):
    self._make_ssh_client(host)
    return self._handle_greenlet_exc(
        self.host_clients[host].scp_recv, host, remote_file, local_file, recurse=recurse
    )


# Traceback (ValueError)
Traceback (most recent call last):
File "./aws-instances", line 172, in <module>
main()
File "./aws-instances", line 73, in main
facts = remote_facts(ips)
File "./aws-instances", line 146, in remote_facts
out_kern = client.run_command('uname -r')
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 223, in run_command
greenlet_timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 96, in run_command
self.get_output(cmd, output, timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 141, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get(timeout=timeout)
File "src/gevent/greenlet.py", line 709, in gevent._greenlet.Greenlet.get
File "src/gevent/greenlet.py", line 317, in gevent._greenlet.Greenlet._raise_exception
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 237, in _run_command
raise ex
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 233, in _run_command
use_pty=use_pty, encoding=encoding, timeout=timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 442, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 324, in execute
channel = self.open_session() if channel is None else channel
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 297, in open_session
wait_select(self.session)
File "pssh/native/_ssh2.pyx", line 171, in pssh.native._ssh2.wait_select
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/select.py", line 145, in select
sel_results = _original_select(rlist, wlist, xlist, 0)
ValueError: filedescriptor out of range in select()

# Fixed code
def _scp_recv(self, host_i, host, remote_file, local_file, recurse=False):
    self._make_ssh_client(host_i, host)
    return self._handle_greenlet_exc(
        self._host_clients[(host_i, host)].scp_recv,
        host,
        remote_file,
        local_file,
        recurse=recurse,
    )
# Buggy code
def _handle_greenlet_exc(self, func, host, *args, **kwargs):
    try:
        self._make_ssh_client(host)
        return func(*args, **kwargs)
    except Exception as ex:
        ex.host = host
        raise ex


# Traceback (ValueError)
Traceback (most recent call last):
File "./aws-instances", line 172, in <module>
main()
File "./aws-instances", line 73, in main
facts = remote_facts(ips)
File "./aws-instances", line 146, in remote_facts
out_kern = client.run_command('uname -r')
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 223, in run_command
greenlet_timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 96, in run_command
self.get_output(cmd, output, timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 141, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get(timeout=timeout)
File "src/gevent/greenlet.py", line 709, in gevent._greenlet.Greenlet.get
File "src/gevent/greenlet.py", line 317, in gevent._greenlet.Greenlet._raise_exception
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 237, in _run_command
raise ex
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 233, in _run_command
use_pty=use_pty, encoding=encoding, timeout=timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 442, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 324, in execute
channel = self.open_session() if channel is None else channel
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 297, in open_session
wait_select(self.session)
File "pssh/native/_ssh2.pyx", line 171, in pssh.native._ssh2.wait_select
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/select.py", line 145, in select
sel_results = _original_select(rlist, wlist, xlist, 0)
ValueError: filedescriptor out of range in select()

# Fixed code
def _handle_greenlet_exc(self, func, host, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except Exception as ex:
        ex.host = host
        raise ex