gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _handleError(self, error_message):
    log.error(error_message)
    self.UIqueue[self.current]["stat"] = STAT_FAIL
    self.UIqueue[self.current]["progress"] = "100 %"
    self.UIqueue[self.current]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
    self.UIqueue[self.current]["message"] = error_message


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def _handleError(self, error_message):
    log.error(error_message)
    doLock = threading.Lock()
    doLock.acquire()
    index = self.current
    doLock.release()
    self.UIqueue[index]["stat"] = STAT_FAIL
    self.UIqueue[index]["progress"] = "100 %"
    self.UIqueue[index]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
    self.UIqueue[index]["message"] = error_message
# Buggy code
def _handleSuccess(self):
    self.UIqueue[self.current]["stat"] = STAT_FINISH_SUCCESS
    self.UIqueue[self.current]["progress"] = "100 %"
    self.UIqueue[self.current]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def _handleSuccess(self):
    doLock = threading.Lock()
    doLock.acquire()
    index = self.current
    doLock.release()
    self.UIqueue[index]["stat"] = STAT_FINISH_SUCCESS
    self.UIqueue[index]["progress"] = "100 %"
    self.UIqueue[index]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
# Buggy code
def __init__(self):
    threading.Thread.__init__(self)
    self.status = 0
    self.current = 0
    self.last = 0
    self.queue = list()
    self.UIqueue = list()
    self.asyncSMTP = None
    self.id = 0


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def __init__(self):
    threading.Thread.__init__(self)
    self.status = 0
    self.current = 0
    self.last = 0
    self.queue = list()
    self.UIqueue = list()
    self.asyncSMTP = None
    self.id = 0
    self.doLock = threading.Lock()
# Buggy code
def run(self):
    main_thread = _get_main_thread()
    while main_thread.is_alive():
        doLock = threading.Lock()
        doLock.acquire()
        if self.current != self.last:
            index = self.current
            doLock.release()
            if self.queue[index]["taskType"] == TASK_EMAIL:
                self._send_raw_email()
            if self.queue[index]["taskType"] == TASK_CONVERT:
                self._convert_any_format()
            if self.queue[index]["taskType"] == TASK_CONVERT_ANY:
                self._convert_any_format()
            # TASK_UPLOAD is handled implicitly
            doLock.acquire()
            self.current += 1
            doLock.release()
        else:
            doLock.release()
        if main_thread.is_alive():
            time.sleep(1)


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def run(self):
    main_thread = _get_main_thread()
    while main_thread.is_alive():
        self.doLock.acquire()
        if self.current != self.last:
            index = self.current
            self.doLock.release()
            if self.queue[index]["taskType"] == TASK_EMAIL:
                self._send_raw_email()
            if self.queue[index]["taskType"] == TASK_CONVERT:
                self._convert_any_format()
            if self.queue[index]["taskType"] == TASK_CONVERT_ANY:
                self._convert_any_format()
            # TASK_UPLOAD is handled implicitly
            self.doLock.acquire()
            self.current += 1
            self.doLock.release()
        else:
            self.doLock.release()
        if main_thread.is_alive():
            time.sleep(1)
# Buggy code
def get_taskstatus(self):
    doLock = threading.Lock()
    doLock.acquire()
    if self.current < len(self.queue):
        if self.UIqueue[self.current]["stat"] == STAT_STARTED:
            if self.queue[self.current]["taskType"] == TASK_EMAIL:
                self.UIqueue[self.current]["progress"] = self.get_send_status()
            self.UIqueue[self.current]["formRuntime"] = (
                datetime.now() - self.queue[self.current]["starttime"]
            )
            self.UIqueue[self.current]["rt"] = (
                self.UIqueue[self.current]["formRuntime"].days * 24 * 60
                + self.UIqueue[self.current]["formRuntime"].seconds
                + self.UIqueue[self.current]["formRuntime"].microseconds
            )
    doLock.release()
    return self.UIqueue


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def get_taskstatus(self):
    self.doLock.acquire()
    if self.current < len(self.queue):
        if self.UIqueue[self.current]["stat"] == STAT_STARTED:
            if self.queue[self.current]["taskType"] == TASK_EMAIL:
                self.UIqueue[self.current]["progress"] = self.get_send_status()
            self.UIqueue[self.current]["formRuntime"] = (
                datetime.now() - self.queue[self.current]["starttime"]
            )
            self.UIqueue[self.current]["rt"] = (
                self.UIqueue[self.current]["formRuntime"].days * 24 * 60
                + self.UIqueue[self.current]["formRuntime"].seconds
                + self.UIqueue[self.current]["formRuntime"].microseconds
            )
    self.doLock.release()
    return self.UIqueue
