gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(
    self,
    callback,
    pass_update_queue=False,
    pass_job_queue=False,
    pass_user_data=False,
    pass_chat_data=False,
):
    self.callback = callback
    self.pass_update_queue = pass_update_queue
    self.pass_job_queue = pass_job_queue
    self.pass_user_data = pass_user_data
    self.pass_chat_data = pass_chat_data


# Traceback (telegram.error.BadRequest)
<project_path>/venv/bin/python <project_path>/issue.py
2017-06-20 23:24:11,743 - __main__ - INFO - /start
2017-06-20 23:24:11,906 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update.
2017-06-20 23:24:11,907 - __main__ - ERROR - Boom!
2017-06-20 23:24:11,907 - __main__ - INFO - /async_start
2017-06-20 23:24:12,188 - telegram.utils.promise - ERROR - An uncaught error was raised while running the promise
Traceback (most recent call last):
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/promise.py", line 42, in run
self._result = self.pooled_function(*self.args, **self.kwargs)
File "<project_path>/issue.py", line 25, in action_async_start
update.message.reply_text(msg, parse_mode=ParseMode.HTML)
File "<project_path>/venv/src/python-telegram-bot/telegram/message.py", line 340, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 125, in decorator
result = func(self, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 158, in decorator
return Bot._message_wrapper(self, url, data, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 146, in _message_wrapper
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 252, in post
**urlopen_kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 194, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Can't parse entities in message text: unsupported start tag "invalid_tag" at byte offset 0

Process finished with exit code 0

# Fixed code
def __init__(
    self,
    callback,
    pass_update_queue=False,
    pass_job_queue=False,
    pass_user_data=False,
    pass_chat_data=False,
    run_async=False,
):
    self.callback = callback
    self.pass_update_queue = pass_update_queue
    self.pass_job_queue = pass_job_queue
    self.pass_user_data = pass_user_data
    self.pass_chat_data = pass_chat_data
    self.run_async = run_async
# Buggy code
def __init__(
    self,
    command,
    callback,
    pass_args=False,
    pass_update_queue=False,
    pass_job_queue=False,
):
    super().__init__(
        callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue
    )
    self.command = command
    self.pass_args = pass_args


# Traceback (telegram.error.BadRequest)
<project_path>/venv/bin/python <project_path>/issue.py
2017-06-20 23:24:11,743 - __main__ - INFO - /start
2017-06-20 23:24:11,906 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update.
2017-06-20 23:24:11,907 - __main__ - ERROR - Boom!
2017-06-20 23:24:11,907 - __main__ - INFO - /async_start
2017-06-20 23:24:12,188 - telegram.utils.promise - ERROR - An uncaught error was raised while running the promise
Traceback (most recent call last):
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/promise.py", line 42, in run
self._result = self.pooled_function(*self.args, **self.kwargs)
File "<project_path>/issue.py", line 25, in action_async_start
update.message.reply_text(msg, parse_mode=ParseMode.HTML)
File "<project_path>/venv/src/python-telegram-bot/telegram/message.py", line 340, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 125, in decorator
result = func(self, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 158, in decorator
return Bot._message_wrapper(self, url, data, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 146, in _message_wrapper
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 252, in post
**urlopen_kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 194, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Can't parse entities in message text: unsupported start tag "invalid_tag" at byte offset 0

Process finished with exit code 0

# Fixed code
def __init__(
    self,
    command,
    callback,
    pass_args=False,
    pass_update_queue=False,
    pass_job_queue=False,
    run_async=False,
):
    super().__init__(
        callback,
        pass_update_queue=pass_update_queue,
        pass_job_queue=pass_job_queue,
        run_async=run_async,
    )
    self.command = command
    self.pass_args = pass_args
# Buggy code
def __init__(
    self,
    pattern,
    callback,
    pass_groups=False,
    pass_groupdict=False,
    pass_update_queue=False,
    pass_job_queue=False,
):
    super().__init__(
        callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue
    )

    if isinstance(pattern, str):
        pattern = re.compile(pattern)

    self.pattern = pattern
    self.pass_groups = pass_groups
    self.pass_groupdict = pass_groupdict


# Traceback (telegram.error.BadRequest)
<project_path>/venv/bin/python <project_path>/issue.py
2017-06-20 23:24:11,743 - __main__ - INFO - /start
2017-06-20 23:24:11,906 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update.
2017-06-20 23:24:11,907 - __main__ - ERROR - Boom!
2017-06-20 23:24:11,907 - __main__ - INFO - /async_start
2017-06-20 23:24:12,188 - telegram.utils.promise - ERROR - An uncaught error was raised while running the promise
Traceback (most recent call last):
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/promise.py", line 42, in run
self._result = self.pooled_function(*self.args, **self.kwargs)
File "<project_path>/issue.py", line 25, in action_async_start
update.message.reply_text(msg, parse_mode=ParseMode.HTML)
File "<project_path>/venv/src/python-telegram-bot/telegram/message.py", line 340, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 125, in decorator
result = func(self, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 158, in decorator
return Bot._message_wrapper(self, url, data, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 146, in _message_wrapper
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 252, in post
**urlopen_kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 194, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Can't parse entities in message text: unsupported start tag "invalid_tag" at byte offset 0

Process finished with exit code 0

# Fixed code
def __init__(
    self,
    pattern,
    callback,
    pass_groups=False,
    pass_groupdict=False,
    pass_update_queue=False,
    pass_job_queue=False,
    run_async=False,
):
    super().__init__(
        callback,
        pass_update_queue=pass_update_queue,
        pass_job_queue=pass_job_queue,
        run_async=run_async,
    )

    if isinstance(pattern, str):
        pattern = re.compile(pattern)

    self.pattern = pattern
    self.pass_groups = pass_groups
    self.pass_groupdict = pass_groupdict
# Buggy code
def __init__(
    self, type, callback, strict=False, pass_update_queue=False, pass_job_queue=False
):
    super().__init__(
        callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue
    )
    self.type = type
    self.strict = strict


# Traceback (telegram.error.BadRequest)
<project_path>/venv/bin/python <project_path>/issue.py
2017-06-20 23:24:11,743 - __main__ - INFO - /start
2017-06-20 23:24:11,906 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update.
2017-06-20 23:24:11,907 - __main__ - ERROR - Boom!
2017-06-20 23:24:11,907 - __main__ - INFO - /async_start
2017-06-20 23:24:12,188 - telegram.utils.promise - ERROR - An uncaught error was raised while running the promise
Traceback (most recent call last):
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/promise.py", line 42, in run
self._result = self.pooled_function(*self.args, **self.kwargs)
File "<project_path>/issue.py", line 25, in action_async_start
update.message.reply_text(msg, parse_mode=ParseMode.HTML)
File "<project_path>/venv/src/python-telegram-bot/telegram/message.py", line 340, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 125, in decorator
result = func(self, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 158, in decorator
return Bot._message_wrapper(self, url, data, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 146, in _message_wrapper
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 252, in post
**urlopen_kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 194, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Can't parse entities in message text: unsupported start tag "invalid_tag" at byte offset 0

Process finished with exit code 0

# Fixed code
def __init__(
    self,
    type,
    callback,
    strict=False,
    pass_update_queue=False,
    pass_job_queue=False,
    run_async=False,
):
    super().__init__(
        callback,
        pass_update_queue=pass_update_queue,
        pass_job_queue=pass_job_queue,
        run_async=run_async,
    )
    self.type = type
    self.strict = strict
# Buggy code
def __init__(self, pooled_function, args, kwargs):
    self.pooled_function = pooled_function
    self.args = args
    self.kwargs = kwargs
    self.done = Event()
    self._result = None
    self._exception = None


# Traceback (telegram.error.BadRequest)
<project_path>/venv/bin/python <project_path>/issue.py
2017-06-20 23:24:11,743 - __main__ - INFO - /start
2017-06-20 23:24:11,906 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update.
2017-06-20 23:24:11,907 - __main__ - ERROR - Boom!
2017-06-20 23:24:11,907 - __main__ - INFO - /async_start
2017-06-20 23:24:12,188 - telegram.utils.promise - ERROR - An uncaught error was raised while running the promise
Traceback (most recent call last):
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/promise.py", line 42, in run
self._result = self.pooled_function(*self.args, **self.kwargs)
File "<project_path>/issue.py", line 25, in action_async_start
update.message.reply_text(msg, parse_mode=ParseMode.HTML)
File "<project_path>/venv/src/python-telegram-bot/telegram/message.py", line 340, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 125, in decorator
result = func(self, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 158, in decorator
return Bot._message_wrapper(self, url, data, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 146, in _message_wrapper
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 252, in post
**urlopen_kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 194, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Can't parse entities in message text: unsupported start tag "invalid_tag" at byte offset 0

Process finished with exit code 0

# Fixed code
def __init__(self, pooled_function, args, kwargs, update=None, error_handling=True):
    self.pooled_function = pooled_function
    self.args = args
    self.kwargs = kwargs
    self.update = update
    self.error_handling = error_handling
    self.done = Event()
    self._result = None
    self._exception = None
# Buggy code
def run(self):
    """Calls the :attr:`pooled_function` callable."""

    try:
        self._result = self.pooled_function(*self.args, **self.kwargs)

    except Exception as exc:
        logger.exception("An uncaught error was raised while running the promise")
        self._exception = exc

    finally:
        self.done.set()


# Traceback (telegram.error.BadRequest)
<project_path>/venv/bin/python <project_path>/issue.py
2017-06-20 23:24:11,743 - __main__ - INFO - /start
2017-06-20 23:24:11,906 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update.
2017-06-20 23:24:11,907 - __main__ - ERROR - Boom!
2017-06-20 23:24:11,907 - __main__ - INFO - /async_start
2017-06-20 23:24:12,188 - telegram.utils.promise - ERROR - An uncaught error was raised while running the promise
Traceback (most recent call last):
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/promise.py", line 42, in run
self._result = self.pooled_function(*self.args, **self.kwargs)
File "<project_path>/issue.py", line 25, in action_async_start
update.message.reply_text(msg, parse_mode=ParseMode.HTML)
File "<project_path>/venv/src/python-telegram-bot/telegram/message.py", line 340, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 125, in decorator
result = func(self, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 158, in decorator
return Bot._message_wrapper(self, url, data, *args, **kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/bot.py", line 146, in _message_wrapper
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 252, in post
**urlopen_kwargs)
File "<project_path>/venv/src/python-telegram-bot/telegram/utils/request.py", line 194, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Can't parse entities in message text: unsupported start tag "invalid_tag" at byte offset 0

Process finished with exit code 0

# Fixed code
def run(self):
    """Calls the :attr:`pooled_function` callable."""

    try:
        self._result = self.pooled_function(*self.args, **self.kwargs)

    except Exception as exc:
        self._exception = exc

    finally:
        self.done.set()
# Buggy code
def serve_forever(self):
    with self.server_lock:
        IOLoop().make_current()
        self.is_running = True
        self.logger.debug("Webhook Server started.")
        self.http_server.listen(self.port, address=self.listen)
        self.loop = IOLoop.current()
        self.loop.start()
        self.logger.debug("Webhook Server stopped.")
        self.is_running = False


# Traceback (NotImplementedError)
Exception in thread Bot:377489430:updater:
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Program Files\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\telegram\ext\updater.py", line 216, in _thread_wrapper
target(*args, **kwargs)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\telegram\ext\updater.py", line 452, in _start_webhook
self.httpd.serve_forever()
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\telegram\utils\webhookhandler.py", line 52, in serve_forever
self.http_server.listen(self.port, address=self.listen)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\tcpserver.py", line 152, in listen
self.add_sockets(sockets)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
self._handlers[sock.fileno()] = add_accept_handler(
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
io_loop.add_handler(sock, accept_handler, IOLoop.READ)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\platform\asyncio.py", line 100, in add_handler
self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
File "C:\Program Files\Python38\lib\asyncio\events.py", line 501, in add_reader
raise NotImplementedError
NotImplementedError

# Fixed code
def serve_forever(self, force_event_loop=False, ready=None):
    with self.server_lock:
        self.is_running = True
        self.logger.debug("Webhook Server started.")
        self._ensure_event_loop(force_event_loop=force_event_loop)
        self.loop = IOLoop.current()
        self.http_server.listen(self.port, address=self.listen)

        if ready is not None:
            ready.set()

        self.loop.start()
        self.logger.debug("Webhook Server stopped.")
        self.is_running = False
# Buggy code
def __init__(self, application, request, **kwargs):
    super().__init__(application, request, **kwargs)
    self.logger = logging.getLogger(__name__)
    self._init_asyncio_patch()


# Traceback (NotImplementedError)
Exception in thread Bot:377489430:updater:
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Program Files\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\telegram\ext\updater.py", line 216, in _thread_wrapper
target(*args, **kwargs)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\telegram\ext\updater.py", line 452, in _start_webhook
self.httpd.serve_forever()
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\telegram\utils\webhookhandler.py", line 52, in serve_forever
self.http_server.listen(self.port, address=self.listen)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\tcpserver.py", line 152, in listen
self.add_sockets(sockets)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
self._handlers[sock.fileno()] = add_accept_handler(
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
io_loop.add_handler(sock, accept_handler, IOLoop.READ)
File "C:\Users\User\.virtualenvs\sandbox38\lib\site-packages\tornado\platform\asyncio.py", line 100, in add_handler
self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
File "C:\Program Files\Python38\lib\asyncio\events.py", line 501, in add_reader
raise NotImplementedError
NotImplementedError

# Fixed code
def __init__(self, application, request, **kwargs):
    super().__init__(application, request, **kwargs)
    self.logger = logging.getLogger(__name__)
# Buggy code
def _trigger_timeout(self, bot, job):
    self.logger.debug("conversation timeout was triggered!")
    del self.timeout_jobs[job.context.conversation_key]
    handlers = self.states.get(self.TIMEOUT, [])
    for handler in handlers:
        check = handler.check_update(job.context.update)
        if check is not None and check is not False:
            handler.handle_update(job.context.update, job.context.dispatcher, check)
    self.update_state(self.END, job.context.conversation_key)


# Traceback (TypeError)
2019-03-18 10:33:52,327 - JobQueue - DEBUG - Ticking jobs with t=1552876432.327480
2019-03-18 10:33:52,329 - JobQueue - DEBUG - Peeked at _trigger_timeout with t=1552876432.325519
2019-03-18 10:33:52,331 - JobQueue - DEBUG - Running job _trigger_timeout
2019-03-18 10:33:52,332 - JobQueue - ERROR - An uncaught error was raised while executing job _trigger_timeout
Traceback (most recent call last):
File "/venv/lib/python3.7/site-packages/telegram/ext/jobqueue.py", line 260, in tick
job.run(self._dispatcher)
File "/venv/lib/python3.7/site-packages/telegram/ext/jobqueue.py", line 388, in run
self.callback(CallbackContext.from_job(self, dispatcher))
TypeError: _trigger_timeout() missing 1 required positional argument: 'job'
2019-03-18 10:33:52,338 - JobQueue - DEBUG - Dropping non-repeating or removed job _trigger_timeout

# Fixed code
def _trigger_timeout(self, context, job=None):
    self.logger.debug("conversation timeout was triggered!")

    # Backward compatibility with bots that do not use CallbackContext
    if isinstance(context, CallbackContext):
        context = context.job.context
    else:
        context = job.context

    del self.timeout_jobs[context.conversation_key]
    handlers = self.states.get(self.TIMEOUT, [])
    for handler in handlers:
        check = handler.check_update(context.update)
        if check is not None and check is not False:
            handler.handle_update(context.update, context.dispatcher, check)
    self.update_state(self.END, context.conversation_key)
# Buggy code
def __init__(self, file_id, bot, file_size=None, file_path=None, **kwargs):
    # Required
    self.file_id = str(file_id)

    # Optionals
    self.file_size = file_size
    if file_path:
        self.file_path = str(file_path)

    self.bot = bot

    self._id_attrs = (self.file_id,)


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/telegram/file.py", line 106, in download
self.bot.request.download(url, filename, timeout=timeout)
File "/usr/local/lib/python3.6/site-packages/telegram/utils/request.py", line 284, in download
buf = self.retrieve(url, timeout=timeout)
File "/usr/local/lib/python3.6/site-packages/telegram/utils/request.py", line 270, in retrieve
return self._request_wrapper('GET', url, **urlopen_kwargs)
File "/usr/local/lib/python3.6/site-packages/telegram/utils/request.py", line 174, in _request_wrapper
resp = self._con_pool.request(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/telegram/vendor/ptb_urllib3/urllib3/request.py", line 66, in request
**urlopen_kw)
File "/usr/local/lib/python3.6/site-packages/telegram/vendor/ptb_urllib3/urllib3/request.py", line 87, in request_encode_url
return self.urlopen(method, url, **extra_kw)
File "/usr/local/lib/python3.6/site-packages/telegram/vendor/ptb_urllib3/urllib3/poolmanager.py", line 244, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "/usr/local/lib/python3.6/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py", line 617, in urlopen
chunked=chunked)
File "/usr/local/lib/python3.6/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py", line 390, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1250, in _send_request
self.putrequest(method, url, **skips)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py", line 1117, in putrequest
self._output(request.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 69-75: ordinal not in range(128)
'ascii' codec can't encode characters in position 69-75: ordinal not in range(128)

# Fixed code
def __init__(self, file_id, bot, file_size=None, file_path=None, **kwargs):
    # Required
    self.file_id = str(file_id)

    # Optionals
    self.file_size = file_size
    self.file_path = file_path

    self.bot = bot

    self._id_attrs = (self.file_id,)
# Buggy code
def _start_webhook(
    self, listen, port, url_path, cert, key, bootstrap_retries, webhook_url
):
    self.logger.debug("Updater thread started")
    use_ssl = cert is not None and key is not None
    if not url_path.startswith("/"):
        url_path = "/{0}".format(url_path)

    # Create and start server
    self.httpd = WebhookServer(
        (listen, port), WebhookHandler, self.update_queue, url_path
    )

    if use_ssl:
        self._check_ssl_cert(cert, key)

        # DO NOT CHANGE: Only set webhook if SSL is handled by library
        if not webhook_url:
            webhook_url = self._gen_webhook_url(listen, port, url_path)

        self._set_webhook(webhook_url, bootstrap_retries, open(cert, "rb"))

    self.httpd.serve_forever(poll_interval=1)


# Traceback (telegram.error.NetworkError)
Traceback (most recent call last):
File "main.py", line 43, in <module>
main()
File "main.py", line 34, in main
updates = bot.getUpdates()
File "/usr/local/lib/python3.5/site-packages/telegram/bot.py", line 114, in decorator
result = func(self, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/telegram/bot.py", line 1315, in getUpdates
result = request.post(url, data, timeout=urlopen_timeout)
File "/usr/local/lib/python3.5/site-packages/telegram/utils/request.py", line 83, in decorator
raise NetworkError('URLError: {0}'.format(error.reason))
telegram.error.NetworkError: URLError: _ssl.c:629: The handshake operation timed out

# Fixed code
def _start_webhook(
    self, listen, port, url_path, cert, key, bootstrap_retries, clean, webhook_url
):
    self.logger.debug("Updater thread started")
    use_ssl = cert is not None and key is not None
    if not url_path.startswith("/"):
        url_path = "/{0}".format(url_path)

    # Create and start server
    self.httpd = WebhookServer(
        (listen, port), WebhookHandler, self.update_queue, url_path
    )

    if use_ssl:
        self._check_ssl_cert(cert, key)

        # DO NOT CHANGE: Only set webhook if SSL is handled by library
        if not webhook_url:
            webhook_url = self._gen_webhook_url(listen, port, url_path)

        self._bootstrap(
            max_retries=bootstrap_retries,
            clean=clean,
            webhook_url=webhook_url,
            cert=open(cert, "rb"),
        )
    elif clean:
        self.logger.warning(
            "cleaning updates is not supported if "
            "SSL-termination happens elsewhere; skipping"
        )

    self.httpd.serve_forever(poll_interval=1)
# Buggy code
def _gen_webhook_url(self, listen, port, url_path):
    return "https://{listen}:{port}{path}".format(
        listen=listen, port=port, path=url_path
    )


# Traceback (telegram.error.NetworkError)
Traceback (most recent call last):
File "main.py", line 43, in <module>
main()
File "main.py", line 34, in main
updates = bot.getUpdates()
File "/usr/local/lib/python3.5/site-packages/telegram/bot.py", line 114, in decorator
result = func(self, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/telegram/bot.py", line 1315, in getUpdates
result = request.post(url, data, timeout=urlopen_timeout)
File "/usr/local/lib/python3.5/site-packages/telegram/utils/request.py", line 83, in decorator
raise NetworkError('URLError: {0}'.format(error.reason))
telegram.error.NetworkError: URLError: _ssl.c:629: The handshake operation timed out

# Fixed code
def _gen_webhook_url(listen, port, url_path):
    return "https://{listen}:{port}{path}".format(
        listen=listen, port=port, path=url_path
    )
# Buggy code
def main():
    global job_queue

    updater = Updater("TOKEN")
    job_queue = updater.job_queue

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.addHandler(CommandHandler("start", start))
    dp.addHandler(CommandHandler("help", start))
    dp.addHandler(CommandHandler("set", set))

    # log all errors
    dp.addErrorHandler(error)

    # Start the Bot
    updater.start_polling()

    # Block until the you presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()


# Traceback (TypeError)
2016-04-29 11:38:22,002 - telegram.ext.dispatcher - ERROR - An uncaught error was raised while processing the update
Traceback (most recent call last):
File "build/bdist.linux-i686/egg/telegram/ext/dispatcher.py", line 180, in processUpdate
handler.handleUpdate(update, self)
File "build/bdist.linux-i686/egg/telegram/ext/commandhandler.py", line 66, in handleUpdate
self.callback(dispatcher.bot, update, **optional_args)
TypeError: set() takes exactly 3 arguments (2 given)

# Fixed code
def main():
    global job_queue

    updater = Updater("TOKEN")
    job_queue = updater.job_queue

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.addHandler(CommandHandler("start", start))
    dp.addHandler(CommandHandler("help", start))
    dp.addHandler(CommandHandler("set", set, pass_args=True))

    # log all errors
    dp.addErrorHandler(error)

    # Start the Bot
    updater.start_polling()

    # Block until the you presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
# Buggy code
def message(bot, update):
    """
    Example for an asynchronous handler. It's not guaranteed that replies will
    be in order when using @run_async.
    """

    sleep(2)  # IO-heavy operation here
    bot.sendMessage(update.message.chat_id, text="Echo: %s" % update.message.text)


# Traceback (TypeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\threading.py", line 923, in _bootstrap_inner
self.run()
File "C:\Program Files\Python 3.5\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python 3.5\lib\site-packages\telegram\dispatcher.py", line 39, in pooled
result = func(*args, **kwargs)
TypeError: akkarin() missing 1 required positional argument: 'args'

# Fixed code
def message(bot, update, **kwargs):
    """
    Example for an asynchronous handler. It's not guaranteed that replies will
    be in order when using @run_async. Also, you have to include **kwargs in
    your parameter list.
    """

    print(kwargs)

    sleep(2)  # IO-heavy operation here
    bot.sendMessage(update.message.chat_id, text="Echo: %s" % update.message.text)
# Buggy code
def run_async(func):
    """
    Function decorator that will run the function in a new thread.

    Args:
        func (function): The function to run in the thread.

    Returns:
        function:
    """

    @wraps(func)
    def pooled(*args, **kwargs):
        """
        A wrapper to run a thread in a thread pool
        """
        global running_async, async_lock
        result = func(*args, **kwargs)
        semaphore.release()
        with async_lock:
            running_async -= 1
        return result

    @wraps(func)
    def async_func(*args, **kwargs):
        """
        A wrapper to run a function in a thread
        """
        global running_async, async_lock
        thread = Thread(target=pooled, args=args, kwargs=kwargs)
        semaphore.acquire()
        with async_lock:
            running_async += 1
        thread.start()
        return thread

    return async_func


# Traceback (TypeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\threading.py", line 923, in _bootstrap_inner
self.run()
File "C:\Program Files\Python 3.5\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python 3.5\lib\site-packages\telegram\dispatcher.py", line 39, in pooled
result = func(*args, **kwargs)
TypeError: akkarin() missing 1 required positional argument: 'args'

# Fixed code
def run_async(func):
    """
    Function decorator that will run the function in a new thread. A function
    decorated with this will have to include **kwargs in their parameter list,
    which will contain all optional parameters.

    Args:
        func (function): The function to run in the thread.

    Returns:
        function:
    """

    @wraps(func)
    def pooled(*pargs, **kwargs):
        """
        A wrapper to run a thread in a thread pool
        """
        global running_async, async_lock
        result = func(*pargs, **kwargs)
        semaphore.release()
        with async_lock:
            running_async -= 1
        return result

    @wraps(func)
    def async_func(*pargs, **kwargs):
        """
        A wrapper to run a function in a thread
        """
        global running_async, async_lock
        thread = Thread(target=pooled, args=pargs, kwargs=kwargs)
        semaphore.acquire()
        with async_lock:
            running_async += 1
        thread.start()
        return thread

    return async_func
# Buggy code
def pooled(*args, **kwargs):
    """
    A wrapper to run a thread in a thread pool
    """
    global running_async, async_lock
    result = func(*args, **kwargs)
    semaphore.release()
    with async_lock:
        running_async -= 1
    return result


# Traceback (TypeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\threading.py", line 923, in _bootstrap_inner
self.run()
File "C:\Program Files\Python 3.5\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python 3.5\lib\site-packages\telegram\dispatcher.py", line 39, in pooled
result = func(*args, **kwargs)
TypeError: akkarin() missing 1 required positional argument: 'args'

# Fixed code
def pooled(*pargs, **kwargs):
    """
    A wrapper to run a thread in a thread pool
    """
    global running_async, async_lock
    result = func(*pargs, **kwargs)
    semaphore.release()
    with async_lock:
        running_async -= 1
    return result
# Buggy code
def async_func(*args, **kwargs):
    """
    A wrapper to run a function in a thread
    """
    global running_async, async_lock
    thread = Thread(target=pooled, args=args, kwargs=kwargs)
    semaphore.acquire()
    with async_lock:
        running_async += 1
    thread.start()
    return thread


# Traceback (TypeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\threading.py", line 923, in _bootstrap_inner
self.run()
File "C:\Program Files\Python 3.5\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python 3.5\lib\site-packages\telegram\dispatcher.py", line 39, in pooled
result = func(*args, **kwargs)
TypeError: akkarin() missing 1 required positional argument: 'args'

# Fixed code
def async_func(*pargs, **kwargs):
    """
    A wrapper to run a function in a thread
    """
    global running_async, async_lock
    thread = Thread(target=pooled, args=pargs, kwargs=kwargs)
    semaphore.acquire()
    with async_lock:
        running_async += 1
    thread.start()
    return thread
# Buggy code
def dispatchStringRegex(self, update):
    """
    Dispatches an update to all string regex handlers that match the
    string.

    Args:
        command (str): The command keyword
        update (telegram.Update): The Telegram update that contains the
            command
    """

    matching_handlers = []

    for matcher in self.string_regex_handlers:
        if match(matcher, update):
            for handler in self.string_regex_handlers[matcher]:
                matching_handlers.append(handler)

    self.dispatchTo(matching_handlers, update)


# Traceback (TypeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\threading.py", line 923, in _bootstrap_inner
self.run()
File "C:\Program Files\Python 3.5\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python 3.5\lib\site-packages\telegram\dispatcher.py", line 39, in pooled
result = func(*args, **kwargs)
TypeError: akkarin() missing 1 required positional argument: 'args'

# Fixed code
def dispatchStringRegex(self, update):
    """
    Dispatches an update to all string regex handlers that match the
    string.

    Args:
        command (str): The command keyword
        update (str): The string that contains the command
    """

    matching_handlers = []

    for matcher in self.string_regex_handlers:
        if match(matcher, update):
            for handler in self.string_regex_handlers[matcher]:
                matching_handlers.append(handler)

    self.dispatchTo(matching_handlers, update)
# Buggy code
def dispatchTo(self, handlers, update):
    """
    Dispatches an update to a list of handlers.

    Args:
        handlers (list): A list of handler-functions.
        update (any): The update to be dispatched
    """

    for handler in handlers:
        self.call_handler(handler, update)


# Traceback (TypeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\threading.py", line 923, in _bootstrap_inner
self.run()
File "C:\Program Files\Python 3.5\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python 3.5\lib\site-packages\telegram\dispatcher.py", line 39, in pooled
result = func(*args, **kwargs)
TypeError: akkarin() missing 1 required positional argument: 'args'

# Fixed code
def dispatchTo(self, handlers, update, **kwargs):
    """
    Dispatches an update to a list of handlers.

    Args:
        handlers (list): A list of handler-functions.
        update (any): The update to be dispatched
    """

    for handler in handlers:
        self.call_handler(handler, update, **kwargs)
# Buggy code
def call_handler(self, handler, update):
    """
    Calls an update handler. Checks the handler for keyword arguments and
    fills them, if possible.

    Args:
        handler (function): An update handler function
        update (any): An update
    """
    kwargs = {}
    fargs = getargspec(handler).args

    if "update_queue" in fargs:
        kwargs["update_queue"] = self.update_queue

    if "args" in fargs:
        if isinstance(update, Update):
            args = update.message.text.split(" ")[1:]
        elif isinstance(update, str):
            args = update.split(" ")[1:]
        else:
            args = None

        kwargs["args"] = args

    handler(self.bot, update, **kwargs)


# Traceback (TypeError)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\threading.py", line 923, in _bootstrap_inner
self.run()
File "C:\Program Files\Python 3.5\lib\threading.py", line 871, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python 3.5\lib\site-packages\telegram\dispatcher.py", line 39, in pooled
result = func(*args, **kwargs)
TypeError: akkarin() missing 1 required positional argument: 'args'

# Fixed code
def call_handler(self, handler, update, **kwargs):
    """
    Calls an update handler. Checks the handler for keyword arguments and
    fills them, if possible.

    Args:
        handler (function): An update handler function
        update (any): An update
    """

    target_kwargs = {}
    fargs = getargspec(handler).args

    """
        async handlers will receive all optional arguments, since we can't
        their argument list.
        """

    is_async = "pargs" == getargspec(handler).varargs

    if is_async or "update_queue" in fargs:
        target_kwargs["update_queue"] = self.update_queue

    if is_async or "args" in fargs:
        if isinstance(update, Update):
            args = update.message.text.split(" ")[1:]
        elif isinstance(update, str):
            args = update.split(" ")[1:]
        else:
            args = None

        target_kwargs["args"] = args

    if is_async or "groups" in fargs:
        target_kwargs["groups"] = kwargs.get("groups", None)

    if is_async or "groupdict" in fargs:
        target_kwargs["groupdict"] = kwargs.get("groupdict", None)

    handler(self.bot, update, **target_kwargs)
# Buggy code
def __init__(self, args, as_module=False):
    self.args = args
    self.as_module = as_module

    self.arg0 = args[0]
    self.package = self.modulename = self.pathname = None


# Traceback (AttributeError)
$ python --version
Python 3.5.6 :: Anaconda, Inc.

$ coverage --version
Coverage.py, version 4.5.1 with C extension
Documentation at https://coverage.readthedocs.io

$ cat foo.py
print(__name__)
print(__spec__.name)

$ python -m foo  # Behaves as expected
__main__
foo

$ coverage run -m foo  # Observe __spec__ is None
__main__
Traceback (most recent call last):
File "/nas/dft/ire/rhys/Build/liquidmetal-debt/foo.py", line 2, in <module>
print(__spec__.name)
AttributeError: 'NoneType' object has no attribute 'name'
Coverage.py warning: No data was collected. (no-data-collected)

# Fixed code
def __init__(self, args, as_module=False):
    self.args = args
    self.as_module = as_module

    self.arg0 = args[0]
    self.package = self.modulename = self.pathname = self.loader = self.spec = None
# Buggy code
def finalize_options(self):
    upload.finalize_options(self)
    if self.upload_dir is None:
        if self.has_sphinx():
            build_sphinx = self.get_finalized_command("build_sphinx")
            self.target_dir = build_sphinx.builder_target_dir
        else:
            build = self.get_finalized_command("build")
            self.target_dir = os.path.join(build.build_base, "docs")
    else:
        self.ensure_dirname("upload_dir")
        self.target_dir = self.upload_dir
    if "pypi.python.org" in self.repository:
        log.warn("Upload_docs command is deprecated. Use RTD instead.")
    self.announce("Using upload directory %s" % self.target_dir)


# Traceback (AttributeError)
Traceback (most recent call last):
File "setup.py", line 67, in <module>
setup(**setup_args)
File "/usr/lib/python3.5/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/lib/python3.5/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/usr/lib/python3.5/distutils/dist.py", line 973, in run_command
cmd_obj.ensure_finalized()
File "/usr/lib/python3.5/distutils/cmd.py", line 107, in ensure_finalized
self.finalize_options()
File "/home/dmitry/.local/lib/python3.5/site-packages/setuptools/command/upload_docs.py", line 65, in finalize_options
self.target_dir = build_sphinx.builder_target_dir
File "/usr/lib/python3.5/distutils/cmd.py", line 103, in __getattr__
raise AttributeError(attr)
AttributeError: builder_target_dir

# Fixed code
def finalize_options(self):
    upload.finalize_options(self)
    if self.upload_dir is None:
        if self.has_sphinx():
            build_sphinx = self.get_finalized_command("build_sphinx")
            self.target_dir = dict(build_sphinx.builder_target_dirs)["html"]
        else:
            build = self.get_finalized_command("build")
            self.target_dir = os.path.join(build.build_base, "docs")
    else:
        self.ensure_dirname("upload_dir")
        self.target_dir = self.upload_dir
    if "pypi.python.org" in self.repository:
        log.warn("Upload_docs command is deprecated for PyPi. Use RTD instead.")
    self.announce("Using upload directory %s" % self.target_dir)
# Buggy code
def spec_for_distutils(self):
    import importlib.abc
    import importlib.util

    class DistutilsLoader(importlib.abc.Loader):
        def create_module(self, spec):
            return importlib.import_module("._distutils", "setuptools")

        def exec_module(self, module):
            pass

    return importlib.util.spec_from_loader("distutils", DistutilsLoader())


# Traceback (SystemError)
$ python --version
Python 3.5.1
$ python -c "import distutils"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "/home/gchan/tmp/setuptools-python-3.5/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module
return importlib.import_module('._distutils', 'setuptools')
File "/home/gchan/tmp/setuptools-python-3.5/lib64/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 981, in _gcd_import
File "<frozen importlib._bootstrap>", line 931, in _sanity_check
SystemError: Parent module 'setuptools' not loaded, cannot perform relative import

# Fixed code
def spec_for_distutils(self):
    import importlib.abc
    import importlib.util

    class DistutilsLoader(importlib.abc.Loader):
        def create_module(self, spec):
            return importlib.import_module("setuptools._distutils")

        def exec_module(self, module):
            pass

    return importlib.util.spec_from_loader("distutils", DistutilsLoader())
# Buggy code
def create_module(self, spec):
    return importlib.import_module("._distutils", "setuptools")


# Traceback (SystemError)
$ python --version
Python 3.5.1
$ python -c "import distutils"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "/home/gchan/tmp/setuptools-python-3.5/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module
return importlib.import_module('._distutils', 'setuptools')
File "/home/gchan/tmp/setuptools-python-3.5/lib64/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 981, in _gcd_import
File "<frozen importlib._bootstrap>", line 931, in _sanity_check
SystemError: Parent module 'setuptools' not loaded, cannot perform relative import

# Fixed code
def create_module(self, spec):
    return importlib.import_module("setuptools._distutils")
# Buggy code
async def graphql_http_server(self, request: Request) -> Response:
    try:
        data = await self.extract_data_from_request(request)
    except HttpError as error:
        return PlainTextResponse(error.message or error.status, status_code=400)

    success, response = await self.execute_graphql_query(request, data)

    status_code = 200 if success else 400
    return JSONResponse(response, status_code=status_code)


# Traceback (TypeError)
Traceback (most recent call last):",
File \"/Users/...REDACTED.../virtualenvs/graphql-Pfr5HTvn/lib/python3.7/site-packages/graphql/execution/execute.py\", line 625, in resolve_field_value_or_error",
result = resolve_fn(source, info, **args)",
File \"/Users/...REDACTED.../app/__init__.py\", line 26, in counter_resolver",
return count + 1",
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'"

# Fixed code
async def graphql_http_server(self, request: Request) -> Response:
    try:
        data = await self.extract_data_from_request(request)
    except HttpError as error:
        return PlainTextResponse(error.message or error.status, status_code=400)

    context_value = await self.get_context_for_request(request)
    extensions = await self.get_extensions_for_request(request, context_value)
    middleware = await self.get_middleware_for_request(request, context_value)

    success, response = await graphql(
        self.schema,
        data,
        context_value=context_value,
        root_value=self.root_value,
        debug=self.debug,
        logger=self.logger,
        error_formatter=self.error_formatter,
        extensions=extensions,
        middleware=middleware,
    )
    status_code = 200 if success else 400
    return JSONResponse(response, status_code=status_code)