gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, loop, services, host):
    """Initialize a new UnicastDnsSdClientProtocol."""
    self.message = create_request(services)
    self.host = host
    self.loop = loop
    self.transport = None
    self.semaphore = asyncio.Semaphore(value=0, loop=loop)
    self.result = None


# Traceback (asyncio.TimeoutError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 565, in _run_application
return await cli_handler(loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 388, in cli_handler
return await _handle_commands(args, config, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 480, in _handle_commands
ret = await _handle_device_command(args, cmd, atv, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 517, in _handle_device_command
return (await _exec_command(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 531, in _exec_command
value = await tmp(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 71, in play_url
player = await self._player(session)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 51, in _player
await verifier.verify_authed()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 88, in verify_authed
resp = await self._send(self.srp.verify1(), 'verify1')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 100, in _send
resp, code = await self.http.post_data(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 76, in post_data
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 64, in post_data
resp = await self._session.post(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 504, in _request
await resp.start(conn)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 860, in start
self._continue = None
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError

# Fixed code
def __init__(self, loop, services, host, timeout):
    """Initialize a new UnicastDnsSdClientProtocol."""
    self.message = create_request(services)
    self.host = host
    self.timeout = timeout
    self.loop = loop
    self.transport = None
    self.semaphore = asyncio.Semaphore(value=0, loop=loop)
    self.result = None
    self._task = None
# Buggy code
async def get_response(self, timeout):
    """Get respoonse with a maximum timeout."""
    await asyncio.wait_for(self.semaphore.acquire(), timeout=timeout, loop=self.loop)
    return self.result


# Traceback (asyncio.TimeoutError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 565, in _run_application
return await cli_handler(loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 388, in cli_handler
return await _handle_commands(args, config, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 480, in _handle_commands
ret = await _handle_device_command(args, cmd, atv, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 517, in _handle_device_command
return (await _exec_command(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 531, in _exec_command
value = await tmp(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 71, in play_url
player = await self._player(session)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 51, in _player
await verifier.verify_authed()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 88, in verify_authed
resp = await self._send(self.srp.verify1(), 'verify1')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 100, in _send
resp, code = await self.http.post_data(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 76, in post_data
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 64, in post_data
resp = await self._session.post(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 504, in _request
await resp.start(conn)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 860, in start
self._continue = None
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError

# Fixed code
async def get_response(self):
    """Get respoonse with a maximum timeout."""
    await asyncio.wait_for(
        self.semaphore.acquire(), timeout=self.timeout, loop=self.loop
    )
    return self.result
# Buggy code
def connection_made(self, transport):
    """Establish connection to host."""
    log_binary(_LOGGER, "Sending DNS request to " + str(self.host), Data=self.message)

    self.transport = transport
    self.transport.sendto(self.message)


# Traceback (asyncio.TimeoutError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 565, in _run_application
return await cli_handler(loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 388, in cli_handler
return await _handle_commands(args, config, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 480, in _handle_commands
ret = await _handle_device_command(args, cmd, atv, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 517, in _handle_device_command
return (await _exec_command(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 531, in _exec_command
value = await tmp(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 71, in play_url
player = await self._player(session)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 51, in _player
await verifier.verify_authed()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 88, in verify_authed
resp = await self._send(self.srp.verify1(), 'verify1')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 100, in _send
resp, code = await self.http.post_data(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 76, in post_data
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 64, in post_data
resp = await self._session.post(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 504, in _request
await resp.start(conn)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 860, in start
self._continue = None
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError

# Fixed code
def connection_made(self, transport):
    """Establish connection to host."""
    self.transport = transport
    self._task = asyncio.ensure_future(self._resend_loop())
# Buggy code
def datagram_received(self, data, _):
    """DNS response packet received."""
    log_binary(_LOGGER, "Received DNS response from " + str(self.host), Data=data)

    self.result = DnsMessage().unpack(data)
    self.transport.close()


# Traceback (asyncio.TimeoutError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 565, in _run_application
return await cli_handler(loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 388, in cli_handler
return await _handle_commands(args, config, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 480, in _handle_commands
ret = await _handle_device_command(args, cmd, atv, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 517, in _handle_device_command
return (await _exec_command(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 531, in _exec_command
value = await tmp(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 71, in play_url
player = await self._player(session)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 51, in _player
await verifier.verify_authed()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 88, in verify_authed
resp = await self._send(self.srp.verify1(), 'verify1')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 100, in _send
resp, code = await self.http.post_data(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 76, in post_data
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 64, in post_data
resp = await self._session.post(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 504, in _request
await resp.start(conn)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 860, in start
self._continue = None
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError

# Fixed code
def datagram_received(self, data, _):
    """DNS response packet received."""
    log_binary(_LOGGER, "Received DNS response from " + str(self.host), Data=data)

    self.result = DnsMessage().unpack(data)
    self.transport.close()
    self._finished()
# Buggy code
def error_received(self, exc):
    """Error received during communication."""
    _LOGGER.debug("Error during DNS lookup for %s: %s", self.host, exc)
    self.semaphore.release()


# Traceback (asyncio.TimeoutError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 565, in _run_application
return await cli_handler(loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 388, in cli_handler
return await _handle_commands(args, config, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 480, in _handle_commands
ret = await _handle_device_command(args, cmd, atv, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 517, in _handle_device_command
return (await _exec_command(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 531, in _exec_command
value = await tmp(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 71, in play_url
player = await self._player(session)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 51, in _player
await verifier.verify_authed()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 88, in verify_authed
resp = await self._send(self.srp.verify1(), 'verify1')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 100, in _send
resp, code = await self.http.post_data(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 76, in post_data
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 64, in post_data
resp = await self._session.post(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 504, in _request
await resp.start(conn)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 860, in start
self._continue = None
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError

# Fixed code
def error_received(self, exc):
    """Error received during communication."""
    _LOGGER.debug("Error during DNS lookup for %s: %s", self.host, exc)
    self._finished()
# Buggy code
def connection_lost(self, exc):
    """Lose connection to host."""
    self.semaphore.release()


# Traceback (asyncio.TimeoutError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 565, in _run_application
return await cli_handler(loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 388, in cli_handler
return await _handle_commands(args, config, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 480, in _handle_commands
ret = await _handle_device_command(args, cmd, atv, loop)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 517, in _handle_device_command
return (await _exec_command(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/__main__.py", line 531, in _exec_command
value = await tmp(*args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 71, in play_url
player = await self._player(session)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/__init__.py", line 51, in _player
await verifier.verify_authed()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 88, in verify_authed
resp = await self._send(self.srp.verify1(), 'verify1')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/airplay/auth.py", line 100, in _send
resp, code = await self.http.post_data(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 76, in post_data
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pyatv/net.py", line 64, in post_data
resp = await self._session.post(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client.py", line 504, in _request
await resp.start(conn)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/client_reqrep.py", line 860, in start
self._continue = None
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError

# Fixed code
def connection_lost(self, exc):
    """Lose connection to host."""
    self._finished()
# Buggy code
def playstate(state):
    """Convert iTunes playstate to API representation."""
    if state is None:
        return const.PLAY_STATE_NO_MEDIA
    elif state == 1:
        return const.PLAY_STATE_LOADING
    elif state == 3:
        return const.PLAY_STATE_PAUSED
    elif state == 4:
        return const.PLAY_STATE_PLAYING
    elif state == 5:
        return const.PLAY_STATE_FAST_FORWARD
    elif state == 6:
        return const.PLAY_STATE_FAST_BACKWARD

    raise exceptions.UnknownPlayState("Unknown playstate: " + str(state))


# Traceback (pyatv.exceptions.UnknownPlayState)
2017-09-20 14:10:29 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
File “/usr/lib/python3.6/asyncio/tasks.py”, line 179, in _step
result = coro.send(None)
File “/usr/lib/python3.6/site-packages/homeassistant/helpers/entity.py”, line 239, in async_update_ha_state
state = self.state
File “/usr/lib/python3.6/site-packages/homeassistant/components/media_player/apple_tv.py”, line 98, in state
state = self._playing.play_state
File “/usr/lib/python3.6/site-packages/pyatv/internal/apple_tv.py”, line 245, in play_state
return convert.playstate(state)
File “/usr/lib/python3.6/site-packages/pyatv/convert.py”, line 48, in playstate
raise exceptions.UnknownPlayState('Unknown playstate: ’ + str(state))
pyatv.exceptions.UnknownPlayState: Unknown playstate: 0

# Fixed code
def playstate(state):
    """Convert iTunes playstate to API representation."""
    # pylint: disable=too-many-return-statements
    if state is None:
        return const.PLAY_STATE_NO_MEDIA
    elif state == 0:
        return const.PLAY_STATE_IDLE
    elif state == 1:
        return const.PLAY_STATE_LOADING
    elif state == 3:
        return const.PLAY_STATE_PAUSED
    elif state == 4:
        return const.PLAY_STATE_PLAYING
    elif state == 5:
        return const.PLAY_STATE_FAST_FORWARD
    elif state == 6:
        return const.PLAY_STATE_FAST_BACKWARD

    raise exceptions.UnknownPlayState("Unknown playstate: " + str(state))
# Buggy code
def login(self):
    """Login to Apple TV using specified login id."""
    # Do not use session.get_data(...) in login as that would end up in
    # an infinte loop.
    url = self._mkurl("login?[AUTH]&hasFP=1", session=False, login_id=True)
    resp = yield from self._do(self.session.get_data, url)
    self._session_id = dmap.first(resp, "mlog", "mlid")
    _LOGGER.info("Logged in and got session id %s", self._session_id)
    return self._session_id


# Traceback (pyatv.exceptions.AuthenticationError)
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/Users/postlund/git/home-assistant/homeassistant/helpers/entity.py", line 200, in async_update_ha_state
yield from self.async_update()
File "/Users/postlund/git/home-assistant/homeassistant/components/media_player/apple_tv.py", line 100, in async_update
playing = yield from self._atv.metadata.playing()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/internal/apple_tv.py", line 225, in playing
playstatus = yield from self.apple_tv.playstatus()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 128, in get
is_daap=daap_data))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 151, in _do
action, url, False, is_login=is_login, is_daap=is_daap))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 154, in _do
'failed to login: ' + str(status))
pyatv.exceptions.AuthenticationError: failed to login: 403

# Fixed code
def login(self):
    """Login to Apple TV using specified login id."""

    # Do not use session.get_data(...) in login as that would end up in
    # an infinte loop.
    def _login_request():
        return self.session.get_data(
            self._mkurl("login?[AUTH]&hasFP=1", session=False, login_id=True)
        )

    resp = yield from self._do(_login_request)
    self._session_id = dmap.first(resp, "mlog", "mlid")
    _LOGGER.info("Logged in and got session id %s", self._session_id)
    return self._session_id
# Buggy code
def get(self, cmd, daap_data=True, **args):
    """Perform a DAAP GET command."""

    def _get_request(url):
        return self.session.get_data(url, should_parse=daap_data)

    yield from self._assure_logged_in()
    return (
        yield from self._do(_get_request, self._mkurl(cmd, *args), is_daap=daap_data)
    )


# Traceback (pyatv.exceptions.AuthenticationError)
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/Users/postlund/git/home-assistant/homeassistant/helpers/entity.py", line 200, in async_update_ha_state
yield from self.async_update()
File "/Users/postlund/git/home-assistant/homeassistant/components/media_player/apple_tv.py", line 100, in async_update
playing = yield from self._atv.metadata.playing()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/internal/apple_tv.py", line 225, in playing
playstatus = yield from self.apple_tv.playstatus()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 128, in get
is_daap=daap_data))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 151, in _do
action, url, False, is_login=is_login, is_daap=is_daap))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 154, in _do
'failed to login: ' + str(status))
pyatv.exceptions.AuthenticationError: failed to login: 403

# Fixed code
def get(self, cmd, daap_data=True, **args):
    """Perform a DAAP GET command."""

    def _get_request():
        return self.session.get_data(self._mkurl(cmd, *args), should_parse=daap_data)

    yield from self._assure_logged_in()
    return (yield from self._do(_get_request, is_daap=daap_data))
# Buggy code
def _get_request(url):
    return self.session.get_data(url, should_parse=daap_data)


# Traceback (pyatv.exceptions.AuthenticationError)
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/Users/postlund/git/home-assistant/homeassistant/helpers/entity.py", line 200, in async_update_ha_state
yield from self.async_update()
File "/Users/postlund/git/home-assistant/homeassistant/components/media_player/apple_tv.py", line 100, in async_update
playing = yield from self._atv.metadata.playing()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/internal/apple_tv.py", line 225, in playing
playstatus = yield from self.apple_tv.playstatus()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 128, in get
is_daap=daap_data))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 151, in _do
action, url, False, is_login=is_login, is_daap=is_daap))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 154, in _do
'failed to login: ' + str(status))
pyatv.exceptions.AuthenticationError: failed to login: 403

# Fixed code
def _get_request():
    return self.session.get_data(self._mkurl(cmd, *args), should_parse=daap_data)
# Buggy code
def post(self, cmd, data=None, **args):
    """Perform DAAP POST command with optional data."""

    def _post_request(url):
        return self.session.post_data(url, data=data)

    yield from self._assure_logged_in()
    return (yield from self._do(_post_request, self._mkurl(cmd, *args)))


# Traceback (pyatv.exceptions.AuthenticationError)
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/Users/postlund/git/home-assistant/homeassistant/helpers/entity.py", line 200, in async_update_ha_state
yield from self.async_update()
File "/Users/postlund/git/home-assistant/homeassistant/components/media_player/apple_tv.py", line 100, in async_update
playing = yield from self._atv.metadata.playing()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/internal/apple_tv.py", line 225, in playing
playstatus = yield from self.apple_tv.playstatus()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 128, in get
is_daap=daap_data))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 151, in _do
action, url, False, is_login=is_login, is_daap=is_daap))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 154, in _do
'failed to login: ' + str(status))
pyatv.exceptions.AuthenticationError: failed to login: 403

# Fixed code
def post(self, cmd, data=None, **args):
    """Perform DAAP POST command with optional data."""

    def _post_request():
        return self.session.post_data(self._mkurl(cmd, *args), data=data)

    yield from self._assure_logged_in()
    return (yield from self._do(_post_request))
# Buggy code
def _post_request(url):
    return self.session.post_data(url, data=data)


# Traceback (pyatv.exceptions.AuthenticationError)
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/Users/postlund/git/home-assistant/homeassistant/helpers/entity.py", line 200, in async_update_ha_state
yield from self.async_update()
File "/Users/postlund/git/home-assistant/homeassistant/components/media_player/apple_tv.py", line 100, in async_update
playing = yield from self._atv.metadata.playing()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/internal/apple_tv.py", line 225, in playing
playstatus = yield from self.apple_tv.playstatus()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 128, in get
is_daap=daap_data))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 151, in _do
action, url, False, is_login=is_login, is_daap=is_daap))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 154, in _do
'failed to login: ' + str(status))
pyatv.exceptions.AuthenticationError: failed to login: 403

# Fixed code
def _post_request():
    return self.session.post_data(self._mkurl(cmd, *args), data=data)
# Buggy code
def _do(self, action, url, retry=True, is_login=False, is_daap=True):
    resp, status = yield from action(url)
    self._log_response(str(action.__name__) + ": %s", resp, is_daap)
    if status >= 200 and status < 300:
        return resp

    # Retry once if we got a bad response, otherwise bail out
    if retry:
        return (
            yield from self._do(action, url, False, is_login=is_login, is_daap=is_daap)
        )
    else:
        raise exceptions.AuthenticationError("failed to login: " + str(status))


# Traceback (pyatv.exceptions.AuthenticationError)
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/Users/postlund/git/home-assistant/homeassistant/helpers/entity.py", line 200, in async_update_ha_state
yield from self.async_update()
File "/Users/postlund/git/home-assistant/homeassistant/components/media_player/apple_tv.py", line 100, in async_update
playing = yield from self._atv.metadata.playing()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/internal/apple_tv.py", line 225, in playing
playstatus = yield from self.apple_tv.playstatus()
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 128, in get
is_daap=daap_data))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 151, in _do
action, url, False, is_login=is_login, is_daap=is_daap))
File "/Users/postlund/git/home-assistant/virtualenv/lib/python3.5/site-packages/pyatv/daap.py", line 154, in _do
'failed to login: ' + str(status))
pyatv.exceptions.AuthenticationError: failed to login: 403

# Fixed code
def _do(self, action, retry=True, is_login=False, is_daap=True):
    resp, status = yield from action()
    self._log_response(str(action.__name__) + ": %s", resp, is_daap)
    if status >= 200 and status < 300:
        return resp

    # When a 403 is received we are likely logged out, so a new
    # login must be performed to get a new session id
    if status == 403:
        _LOGGER.info("implicitly logged out, logging in again")
        yield from self.login()

    # Retry once if we got a bad response, otherwise bail out
    if retry:
        return (yield from self._do(action, False, is_login=is_login, is_daap=is_daap))
    else:
        raise exceptions.AuthenticationError("failed to login: " + str(status))
# Buggy code
def __init__(self, lb, ub, keep_feasible=False):
    self.lb = lb
    self.ub = ub
    self.keep_feasible = keep_feasible


# Traceback (TypeError)
Traceback (most recent call last):
File "C:/Users/DEK328/AppData/Roaming/JetBrains/PyCharm2020.3/scratches/bug_scipy.py", line 17, in <module>
minimize(f, x0=np.array([0,0]), method='Powell', bounds=bounds)
File "C:\Users\DEK328\Anaconda3\envs\vibration\lib\site-packages\scipy\optimize\_minimize.py", line 608, in minimize
return _minimize_powell(fun, x0, args, callback, bounds, **options)
File "C:\Users\DEK328\Anaconda3\envs\vibration\lib\site-packages\scipy\optimize\optimize.py", line 2932, in _minimize_powell
fval, x, direc1 = _linesearch_powell(func, x, direc1,
File "C:\Users\DEK328\Anaconda3\envs\vibration\lib\site-packages\scipy\optimize\optimize.py", line 2667, in _linesearch_powell
bound = _line_for_search(p, xi, lower_bound, upper_bound)
File "C:\Users\DEK328\Anaconda3\envs\vibration\lib\site-packages\scipy\optimize\optimize.py", line 2610, in _line_for_search
lower_bound, upper_bound = lower_bound[nonzero], upper_bound[nonzero]
TypeError: only integer scalar arrays can be converted to a scalar index

# Fixed code
def __init__(self, lb, ub, keep_feasible=False):
    self.lb = np.asarray(lb)
    self.ub = np.asarray(ub)
    self.keep_feasible = keep_feasible
# Buggy code
def _good_shape(x, shape, axes):
    """Ensure that shape argument is valid for scipy.fftpack

    scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
    """
    if shape and not axes:
        shape = _helper._iterable_of_int(shape, "shape")
        if len(shape) != np.ndim(x):
            raise ValueError(
                "when given, axes and shape arguments have to be of the same length"
            )
    return shape


# Traceback (ValueError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Python38\lib\site-packages\scipy\fftpack\basic.py", line 384, in fft2
return fftn(x,shape,axes,overwrite_x)
File "C:\Program Files\Python38\lib\site-packages\scipy\fftpack\basic.py", line 336, in fftn
shape = _good_shape(x, shape, axes)
File "C:\Program Files\Python38\lib\site-packages\scipy\fftpack\helper.py", line 106, in _good_shape
if shape and not axes:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

# Fixed code
def _good_shape(x, shape, axes):
    """Ensure that shape argument is valid for scipy.fftpack

    scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
    """
    if shape is not None and axes is None:
        shape = _helper._iterable_of_int(shape, "shape")
        if len(shape) != np.ndim(x):
            raise ValueError(
                "when given, axes and shape arguments have to be of the same length"
            )
    return shape
# Buggy code
def compute_md5(idirs):
    released = paver.path.path(idirs).listdir()
    checksums = []
    for fn in sorted(released):
        with open(fn, "rb") as f:
            m = md5(f.read())
        checksums.append("%s  %s" % (m.hexdigest(), os.path.basename(f)))

    return checksums


# Traceback (TypeError)
Traceback (most recent call last):
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 201, in _run_task
return do_task()
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 198, in do_task
return func(**kw)
File "pavement.py", line 199, in release
write_release_and_log()
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 333, in __call__
retval = environment._run_task(self.name, self.needs, self.func)
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 219, in _run_task
return do_task()
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 198, in do_task
return func(**kw)
File "pavement.py", line 287, in write_release_and_log
write_release_task(options, os.path.join(options.installers.releasedir, 'README'))
File "pavement.py", line 247, in write_release_task
ftarget.writelines(['%s\n' % c for c in compute_md5(idirs)])
File "pavement.py", line 212, in compute_md5
checksums.append('%s  %s' % (m.hexdigest(), os.path.basename(f)))
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/posixpath.py", line 142, in basename
p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

# Fixed code
def compute_md5(idirs):
    released = paver.path.path(idirs).listdir()
    checksums = []
    for fn in sorted(released):
        with open(fn, "rb") as f:
            m = md5(f.read())
        checksums.append("%s  %s" % (m.hexdigest(), os.path.basename(fn)))

    return checksums
# Buggy code
def compute_sha256(idirs):
    # better checksum so gpg signed README.txt containing the sums can be used
    # to verify the binaries instead of signing all binaries
    released = paver.path.path(idirs).listdir()
    checksums = []
    for fn in sorted(released):
        with open(fn, "rb") as f:
            m = sha256(f.read())
        checksums.append("%s  %s" % (m.hexdigest(), os.path.basename(f)))

    return checksums


# Traceback (TypeError)
Traceback (most recent call last):
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 201, in _run_task
return do_task()
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 198, in do_task
return func(**kw)
File "pavement.py", line 199, in release
write_release_and_log()
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 333, in __call__
retval = environment._run_task(self.name, self.needs, self.func)
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 219, in _run_task
return do_task()
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/site-packages/paver/tasks.py", line 198, in do_task
return func(**kw)
File "pavement.py", line 287, in write_release_and_log
write_release_task(options, os.path.join(options.installers.releasedir, 'README'))
File "pavement.py", line 247, in write_release_task
ftarget.writelines(['%s\n' % c for c in compute_md5(idirs)])
File "pavement.py", line 212, in compute_md5
checksums.append('%s  %s' % (m.hexdigest(), os.path.basename(f)))
File "/mnt/c/Users/treddy/venv_py38/lib/python3.8/posixpath.py", line 142, in basename
p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

# Fixed code
def compute_sha256(idirs):
    # better checksum so gpg signed README.txt containing the sums can be used
    # to verify the binaries instead of signing all binaries
    released = paver.path.path(idirs).listdir()
    checksums = []
    for fn in sorted(released):
        with open(fn, "rb") as f:
            m = sha256(f.read())
        checksums.append("%s  %s" % (m.hexdigest(), os.path.basename(fn)))

    return checksums
# Buggy code
def _estimate_error_norm(self, K, h, scale):
    err5 = np.dot(K.T, self.E5) / scale
    err3 = np.dot(K.T, self.E3) / scale
    err5_norm_2 = np.sum(err5**2)
    err3_norm_2 = np.sum(err3**2)
    if err5_norm_2 == 0 and err3_norm_2 == 0:
        return 0
    denom = err5_norm_2 + 0.01 * err3_norm_2
    return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))


# Traceback (TypeError)
TypeError                                 Traceback (most recent call last)
<ipython-input-123-accff485a0c9> in <module>
13 dop.step()
14 print(dop.t)
---> 15 dop.step()

~/miniconda3/lib/python3.7/site-packages/scipy/integrate/_ivp/base.py in step(self)
180         else:
181             t = self.t
--> 182             success, message = self._step_impl()
183
184             if not success:

~/miniconda3/lib/python3.7/site-packages/scipy/integrate/_ivp/rk.py in _step_impl(self)
118         atol = self.atol
119
--> 120         min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
121
122         if self.h_abs > max_step:

TypeError: ufunc 'nextafter' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def _estimate_error_norm(self, K, h, scale):
    err5 = np.dot(K.T, self.E5) / scale
    err3 = np.dot(K.T, self.E3) / scale
    err5_norm_2 = np.linalg.norm(err5) ** 2
    err3_norm_2 = np.linalg.norm(err3) ** 2
    if err5_norm_2 == 0 and err3_norm_2 == 0:
        return 0.0
    denom = err5_norm_2 + 0.01 * err3_norm_2
    return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))
# Buggy code
def _get_umf_family(A):
    """Get umfpack family string given the sparse matrix dtype."""
    _families = {
        (np.float64, np.int32): "di",
        (np.complex128, np.int32): "zi",
        (np.float64, np.int64): "dl",
        (np.complex128, np.int64): "zl",
    }

    f_type = np.sctypeDict[A.dtype.name]
    i_type = np.sctypeDict[A.indices.dtype.name]

    try:
        family = _families[(f_type, i_type)]

    except KeyError:
        msg = (
            "only float64 or complex128 matrices with int32 or int64"
            " indices are supported! (got: matrix: %s, indices: %s)" % (f_type, i_type)
        )
        raise ValueError(msg)

    return family


# Traceback (RuntimeError)
Traceback (most recent call last):
File "issue.py", line 11, in <module>
x = sp.linalg.spsolve(A, b)
File "/somepath/python3.6/site-packages/scipy/sparse/linalg/dsolve/linsolve.py", line 176, in spsolve
autoTranspose=True)
File "/somepath/python3.6/site-packages/scikits/umfpack/umfpack.py", line 756, in linsolve
self.numeric(mtx)
File "/somepath/python3.6/site-packages/scikits/umfpack/umfpack.py", line 577, in numeric
umfStatus[status]))
RuntimeError: <function umfpack_di_numeric at 0x7fef7224f158> failed with UMFPACK_ERROR_out_of_memory

# Fixed code
def _get_umf_family(A):
    """Get umfpack family string given the sparse matrix dtype."""
    _families = {
        (np.float64, np.int32): "di",
        (np.complex128, np.int32): "zi",
        (np.float64, np.int64): "dl",
        (np.complex128, np.int64): "zl",
    }

    f_type = np.sctypeDict[A.dtype.name]
    i_type = np.sctypeDict[A.indices.dtype.name]

    try:
        family = _families[(f_type, i_type)]

    except KeyError:
        msg = (
            "only float64 or complex128 matrices with int32 or int64"
            " indices are supported! (got: matrix: %s, indices: %s)" % (f_type, i_type)
        )
        raise ValueError(msg)

    # See gh-8278. Considered converting only if
    # A.shape[0]*A.shape[1] > np.iinfo(np.int32).max,
    # but that didn't always fix the issue.
    family = family[0] + "l"
    A_new = copy.copy(A)
    A_new.indptr = np.array(A.indptr, copy=False, dtype=np.int64)
    A_new.indices = np.array(A.indices, copy=False, dtype=np.int64)

    return family, A_new
# Buggy code
def _skip_unknown_chunk(fid, is_big_endian):
    if is_big_endian:
        fmt = ">I"
    else:
        fmt = "<I"

    data = fid.read(4)
    # call unpack() and seek() only if we have really read data from file
    # otherwise empty read at the end of the file would trigger
    # unnecessary exception at unpack() call
    # in case data equals somehow to 0, there is no need for seek() anyway
    if data:
        size = struct.unpack(fmt, data)[0]
        fid.seek(size, 1)


# Traceback (ValueError)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "E:\alon_emanuel_drive\School\Year2\Semester2\67690_AI_as_a_Tool\venvs\prosody-venv\lib\site-packages\scipy\io\wavfile.py", line 248, in read
raise ValueError("Incomplete wav chunk.")
ValueError: Incomplete wav chunk.

# Fixed code
def _skip_unknown_chunk(fid, is_big_endian):
    if is_big_endian:
        fmt = ">I"
    else:
        fmt = "<I"

    data = fid.read(4)
    # call unpack() and seek() only if we have really read data from file
    # otherwise empty read at the end of the file would trigger
    # unnecessary exception at unpack() call
    # in case data equals somehow to 0, there is no need for seek() anyway
    if data:
        size = struct.unpack(fmt, data)[0]
        fid.seek(size, 1)
        _handle_pad_byte(fid, size)
# Buggy code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        raise ValueError("k exceeds matrix dimensions")
    R, C = self.blocksize
    y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), dtype=upcast(self.dtype))
    _sparsetools.bsr_diagonal(
        k, rows // R, cols // C, R, C, self.indptr, self.indices, np.ravel(self.data), y
    )
    return y


# Traceback (ValueError)
(0,)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-106e34b7d64c> in <module>
2 print(np.diag(m.todense()).shape)
3
----> 4 m.diagonal()

~/.pyenv/versions/3.6.9/lib/python3.6/site-packages/scipy/sparse/compressed.py in diagonal(self, k)
531         rows, cols = self.shape
532         if k <= -rows or k >= cols:
--> 533             raise ValueError("k exceeds matrix dimensions")
534         fn = getattr(_sparsetools, self.format + "_diagonal")
535         y = np.empty(min(rows + min(k, 0), cols - max(k, 0)),

ValueError: k exceeds matrix dimensions

# Fixed code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        return np.empty(0, dtype=self.data.dtype)
    R, C = self.blocksize
    y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), dtype=upcast(self.dtype))
    _sparsetools.bsr_diagonal(
        k, rows // R, cols // C, R, C, self.indptr, self.indices, np.ravel(self.data), y
    )
    return y
# Buggy code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        raise ValueError("k exceeds matrix dimensions")
    fn = getattr(_sparsetools, self.format + "_diagonal")
    y = np.empty(min(rows + min(k, 0), cols - max(k, 0)), dtype=upcast(self.dtype))
    fn(k, self.shape[0], self.shape[1], self.indptr, self.indices, self.data, y)
    return y


# Traceback (ValueError)
(0,)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-106e34b7d64c> in <module>
2 print(np.diag(m.todense()).shape)
3
----> 4 m.diagonal()

~/.pyenv/versions/3.6.9/lib/python3.6/site-packages/scipy/sparse/compressed.py in diagonal(self, k)
531         rows, cols = self.shape
532         if k <= -rows or k >= cols:
--> 533             raise ValueError("k exceeds matrix dimensions")
534         fn = getattr(_sparsetools, self.format + "_diagonal")
535         y = np.empty(min(rows + min(k, 0), cols - max(k, 0)),

ValueError: k exceeds matrix dimensions

# Fixed code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        return np.empty(0, dtype=self.data.dtype)
    fn = getattr(_sparsetools, self.format + "_diagonal")
    y = np.empty(min(rows + min(k, 0), cols - max(k, 0)), dtype=upcast(self.dtype))
    fn(k, self.shape[0], self.shape[1], self.indptr, self.indices, self.data, y)
    return y
# Buggy code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        raise ValueError("k exceeds matrix dimensions")
    diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), dtype=self.dtype)
    diag_mask = (self.row + k) == self.col

    if self.has_canonical_format:
        row = self.row[diag_mask]
        data = self.data[diag_mask]
    else:
        row, _, data = self._sum_duplicates(
            self.row[diag_mask], self.col[diag_mask], self.data[diag_mask]
        )
    diag[row + min(k, 0)] = data

    return diag


# Traceback (ValueError)
(0,)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-106e34b7d64c> in <module>
2 print(np.diag(m.todense()).shape)
3
----> 4 m.diagonal()

~/.pyenv/versions/3.6.9/lib/python3.6/site-packages/scipy/sparse/compressed.py in diagonal(self, k)
531         rows, cols = self.shape
532         if k <= -rows or k >= cols:
--> 533             raise ValueError("k exceeds matrix dimensions")
534         fn = getattr(_sparsetools, self.format + "_diagonal")
535         y = np.empty(min(rows + min(k, 0), cols - max(k, 0)),

ValueError: k exceeds matrix dimensions

# Fixed code
def diagonal(self, k=0):
    rows, cols = self.shape
    if k <= -rows or k >= cols:
        return np.empty(0, dtype=self.data.dtype)
    diag = np.zeros(min(rows + min(k, 0), cols - max(k, 0)), dtype=self.dtype)
    diag_mask = (self.row + k) == self.col

    if self.has_canonical_format:
        row = self.row[diag_mask]
        data = self.data[diag_mask]
    else:
        row, _, data = self._sum_duplicates(
            self.row[diag_mask], self.col[diag_mask], self.data[diag_mask]
        )
    diag[row + min(k, 0)] = data

    return diag