# Buggy code
def _convert_any_format(self):
    # convert book, and upload in case of google drive
    doLock = threading.Lock()
    doLock.acquire()
    index = self.current
    doLock.release()
    self.UIqueue[index]["stat"] = STAT_STARTED
    self.queue[index]["starttime"] = datetime.now()
    self.UIqueue[index]["formStarttime"] = self.queue[self.current]["starttime"]
    curr_task = self.queue[index]["taskType"]
    filename = self._convert_ebook_format()
    if filename:
        if config.config_use_google_drive:
            gdriveutils.updateGdriveCalibreFromLocal()
        if curr_task == TASK_CONVERT:
            self.add_email(
                self.queue[index]["settings"]["subject"],
                self.queue[index]["path"],
                filename,
                self.queue[index]["settings"],
                self.queue[index]["kindle"],
                self.UIqueue[index]["user"],
                self.queue[index]["title"],
                self.queue[index]["settings"]["body"],
            )


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def _convert_any_format(self):
    # convert book, and upload in case of google drive
    self.doLock.acquire()
    index = self.current
    self.doLock.release()
    self.UIqueue[index]["stat"] = STAT_STARTED
    self.queue[index]["starttime"] = datetime.now()
    self.UIqueue[index]["formStarttime"] = self.queue[self.current]["starttime"]
    curr_task = self.queue[index]["taskType"]
    filename = self._convert_ebook_format()
    if filename:
        if config.config_use_google_drive:
            gdriveutils.updateGdriveCalibreFromLocal()
        if curr_task == TASK_CONVERT:
            self.add_email(
                self.queue[index]["settings"]["subject"],
                self.queue[index]["path"],
                filename,
                self.queue[index]["settings"],
                self.queue[index]["kindle"],
                self.UIqueue[index]["user"],
                self.queue[index]["title"],
                self.queue[index]["settings"]["body"],
            )
# Buggy code
def _handleError(self, error_message):
    log.error(error_message)
    doLock = threading.Lock()
    doLock.acquire()
    index = self.current
    doLock.release()
    self.UIqueue[index]["stat"] = STAT_FAIL
    self.UIqueue[index]["progress"] = "100 %"
    self.UIqueue[index]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
    self.UIqueue[index]["message"] = error_message


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def _handleError(self, error_message):
    log.error(error_message)
    self.doLock.acquire()
    index = self.current
    self.doLock.release()
    self.UIqueue[index]["stat"] = STAT_FAIL
    self.UIqueue[index]["progress"] = "100 %"
    self.UIqueue[index]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
    self.UIqueue[index]["message"] = error_message
# Buggy code
def _handleSuccess(self):
    doLock = threading.Lock()
    doLock.acquire()
    index = self.current
    doLock.release()
    self.UIqueue[index]["stat"] = STAT_FINISH_SUCCESS
    self.UIqueue[index]["progress"] = "100 %"
    self.UIqueue[index]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )


# Traceback (IndexError)
Traceback (most recent call last):
File "calibre-web/vendor/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "calibre-web/vendor/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "calibre-web/vendor/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "calibre-web/vendor/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "calibre-web/cps/web.py", line 348, in decorated_view
return func(*args, **kwargs)
File "calibre-web/cps/web.py", line 490, in inner
return f(*args, **kwargs)
File "calibre-web/cps/web.py", line 3868, in upload
"<a href=\"" + url_for('show_book', book_id=book.id) + "\">" + uploadText + "</a>")
File "calibre-web/cps/worker.py", line 406, in add_upload
self.UIqueue[self.current]['formStarttime'] = self.queue[self.current]['starttime']
IndexError: list index out of range

# Fixed code
def _handleSuccess(self):
    self.doLock.acquire()
    index = self.current
    self.doLock.release()
    self.UIqueue[index]["stat"] = STAT_FINISH_SUCCESS
    self.UIqueue[index]["progress"] = "100 %"
    self.UIqueue[index]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
# Buggy code
def check_read_formats(entry):
    EXTENSIONS_READER = {"TXT", "PDF", "EPUB", "ZIP", "CBZ", "TAR", "CBT", "RAR", "CBR"}
    bookformats = list()
    if len(entry.data):
        for ele in iter(entry.data):
            if ele.format in EXTENSIONS_READER:
                bookformats.append(ele.format.lower())
    return bookformats


# Traceback (TypeError)
[2019-04-29 08:55:11,436] ERROR in app: Exception on /read/4/zip [GET]
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1816, in full_dispatch_request
return self.finalize_request(rv)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1831, in finalize_request
response = self.make_response(rv)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1957, in make_response
'The view function did not return a valid response. The'
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

# Fixed code
def check_read_formats(entry):
    EXTENSIONS_READER = {"TXT", "PDF", "EPUB", "CBZ", "CBT", "CBR"}
    bookformats = list()
    if len(entry.data):
        for ele in iter(entry.data):
            if ele.format in EXTENSIONS_READER:
                bookformats.append(ele.format.lower())
    return bookformats
# Buggy code
def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime)):
        return obj.isoformat()
    raise TypeError("Type %s not serializable" % type(obj))


# Traceback (ValueError)
[2019-06-28 22:37:50,052] ERROR in app: Exception on /tasks [GET]
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/python2.7/site-packages/flask_login/utils.py", line 261, in decorated_view
return func(*args, **kwargs)
File "/calibre-web/app/cps/web.py", line 1646, in get_tasks_status
tasks=helper.global_WorkerThread.get_taskstatus()
File "/calibre-web/app/cps/worker.py", line 225, in get_taskstatus
datetime.now() - self.queue[self.current]['starttime'])
File "/calibre-web/app/cps/worker.py", line 489, in _formatRuntime
if int(v) > 0:
ValueError: invalid literal for int() with base 10: '1 day, 5'
::ffff:172.17.0.1 - - [2019-06-28 22:37:50] "GET /tasks HTTP/1.1" 500 411 0.011915

# Fixed code
def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime)):
        return obj.isoformat()
    if isinstance(obj, (timedelta)):
        return {
            "__type__": "timedelta",
            "days": obj.days,
            "seconds": obj.seconds,
            "microseconds": obj.microseconds,
        }
    raise TypeError("Type %s not serializable" % type(obj))
# Buggy code
def get_taskstatus(self):
    if self.current < len(self.queue):
        if self.UIqueue[self.current]["stat"] == STAT_STARTED:
            if self.queue[self.current]["taskType"] == TASK_EMAIL:
                self.UIqueue[self.current]["progress"] = self.get_send_status()
            self.UIqueue[self.current]["runtime"] = self._formatRuntime(
                datetime.now() - self.queue[self.current]["starttime"]
            )
    return self.UIqueue


# Traceback (ValueError)
[2019-06-28 22:37:50,052] ERROR in app: Exception on /tasks [GET]
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/python2.7/site-packages/flask_login/utils.py", line 261, in decorated_view
return func(*args, **kwargs)
File "/calibre-web/app/cps/web.py", line 1646, in get_tasks_status
tasks=helper.global_WorkerThread.get_taskstatus()
File "/calibre-web/app/cps/worker.py", line 225, in get_taskstatus
datetime.now() - self.queue[self.current]['starttime'])
File "/calibre-web/app/cps/worker.py", line 489, in _formatRuntime
if int(v) > 0:
ValueError: invalid literal for int() with base 10: '1 day, 5'
::ffff:172.17.0.1 - - [2019-06-28 22:37:50] "GET /tasks HTTP/1.1" 500 411 0.011915

# Fixed code
def get_taskstatus(self):
    if self.current < len(self.queue):
        if self.UIqueue[self.current]["stat"] == STAT_STARTED:
            if self.queue[self.current]["taskType"] == TASK_EMAIL:
                self.UIqueue[self.current]["progress"] = self.get_send_status()
            self.UIqueue[self.current]["formRuntime"] = (
                datetime.now() - self.queue[self.current]["starttime"]
            )
            self.UIqueue[self.current]["rt"] = (
                self.UIqueue[self.current]["formRuntime"].days * 24 * 60
                + self.UIqueue[self.current]["formRuntime"].seconds
                + self.UIqueue[self.current]["formRuntime"].microseconds
            )
    return self.UIqueue
# Buggy code
def _handleError(self, error_message):
    web.app.logger.error(error_message)
    self.UIqueue[self.current]["stat"] = STAT_FAIL
    self.UIqueue[self.current]["progress"] = "100 %"
    self.UIqueue[self.current]["runtime"] = self._formatRuntime(
        datetime.now() - self.queue[self.current]["starttime"]
    )
    self.UIqueue[self.current]["message"] = error_message


# Traceback (ValueError)
[2019-06-28 22:37:50,052] ERROR in app: Exception on /tasks [GET]
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/python2.7/site-packages/flask_login/utils.py", line 261, in decorated_view
return func(*args, **kwargs)
File "/calibre-web/app/cps/web.py", line 1646, in get_tasks_status
tasks=helper.global_WorkerThread.get_taskstatus()
File "/calibre-web/app/cps/worker.py", line 225, in get_taskstatus
datetime.now() - self.queue[self.current]['starttime'])
File "/calibre-web/app/cps/worker.py", line 489, in _formatRuntime
if int(v) > 0:
ValueError: invalid literal for int() with base 10: '1 day, 5'
::ffff:172.17.0.1 - - [2019-06-28 22:37:50] "GET /tasks HTTP/1.1" 500 411 0.011915

# Fixed code
def _handleError(self, error_message):
    web.app.logger.error(error_message)
    self.UIqueue[self.current]["stat"] = STAT_FAIL
    self.UIqueue[self.current]["progress"] = "100 %"
    self.UIqueue[self.current]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
    self.UIqueue[self.current]["message"] = error_message
# Buggy code
def _handleSuccess(self):
    self.UIqueue[self.current]["stat"] = STAT_FINISH_SUCCESS
    self.UIqueue[self.current]["progress"] = "100 %"
    self.UIqueue[self.current]["runtime"] = self._formatRuntime(
        datetime.now() - self.queue[self.current]["starttime"]
    )


# Traceback (ValueError)
[2019-06-28 22:37:50,052] ERROR in app: Exception on /tasks [GET]
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/lib/python2.7/site-packages/flask_login/utils.py", line 261, in decorated_view
return func(*args, **kwargs)
File "/calibre-web/app/cps/web.py", line 1646, in get_tasks_status
tasks=helper.global_WorkerThread.get_taskstatus()
File "/calibre-web/app/cps/worker.py", line 225, in get_taskstatus
datetime.now() - self.queue[self.current]['starttime'])
File "/calibre-web/app/cps/worker.py", line 489, in _formatRuntime
if int(v) > 0:
ValueError: invalid literal for int() with base 10: '1 day, 5'
::ffff:172.17.0.1 - - [2019-06-28 22:37:50] "GET /tasks HTTP/1.1" 500 411 0.011915

# Fixed code
def _handleSuccess(self):
    self.UIqueue[self.current]["stat"] = STAT_FINISH_SUCCESS
    self.UIqueue[self.current]["progress"] = "100 %"
    self.UIqueue[self.current]["formRuntime"] = (
        datetime.now() - self.queue[self.current]["starttime"]
    )
# Buggy code
def save_cover(img, book_path):
    content_type = img.headers.get("content-type")
    if content_type not in ("image/jpeg", "image/png", "image/webp"):
        web.app.logger.error("Only jpg/jpeg/png/webp files are supported as coverfile")
        return False

    # convert to jpg because calibre only supports jpg
    if content_type in ("image/png", "image/webp"):
        if hasattr(img, "stream"):
            imgc = Image.open(img.stream)
        else:
            imgc = Image.open(io.BytesIO(img.content))
        im = imgc.convert("RGB")
        tmp_bytesio = io.BytesIO()
        im.save(tmp_bytesio, format="JPEG")
        img._content = tmp_bytesio.getvalue()

    if ub.config.config_use_google_drive:
        tmpDir = gettempdir()
        if save_cover_from_filestorage(tmpDir, "uploaded_cover.jpg", img) is True:
            gd.uploadFileToEbooksFolder(
                os.path.join(book_path, "cover.jpg"),
                os.path.join(tmpDir, "uploaded_cover.jpg"),
            )
            web.app.logger.info("Cover is saved on Google Drive")
            return True
        else:
            return False
    else:
        return save_cover_from_filestorage(
            os.path.join(ub.config.config_calibre_dir, book_path), "cover.jpg", img
        )


# Traceback (ModuleNotFoundError)
c:\CalibreWeb>python37 cps.py
Traceback (most recent call last):
File "cps.py", line 13, in <module>
from cps.server import Server
File "c:\CalibreWeb\cps\server.py", line 25, in <module>
import web
File "c:\CalibreWeb\cps\web.py", line 38, in <module>
import helper
File "c:\CalibreWeb\cps\helper.py", line 38, in <module>
from PIL import Image
ModuleNotFoundError: No module named 'PIL'

# Fixed code
def save_cover(img, book_path):
    content_type = img.headers.get("content-type")
    if content_type not in ("image/jpeg", "image/png", "image/webp"):
        web.app.logger.error("Only jpg/jpeg/png/webp files are supported as coverfile")
        return False

    if use_PIL:
        # convert to jpg because calibre only supports jpg
        if content_type in ("image/png", "image/webp"):
            if hasattr(img, "stream"):
                imgc = Image.open(img.stream)
            else:
                imgc = Image.open(io.BytesIO(img.content))
            im = imgc.convert("RGB")
            tmp_bytesio = io.BytesIO()
            im.save(tmp_bytesio, format="JPEG")
            img._content = tmp_bytesio.getvalue()

    if ub.config.config_use_google_drive:
        tmpDir = gettempdir()
        if save_cover_from_filestorage(tmpDir, "uploaded_cover.jpg", img) is True:
            gd.uploadFileToEbooksFolder(
                os.path.join(book_path, "cover.jpg"),
                os.path.join(tmpDir, "uploaded_cover.jpg"),
            )
            web.app.logger.info("Cover is saved on Google Drive")
            return True
        else:
            return False
    else:
        return save_cover_from_filestorage(
            os.path.join(ub.config.config_calibre_dir, book_path), "cover.jpg", img
        )
# Buggy code
def debug(address, **kwargs):
    if _settrace.called:
        raise RuntimeError("this process already has a debug adapter")

    try:
        _, port = address
    except Exception:
        port = address
        address = ("127.0.0.1", port)
    try:
        port.__index__()  # ensure it's int-like
    except Exception:
        raise ValueError("expected port or (host, port)")
    if not (0 <= port < 2**16):
        raise ValueError("invalid port number")

    ensure_logging()
    log.debug("{0}({1!r}, **{2!r})", func.__name__, address, kwargs)
    log.info("Initial debug configuration: {0!j}", _config)

    qt_mode = _config.get("qt", "none")
    if qt_mode != "none":
        pydevd.enable_qt_support(qt_mode)

    settrace_kwargs = {
        "suspend": False,
        "patch_multiprocessing": _config.get("subProcess", True),
    }

    debugpy_path = os.path.dirname(absolute_path(debugpy.__file__))
    settrace_kwargs["dont_trace_start_patterns"] = (debugpy_path,)
    settrace_kwargs["dont_trace_end_patterns"] = ("debugpy_launcher.py",)

    try:
        return func(address, settrace_kwargs, **kwargs)
    except Exception:
        log.reraise_exception("{0}() failed:", func.__name__, level="info")


# Traceback (IOError)
Traceback (most recent call last):
File "c:/Users/kanadig/.vscode/extensions/ms-python.python-2019.5.17059/pythonFiles/ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 434, in main
run()
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 312, in run_file
runpy.run_path(target, run_name='__main__')
File "C:\Python27\lib\runpy.py", line 251, in run_path
code = _get_code_from_file(path_name)
File "C:\Python27\lib\runpy.py", line 227, in _get_code_from_file
with open(fname, "rb") as f:
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\\GIT\\pyscratch2\\??\\experiment.py'

# Fixed code
def debug(address, **kwargs):
    if _settrace.called:
        raise RuntimeError("this process already has a debug adapter")

    try:
        _, port = address
    except Exception:
        port = address
        address = ("127.0.0.1", port)
    try:
        port.__index__()  # ensure it's int-like
    except Exception:
        raise ValueError("expected port or (host, port)")
    if not (0 <= port < 2**16):
        raise ValueError("invalid port number")

    ensure_logging()
    log.debug("{0}({1!r}, **{2!r})", func.__name__, address, kwargs)
    log.info("Initial debug configuration: {0!j}", _config)

    qt_mode = _config.get("qt", "none")
    if qt_mode != "none":
        pydevd.enable_qt_support(qt_mode)

    settrace_kwargs = {
        "suspend": False,
        "patch_multiprocessing": _config.get("subProcess", True),
    }

    debugpy_path = os.path.dirname(absolute_path(debugpy.__file__))
    settrace_kwargs["dont_trace_start_patterns"] = (debugpy_path,)
    settrace_kwargs["dont_trace_end_patterns"] = (str("debugpy_launcher.py"),)

    try:
        return func(address, settrace_kwargs, **kwargs)
    except Exception:
        log.reraise_exception("{0}() failed:", func.__name__, level="info")
# Buggy code
def set_target(kind, parser=(lambda x: x), positional=False):
    def do(arg, it):
        options.target_kind = kind
        options.target = parser(arg if positional else next(it))

    return do


# Traceback (IOError)
Traceback (most recent call last):
File "c:/Users/kanadig/.vscode/extensions/ms-python.python-2019.5.17059/pythonFiles/ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 434, in main
run()
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 312, in run_file
runpy.run_path(target, run_name='__main__')
File "C:\Python27\lib\runpy.py", line 251, in run_path
code = _get_code_from_file(path_name)
File "C:\Python27\lib\runpy.py", line 227, in _get_code_from_file
with open(fname, "rb") as f:
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\\GIT\\pyscratch2\\??\\experiment.py'

# Fixed code
def set_target(kind, parser=(lambda x: x), positional=False):
    def do(arg, it):
        options.target_kind = kind
        target = parser(arg if positional else next(it))

        if isinstance(target, bytes):
            # target may be the code, so, try some additional encodings...
            try:
                target = target.decode(sys.getfilesystemencoding())
            except UnicodeDecodeError:
                try:
                    target = target.decode("utf-8")
                except UnicodeDecodeError:
                    import locale

                    target = target.decode(locale.getpreferredencoding(False))
        options.target = target

    return do
# Buggy code
def do(arg, it):
    options.target_kind = kind
    options.target = parser(arg if positional else next(it))


# Traceback (IOError)
Traceback (most recent call last):
File "c:/Users/kanadig/.vscode/extensions/ms-python.python-2019.5.17059/pythonFiles/ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 434, in main
run()
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 312, in run_file
runpy.run_path(target, run_name='__main__')
File "C:\Python27\lib\runpy.py", line 251, in run_path
code = _get_code_from_file(path_name)
File "C:\Python27\lib\runpy.py", line 227, in _get_code_from_file
with open(fname, "rb") as f:
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\\GIT\\pyscratch2\\??\\experiment.py'

# Fixed code
def do(arg, it):
    options.target_kind = kind
    target = parser(arg if positional else next(it))

    if isinstance(target, bytes):
        # target may be the code, so, try some additional encodings...
        try:
            target = target.decode(sys.getfilesystemencoding())
        except UnicodeDecodeError:
            try:
                target = target.decode("utf-8")
            except UnicodeDecodeError:
                import locale

                target = target.decode(locale.getpreferredencoding(False))
    options.target = target
# Buggy code
def run_file():
    start_debugging(options.target)

    # run_path has one difference with invoking Python from command-line:
    # if the target is a file (rather than a directory), it does not add its
    # parent directory to sys.path. Thus, importing other modules from the
    # same directory is broken unless sys.path is patched here.
    if os.path.isfile(options.target):
        dir = os.path.dirname(options.target)
        sys.path.insert(0, dir)
    else:
        log.debug("Not a file: {0!r}", options.target)

    log.describe_environment("Pre-launch environment:")
    log.info("Running file {0!r}", options.target)

    runpy.run_path(options.target, run_name=compat.force_str("__main__"))


# Traceback (IOError)
Traceback (most recent call last):
File "c:/Users/kanadig/.vscode/extensions/ms-python.python-2019.5.17059/pythonFiles/ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 434, in main
run()
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 312, in run_file
runpy.run_path(target, run_name='__main__')
File "C:\Python27\lib\runpy.py", line 251, in run_path
code = _get_code_from_file(path_name)
File "C:\Python27\lib\runpy.py", line 227, in _get_code_from_file
with open(fname, "rb") as f:
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\\GIT\\pyscratch2\\??\\experiment.py'

# Fixed code
def run_file():
    target = options.target
    start_debugging(target)

    target_as_str = compat.filename_str(target)

    # run_path has one difference with invoking Python from command-line:
    # if the target is a file (rather than a directory), it does not add its
    # parent directory to sys.path. Thus, importing other modules from the
    # same directory is broken unless sys.path is patched here.

    if os.path.isfile(target_as_str):
        dir = os.path.dirname(target_as_str)
        sys.path.insert(0, dir)
    else:
        log.debug("Not a file: {0!r}", target)

    log.describe_environment("Pre-launch environment:")

    log.info("Running file {0!r}", target)
    runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
# Buggy code
def run_code():
    # Add current directory to path, like Python itself does for -c.
    sys.path.insert(0, "")
    code = compile(options.target, "<string>", "exec")

    start_debugging("-c")

    log.describe_environment("Pre-launch environment:")
    log.info("Running code:\n\n{0}", options.target)

    eval(code, {})


# Traceback (IOError)
Traceback (most recent call last):
File "c:/Users/kanadig/.vscode/extensions/ms-python.python-2019.5.17059/pythonFiles/ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 434, in main
run()
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 312, in run_file
runpy.run_path(target, run_name='__main__')
File "C:\Python27\lib\runpy.py", line 251, in run_path
code = _get_code_from_file(path_name)
File "C:\Python27\lib\runpy.py", line 227, in _get_code_from_file
with open(fname, "rb") as f:
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\\GIT\\pyscratch2\\??\\experiment.py'

# Fixed code
def run_code():
    # Add current directory to path, like Python itself does for -c.
    sys.path.insert(0, str(""))
    code = compile(options.target, str("<string>"), str("exec"))

    start_debugging(str("-c"))

    log.describe_environment("Pre-launch environment:")
    log.info("Running code:\n\n{0}", options.target)

    eval(code, {})
# Buggy code
def main():
    original_argv = list(sys.argv)
    try:
        parse_argv()
    except Exception as exc:
        print(HELP + "\nError: " + str(exc), file=sys.stderr)
        sys.exit(2)

    if options.log_to is not None:
        debugpy.log_to(options.log_to)
    if options.log_to_stderr:
        debugpy.log_to(sys.stderr)

    api.ensure_logging()

    log.info(
        "sys.argv before parsing: {0!r}\n         after parsing:  {1!r}",
        original_argv,
        sys.argv,
    )

    try:
        run = {
            "file": run_file,
            "module": run_module,
            "code": run_code,
            "pid": attach_to_pid,
        }[options.target_kind]
        run()
    except SystemExit as exc:
        log.reraise_exception(
            "Debuggee exited via SystemExit: {0!r}", exc.code, level="debug"
        )


# Traceback (IOError)
Traceback (most recent call last):
File "c:/Users/kanadig/.vscode/extensions/ms-python.python-2019.5.17059/pythonFiles/ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 434, in main
run()
File "C:\GIT\ptvsd\src\ptvsd\__main__.py", line 312, in run_file
runpy.run_path(target, run_name='__main__')
File "C:\Python27\lib\runpy.py", line 251, in run_path
code = _get_code_from_file(path_name)
File "C:\Python27\lib\runpy.py", line 227, in _get_code_from_file
with open(fname, "rb") as f:
IOError: [Errno 22] invalid mode ('rb') or filename: 'c:\\GIT\\pyscratch2\\??\\experiment.py'

# Fixed code
def main():
    original_argv = list(sys.argv)
    try:
        parse_argv()
    except Exception as exc:
        print(str(HELP) + str("\nError: ") + str(exc), file=sys.stderr)
        sys.exit(2)

    if options.log_to is not None:
        debugpy.log_to(options.log_to)
    if options.log_to_stderr:
        debugpy.log_to(sys.stderr)

    api.ensure_logging()

    log.info(
        str("sys.argv before parsing: {0!r}\n         after parsing:  {1!r}"),
        original_argv,
        sys.argv,
    )

    try:
        run = {
            "file": run_file,
            "module": run_module,
            "code": run_code,
            "pid": attach_to_pid,
        }[options.target_kind]
        run()
    except SystemExit as exc:
        log.reraise_exception(
            "Debuggee exited via SystemExit: {0!r}", exc.code, level="debug"
        )
# Buggy code
def list_all(resolve=False):
    """Return the list of vendored projects."""
    # TODO: Derive from os.listdir(VENDORED_ROOT)?
    projects = [
        "pydevd",
    ]
    if not resolve:
        return projects
    return [project_root(name) for name in projects]


# Traceback (AttributeError)
/usr/bin/env /usr/bin/python3 /Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/launcher 60731 -- odoo-bin -c odoo.conf
~/git-repo/odoo(master ✗)  /usr/bin/env /usr/bin/python3 /Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/launcher 60731 -- odoo-bin -c odoo.conf
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/__main__.py", line 43, in <module>
from debugpy.server import cli
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/../debugpy/server/__init__.py", line 9, in <module>
import debugpy._vendored.force_pydevd  # noqa
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/../debugpy/_vendored/force_pydevd.py", line 15, in <module>
prefix_matcher('pydev', '_pydev'))
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/../debugpy/_vendored/__init__.py", line 106, in check_modules
elif not mod.__file__.startswith(root):
AttributeError: 'NoneType' object has no attribute 'startswith'

# Fixed code
def list_all(resolve=False):
    """Return the list of vendored projects."""
    # TODO: Derive from os.listdir(VENDORED_ROOT)?
    projects = ["pydevd"]
    if not resolve:
        return projects
    return [project_root(name) for name in projects]
# Buggy code
def project_root(project):
    """Return the path the root dir of the vendored project.

    If "project" is an empty string then the path prefix for vendored
    projects (e.g. "debugpy/_vendored/") will be returned.
    """
    if not project:
        project = ""
    return os.path.join(VENDORED_ROOT, project)


# Traceback (AttributeError)
/usr/bin/env /usr/bin/python3 /Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/launcher 60731 -- odoo-bin -c odoo.conf
~/git-repo/odoo(master ✗)  /usr/bin/env /usr/bin/python3 /Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/launcher 60731 -- odoo-bin -c odoo.conf
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/__main__.py", line 43, in <module>
from debugpy.server import cli
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/../debugpy/server/__init__.py", line 9, in <module>
import debugpy._vendored.force_pydevd  # noqa
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/../debugpy/_vendored/force_pydevd.py", line 15, in <module>
prefix_matcher('pydev', '_pydev'))
File "/Users/jeffery/.vscode/extensions/ms-python.python-2020.11.371526539/pythonFiles/lib/python/debugpy/../debugpy/_vendored/__init__.py", line 106, in check_modules
elif not mod.__file__.startswith(root):
AttributeError: 'NoneType' object has no attribute 'startswith'

# Fixed code
def project_root(project):
    """Return the path the root dir of the vendored project.

    If "project" is an empty string then the path prefix for vendored
    projects (e.g. "debugpy/_vendored/") will be returned.
    """
    if not project:
        project = ""
    return os.path.join(VENDORED_ROOT, project)