gurudesh/pytracebugs huggingface dataset:
# Buggy code
async def fetch_id(self):
    params = {"key": self._token, "forUsername": self.name, "part": "id"}
    async with aiohttp.ClientSession() as session:
        async with session.get(YOUTUBE_CHANNELS_ENDPOINT, params=params) as r:
            data = await r.json()

    if (
        "error" in data
        and data["error"]["code"] == 400
        and data["error"]["errors"][0]["reason"] == "keyInvalid"
    ):
        raise InvalidYoutubeCredentials()
    elif "items" in data and len(data["items"]) == 0:
        raise StreamNotFound()
    elif "items" in data:
        return data["items"][0]["id"]
    raise APIError()


# Traceback (AttributeError)
Exception during loading of cog
Traceback (most recent call last):
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\core\core_commands.py", line 87, in _load
await bot.load_extension(spec)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\core\bot.py", line 222, in load_extension
await lib.setup(self)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\__init__.py", line 6, in setup
await cog.initialize()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\streams.py", line 71, in initialize
self.streams = await self.load_streams()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\streams.py", line 618, in load_streams
return [x for x in streams if not (x.name.lower() in seen or seen_add(x.name.lower()))]
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\redbot\cogs\streams\streams.py", line 618, in <listcomp>
return [x for x in streams if not (x.name.lower() in seen or seen_add(x.name.lower()))]
AttributeError: 'NoneType' object has no attribute 'lower'

# Fixed code
async def fetch_id(self):
    return await self._fetch_channel_resource("id")
# Buggy code
async def has_java(loop) -> Tuple[bool, Optional[_JavaVersion]]:
    java_available = shutil.which("java") is not None
    if not java_available:
        return False, None

    version = await get_java_version(loop)
    return version >= (1, 8), version


# Traceback (ValueError)
[20/08/2018 02:50] ERROR core_commands _load 89: Package loading failed
Traceback (most recent call last):
File "/home/ruben/.local/lib/python3.6/site-packages/redbot/core/core_commands.py", line 87, in _load
await bot.load_extension(spec)
File "/home/ruben/.local/lib/python3.6/site-packages/redbot/core/bot.py", line 226, in load_extension
await lib.setup(self)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/__init__.py", line 53, in setup
await start_lavalink_server(bot.loop)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/manager.py", line 68, in start_lavalink_server
java_available, java_version = await has_java(loop)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/manager.py", line 47, in has_java
version = await get_java_version(loop)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/manager.py", line 63, in get_java_version
major, minor = version_string.split(".")[:2]
ValueError: not enough values to unpack (expected 2, got 1)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f8b24284ef0>

# Fixed code
async def has_java(loop) -> Tuple[bool, Optional[_JavaVersion]]:
    java_available = shutil.which("java") is not None
    if not java_available:
        return False, None

    version = await get_java_version(loop)
    return (2, 0) > version >= (1, 8) or version >= (8, 0), version
# Buggy code
async def get_java_version(loop) -> _JavaVersion:
    """
    This assumes we've already checked that java exists.
    """
    proc = Popen(
        shlex.split("java -version", posix=os.name == "posix"), stdout=PIPE, stderr=PIPE
    )
    _, err = proc.communicate()

    version_info = str(err, encoding="utf-8")

    version_line = version_info.split("\n")[0]
    version_start = version_line.find('"')
    version_string = version_line[version_start + 1 : -1]
    major, minor = version_string.split(".")[:2]
    return int(major), int(minor)


# Traceback (ValueError)
[20/08/2018 02:50] ERROR core_commands _load 89: Package loading failed
Traceback (most recent call last):
File "/home/ruben/.local/lib/python3.6/site-packages/redbot/core/core_commands.py", line 87, in _load
await bot.load_extension(spec)
File "/home/ruben/.local/lib/python3.6/site-packages/redbot/core/bot.py", line 226, in load_extension
await lib.setup(self)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/__init__.py", line 53, in setup
await start_lavalink_server(bot.loop)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/manager.py", line 68, in start_lavalink_server
java_available, java_version = await has_java(loop)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/manager.py", line 47, in has_java
version = await get_java_version(loop)
File "/home/ruben/Downloads/Red-DiscordBot-3-develop/redbot/cogs/audio/manager.py", line 63, in get_java_version
major, minor = version_string.split(".")[:2]
ValueError: not enough values to unpack (expected 2, got 1)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f8b24284ef0>

# Fixed code
async def get_java_version(loop) -> _JavaVersion:
    """
    This assumes we've already checked that java exists.
    """
    _proc: asyncio.subprocess.Process = await asyncio.create_subprocess_exec(
        "java",
        "-version",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        loop=loop,
    )
    # java -version outputs to stderr
    _, err = await _proc.communicate()

    version_info: str = err.decode("utf-8")
    # We expect the output to look something like:
    #     $ java -version
    #     ...
    #     ... version "MAJOR.MINOR.PATCH[_BUILD]" ...
    #     ...
    # We only care about the major and minor parts though.
    version_line_re = re.compile(
        r'version "(?P<major>\d+).(?P<minor>\d+).\d+(?:_\d+)?"'
    )

    lines = version_info.splitlines()
    for line in lines:
        match = version_line_re.search(line)
        if match:
            return int(match["major"]), int(match["minor"])

    raise RuntimeError(
        "The output of `java -version` was unexpected. Please report this issue on Red's "
        "issue tracker."
    )
# Buggy code
async def load_streams(self):
    streams = []

    for raw_stream in await self.db.streams():
        _class = getattr(StreamClasses, raw_stream["type"], None)
        if not _class:
            continue
        raw_msg_cache = raw_stream["messages"]
        raw_stream["_messages_cache"] = []
        for raw_msg in raw_msg_cache:
            chn = self.bot.get_channel(raw_msg["channel"])
            msg = await chn.get_message(raw_msg["message"])
            raw_stream["_messages_cache"].append(msg)
        token = await self.db.tokens.get_raw(_class.__name__)
        streams.append(_class(token=token, **raw_stream))

    # issue 1191 extended resolution: Remove this after suitable period
    # Fast dedupe below
    seen = set()
    seen_add = seen.add
    return [
        x for x in streams if not (x.name.lower() in seen or seen_add(x.name.lower()))
    ]


# Traceback (KeyError)
Exception during loading of cog
Traceback (most recent call last):
File "/home/jjay/rewrite/lib/python3.6/site-packages/redbot/core/core_commands.py", line 87, in _load
await bot.load_extension(spec)
File "/home/jjay/rewrite/lib/python3.6/site-packages/redbot/core/bot.py", line 222, in load_extension
await lib.setup(self)
File "/home/jjay/rewrite/lib/python3.6/site-packages/redbot/cogs/streams/__init__.py", line 6, in setup
await cog.initialize()
File "/home/jjay/rewrite/lib/python3.6/site-packages/redbot/cogs/streams/streams.py", line 71, in initialize
self.streams = await self.load_streams()
File "/home/jjay/rewrite/lib/python3.6/site-packages/redbot/cogs/streams/streams.py", line 611, in load_streams
token = await self.db.tokens.get_raw(_class.__name__)
File "/home/jjay/rewrite/lib/python3.6/site-packages/redbot/core/config.py", line 342, in get_raw
return await self.driver.get(*self.identifiers, *path)
File "/home/jjay/rewrite/lib/python3.6/site-packages/redbot/core/drivers/red_json.py", line 100, in get
partial = partial[i]
KeyError: 'MixerStream'

# Fixed code
async def load_streams(self):
    streams = []

    for raw_stream in await self.db.streams():
        _class = getattr(StreamClasses, raw_stream["type"], None)
        if not _class:
            continue
        raw_msg_cache = raw_stream["messages"]
        raw_stream["_messages_cache"] = []
        for raw_msg in raw_msg_cache:
            chn = self.bot.get_channel(raw_msg["channel"])
            msg = await chn.get_message(raw_msg["message"])
            raw_stream["_messages_cache"].append(msg)
        token = await self.db.tokens.get_raw(_class.__name__, default=None)
        if token is not None:
            raw_stream["token"] = token
        streams.append(_class(**raw_stream))

    return streams
# Buggy code
async def maybe_download_lavalink(loop, cog):
    jar_exists = LAVALINK_JAR_FILE.exists()
    current_build = redbot.core.VersionInfo(*await cog.config.current_build())

    session = ClientSession(loop=loop)

    if not jar_exists or current_build < redbot.core.version_info:
        LAVALINK_DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True)
        await download_lavalink(session)
        await cog.config.current_build.set(redbot.core.version_info.to_json())

    session.close()

    shutil.copyfile(str(BUNDLED_APP_YML_FILE), str(APP_YML_FILE))


# Traceback (TypeError)
[24/05/2018 06:25] ERROR core_commands load 363: Package loading failed
Traceback (most recent call last):
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/core_commands.py", line 361, in load
await ctx.bot.load_extension(spec)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/bot.py", line 227, in load_extension
await lib.setup(self)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/__init__.py", line 53, in setup
await start_lavalink_server(bot.loop)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/manager.py", line 66, in start_lavalink_server
java_available, java_version = await has_java(loop)
TypeError: 'bool' object is not iterable

# Fixed code
async def maybe_download_lavalink(loop, cog):
    jar_exists = LAVALINK_JAR_FILE.exists()
    current_build = redbot.core.VersionInfo(*await cog.config.current_build())

    if not jar_exists or current_build < redbot.core.version_info:
        log.info("Downloading Lavalink.jar")
        LAVALINK_DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True)
        async with ClientSession(loop=loop) as session:
            await download_lavalink(session)
        await cog.config.current_build.set(redbot.core.version_info.to_json())

    shutil.copyfile(str(BUNDLED_APP_YML_FILE), str(APP_YML_FILE))
# Buggy code
async def has_java(loop):
    java_available = shutil.which("java") is not None
    if not java_available:
        return False

    version = await get_java_version(loop)
    return version >= (1, 8), version


# Traceback (TypeError)
[24/05/2018 06:25] ERROR core_commands load 363: Package loading failed
Traceback (most recent call last):
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/core_commands.py", line 361, in load
await ctx.bot.load_extension(spec)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/bot.py", line 227, in load_extension
await lib.setup(self)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/__init__.py", line 53, in setup
await start_lavalink_server(bot.loop)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/manager.py", line 66, in start_lavalink_server
java_available, java_version = await has_java(loop)
TypeError: 'bool' object is not iterable

# Fixed code
async def has_java(loop) -> Tuple[bool, Optional[_JavaVersion]]:
    java_available = shutil.which("java") is not None
    if not java_available:
        return False, None

    version = await get_java_version(loop)
    return version >= (1, 8), version
# Buggy code
async def get_java_version(loop):
    """
    This assumes we've already checked that java exists.
    """
    proc = Popen(
        shlex.split("java -version", posix=os.name == "posix"), stdout=PIPE, stderr=PIPE
    )
    _, err = proc.communicate()

    version_info = str(err, encoding="utf-8")

    version_line = version_info.split("\n")[0]
    version_start = version_line.find('"')
    version_string = version_line[version_start + 1 : -1]
    major, minor = version_string.split(".")[:2]
    return int(major), int(minor)


# Traceback (TypeError)
[24/05/2018 06:25] ERROR core_commands load 363: Package loading failed
Traceback (most recent call last):
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/core_commands.py", line 361, in load
await ctx.bot.load_extension(spec)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/bot.py", line 227, in load_extension
await lib.setup(self)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/__init__.py", line 53, in setup
await start_lavalink_server(bot.loop)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/manager.py", line 66, in start_lavalink_server
java_available, java_version = await has_java(loop)
TypeError: 'bool' object is not iterable

# Fixed code
async def get_java_version(loop) -> _JavaVersion:
    """
    This assumes we've already checked that java exists.
    """
    proc = Popen(
        shlex.split("java -version", posix=os.name == "posix"), stdout=PIPE, stderr=PIPE
    )
    _, err = proc.communicate()

    version_info = str(err, encoding="utf-8")

    version_line = version_info.split("\n")[0]
    version_start = version_line.find('"')
    version_string = version_line[version_start + 1 : -1]
    major, minor = version_string.split(".")[:2]
    return int(major), int(minor)
# Buggy code
async def load(self, ctx, *, cog_name: str):
    """Loads packages"""

    cog_names = [c.strip() for c in cog_name.split(" ")]
    loaded, failed, not_found = await self._load(cog_names)

    if loaded:
        fmt = "Loaded {packs}"
        formed = self._get_package_strings(loaded, fmt)
        await ctx.send(formed)

    if failed:
        fmt = (
            "Failed to load package{plural} {packs}. Check your console or "
            "logs for details."
        )
        formed = self.get_package_strings(failed, fmt)
        await ctx.send(formed)

    if not_found:
        fmt = "The package{plural} {packs} {other} not found in any cog path."
        formed = self._get_package_strings(not_found, fmt, ("was", "were"))
        await ctx.send(formed)


# Traceback (TypeError)
[24/05/2018 06:25] ERROR core_commands load 363: Package loading failed
Traceback (most recent call last):
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/core_commands.py", line 361, in load
await ctx.bot.load_extension(spec)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/bot.py", line 227, in load_extension
await lib.setup(self)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/__init__.py", line 53, in setup
await start_lavalink_server(bot.loop)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/manager.py", line 66, in start_lavalink_server
java_available, java_version = await has_java(loop)
TypeError: 'bool' object is not iterable

# Fixed code
async def load(self, ctx, *, cog_name: str):
    """Loads packages"""

    cog_names = [c.strip() for c in cog_name.split(" ")]
    async with ctx.typing():
        loaded, failed, not_found = await self._load(cog_names)

    if loaded:
        fmt = "Loaded {packs}"
        formed = self._get_package_strings(loaded, fmt)
        await ctx.send(formed)

    if failed:
        fmt = (
            "Failed to load package{plural} {packs}. Check your console or "
            "logs for details."
        )
        formed = self.get_package_strings(failed, fmt)
        await ctx.send(formed)

    if not_found:
        fmt = "The package{plural} {packs} {other} not found in any cog path."
        formed = self._get_package_strings(not_found, fmt, ("was", "were"))
        await ctx.send(formed)
# Buggy code
async def reload_(self, ctx, *, cog_name: str):
    """Reloads packages"""

    cog_names = [c.strip() for c in cog_name.split(" ")]

    loaded, failed, not_found = await self._reload(cog_names)

    if loaded:
        fmt = "Package{plural} {packs} {other} reloaded."
        formed = self._get_package_strings(loaded, fmt, ("was", "were"))
        await ctx.send(formed)

    if failed:
        fmt = "Failed to reload package{plural} {packs}. Check your logs for details"
        formed = self._get_package_strings(failed, fmt)
        await ctx.send(formed)

    if not_found:
        fmt = "The package{plural} {packs} {other} not found in any cog path."
        formed = self._get_package_strings(not_found, fmt, ("was", "were"))
        await ctx.send(formed)


# Traceback (TypeError)
[24/05/2018 06:25] ERROR core_commands load 363: Package loading failed
Traceback (most recent call last):
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/core_commands.py", line 361, in load
await ctx.bot.load_extension(spec)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/core/bot.py", line 227, in load_extension
await lib.setup(self)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/__init__.py", line 53, in setup
await start_lavalink_server(bot.loop)
File "/home/tobyh/.pyenv/versions/3.6.5/envs/red/lib/python3.6/site-packages/redbot/cogs/audio/manager.py", line 66, in start_lavalink_server
java_available, java_version = await has_java(loop)
TypeError: 'bool' object is not iterable

# Fixed code
async def reload_(self, ctx, *, cog_name: str):
    """Reloads packages"""

    cog_names = [c.strip() for c in cog_name.split(" ")]
    async with ctx.typing():
        loaded, failed, not_found = await self._reload(cog_names)

    if loaded:
        fmt = "Package{plural} {packs} {other} reloaded."
        formed = self._get_package_strings(loaded, fmt, ("was", "were"))
        await ctx.send(formed)

    if failed:
        fmt = "Failed to reload package{plural} {packs}. Check your logs for details"
        formed = self._get_package_strings(failed, fmt)
        await ctx.send(formed)

    if not_found:
        fmt = "The package{plural} {packs} {other} not found in any cog path."
        formed = self._get_package_strings(not_found, fmt, ("was", "were"))
        await ctx.send(formed)
# Buggy code
async def remove_instance(selected, instance_data):
    instance_list = load_existing_config()
    if instance_data["STORAGE_TYPE"] == "MongoDB":
        m = Mongo("Core", **instance_data["STORAGE_DETAILS"])
        db = m.db
        collections = await db.collection_names(include_system_collections=False)
        for name in collections:
            collection = await db.get_collection(name)
            await collection.drop()
    else:
        pth = Path(instance_data["DATA_PATH"])
        safe_delete(pth)
    save_config(selected, {}, remove=True)
    print("The instance {} has been removed\n".format(selected))


# Traceback (NameError)
pi@raspberrypi:~ $ export PATH=.local/bin/
pi@raspberrypi:~ $ redbot-launcher
==========================
Red Discord Bot - Launcher
==========================

1. Run Red w/ autorestart in case of issues
2. Run Red
3. Update Red
4. Update Red (development version)
5. Create Instance
6. Remove Instance
7. Debug information (use this if having issues with the launcher or bot)
0. Exit
6
You have chosen to remove an instance. The following is a list of instances that currently exist:

Oxibot

Red

Please select one of the above by entering its name
Red
Would you like to make a backup of the data for this instance? (y/n)n
Removing the instance...
Traceback (most recent call last):
File ".local/bin/redbot-launcher", line 11, in <module>
sys.exit(main())
File "/home/pi/.local/lib/python3.6/site-packages/redbot/launcher.py", line 358, in main
main_menu()
File "/home/pi/.local/lib/python3.6/site-packages/redbot/launcher.py", line 323, in main_menu
asyncio.get_event_loop().run_until_complete(remove_instance())
File "/usr/local/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
return future.result()
File "/home/pi/.local/lib/python3.6/site-packages/redbot/setup.py", line 379, in remove_instance
m = Mongo("Core", **instance_data["STORAGE_DETAILS"])
NameError: name 'Mongo' is not defined

# Fixed code
async def remove_instance(selected, instance_data):
    if instance_data["STORAGE_TYPE"] == "MongoDB":
        from redbot.core.drivers.red_mongo import Mongo

        m = Mongo("Core", **instance_data["STORAGE_DETAILS"])
        db = m.db
        collections = await db.collection_names(include_system_collections=False)
        for name in collections:
            collection = await db.get_collection(name)
            await collection.drop()
    else:
        pth = Path(instance_data["DATA_PATH"])
        safe_delete(pth)
    save_config(selected, {}, remove=True)
    print("The instance {} has been removed\n".format(selected))
# Buggy code
async def imgur_search(self, ctx, *, term: str):
    """Searches Imgur for the specified term and returns up to 3 results"""
    url = self.imgur_base_url + "time/all/0"
    params = {"q": term}
    headers = {
        "Authorization": "Client-ID {}".format(await self.settings.imgur_client_id())
    }
    async with self.session.get(url, headers=headers, data=params) as search_get:
        data = await search_get.json()

    if data["success"]:
        results = data["data"]
        if not results:
            await ctx.send(_("Your search returned no results"))
            return
        shuffle(results)
        msg = _("Search results...\n")
        for r in results[:3]:
            msg += r["gifv"] if "gifv" in r else r["link"]
            msg += "\n"
        await ctx.send(msg)
    else:
        await ctx.send(
            _("Something went wrong. Error code is {}").format(data["status"])
        )


# Traceback (aiohttp.client_exceptions.ClientResponseError)
Exception in command 'imgur search'
Traceback (most recent call last):
File "/home/palm/redv3/lib/python3.5/site-packages/discord/ext/commands/core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "/home/palm/redv3/lib/python3.5/site-packages/redbot/cogs/image/image.py", line 47, in imgur_search
data = await search_get.json()
File "/home/palm/redv3/lib/python3.5/site-packages/aiohttp/client_reqrep.py", line 730, in json
headers=self.headers)
aiohttp.client_exceptions.ClientResponseError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html; charset=utf-8'

# Fixed code
async def imgur_search(self, ctx, *, term: str):
    """Searches Imgur for the specified term and returns up to 3 results"""
    url = self.imgur_base_url + "gallery/search/time/all/0"
    params = {"q": term}
    imgur_client_id = await self.settings.imgur_client_id()
    if not imgur_client_id:
        await ctx.send(
            _("A client ID has not been set! Please set one with {}").format(
                "`{}imgurcreds`".format(ctx.prefix)
            )
        )
        return
    headers = {"Authorization": "Client-ID {}".format(imgur_client_id)}
    async with self.session.get(url, headers=headers, params=params) as search_get:
        data = await search_get.json()

    if data["success"]:
        results = data["data"]
        if not results:
            await ctx.send(_("Your search returned no results"))
            return
        shuffle(results)
        msg = _("Search results...\n")
        for r in results[:3]:
            msg += r["gifv"] if "gifv" in r else r["link"]
            msg += "\n"
        await ctx.send(msg)
    else:
        await ctx.send(
            _("Something went wrong. Error code is {}").format(data["status"])
        )
# Buggy code
async def imgurcreds(self, ctx, imgur_client_id: str):
    """Sets the imgur client id
    You will need an account on Imgur to get this

    You can get these by visiting https://api.imgur.com/oauth2/addclient
    and filling out the form. Enter a name for the application, select
    'Anonymous usage without user authorization' for the auth type,
    leave the app website blank, enter a valid email address, and
    enter a description. Check the box for the captcha, then click Next.
    Your client ID will be on the page that loads"""
    await self.settings.imgur_client_id.set(imgur_client_id)
    await ctx.send(_("Set the imgur client id!"))


# Traceback (aiohttp.client_exceptions.ClientResponseError)
Exception in command 'imgur search'
Traceback (most recent call last):
File "/home/palm/redv3/lib/python3.5/site-packages/discord/ext/commands/core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "/home/palm/redv3/lib/python3.5/site-packages/redbot/cogs/image/image.py", line 47, in imgur_search
data = await search_get.json()
File "/home/palm/redv3/lib/python3.5/site-packages/aiohttp/client_reqrep.py", line 730, in json
headers=self.headers)
aiohttp.client_exceptions.ClientResponseError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html; charset=utf-8'

# Fixed code
async def imgurcreds(self, ctx, imgur_client_id: str):
    """Sets the imgur client id
    You will need an account on Imgur to get this

    You can get these by visiting https://api.imgur.com/oauth2/addclient
    and filling out the form. Enter a name for the application, select
    'Anonymous usage without user authorization' for the auth type,
    set the authorization callback url to 'https://localhost'
    leave the app website blank, enter a valid email address, and
    enter a description. Check the box for the captcha, then click Next.
    Your client ID will be on the page that loads"""
    await self.settings.imgur_client_id.set(imgur_client_id)
    await ctx.send(_("Set the imgur client id!"))
# Buggy code
async def announce_channel(self, ctx, channel: discord.TextChannel = None):
    """
    Changes the channel on which the bot makes announcements.
    """
    if channel is None:
        channel = ctx.channel
    await self.conf.guild(ctx.guild).set("announce_channel", channel.id)

    await ctx.send(
        "The announcement channel has been set to {}".format(channel.mention)
    )


# Traceback (AttributeError)
Task exception was never retrieved
future: <Task finished coro=<Announcer.announcer() done, defined at c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py:50> exception=AttributeError("'Guild' object has no attribute 'default_channel'",)>
Traceback (most recent call last):
File "c:\users\endms\appdata\local\programs\python\python35\lib\asyncio\tasks.py", line 239, in _step
result = coro.send(None)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 60, in announcer
channel = await self._get_announce_channel(g)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 46, in _get_announce_channel
channel = guild.default_channel
AttributeError: 'Guild' object has no attribute 'default_channel'
Task exception was never retrieved
future: <Task finished coro=<Announcer.announcer() done, defined at c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py:50> exception=AttributeError("'Guild' object has no attribute 'default_channel'",)>
Traceback (most recent call last):
File "c:\users\endms\appdata\local\programs\python\python35\lib\asyncio\tasks.py", line 239, in _step
result = coro.send(None)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 60, in announcer
channel = await self._get_announce_channel(g)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 46, in _get_announce_channel
channel = guild.default_channel
AttributeError: 'Guild' object has no attribute 'default_channel'

# Fixed code
async def announce_channel(self, ctx, channel: discord.TextChannel = None):
    """
    Changes the channel on which the bot makes announcements.
    """
    if channel is None:
        channel = ctx.channel
    await self.conf.guild(ctx.guild).announce_channel.set(channel.id)

    await ctx.send(
        "The announcement channel has been set to {}".format(channel.mention)
    )
# Buggy code
async def _get_announce_channel(self, guild: discord.Guild) -> discord.TextChannel:
    channel_id = await self.config.guild(guild).announce_channel()
    channel = None

    if channel_id is not None:
        channel = guild.get_channel(channel_id)

    if channel is None:
        channel = guild.default_channel

    return channel


# Traceback (AttributeError)
Task exception was never retrieved
future: <Task finished coro=<Announcer.announcer() done, defined at c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py:50> exception=AttributeError("'Guild' object has no attribute 'default_channel'",)>
Traceback (most recent call last):
File "c:\users\endms\appdata\local\programs\python\python35\lib\asyncio\tasks.py", line 239, in _step
result = coro.send(None)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 60, in announcer
channel = await self._get_announce_channel(g)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 46, in _get_announce_channel
channel = guild.default_channel
AttributeError: 'Guild' object has no attribute 'default_channel'
Task exception was never retrieved
future: <Task finished coro=<Announcer.announcer() done, defined at c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py:50> exception=AttributeError("'Guild' object has no attribute 'default_channel'",)>
Traceback (most recent call last):
File "c:\users\endms\appdata\local\programs\python\python35\lib\asyncio\tasks.py", line 239, in _step
result = coro.send(None)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 60, in announcer
channel = await self._get_announce_channel(g)
File "c:\users\endms\appdata\local\programs\python\python35\lib\site-packages\redbot\cogs\admin\announcer.py", line 46, in _get_announce_channel
channel = guild.default_channel
AttributeError: 'Guild' object has no attribute 'default_channel'

# Fixed code
async def _get_announce_channel(self, guild: discord.Guild) -> discord.TextChannel:
    channel_id = await self.config.guild(guild).announce_channel()
    channel = None

    if channel_id is not None:
        channel = guild.get_channel(channel_id)

    if channel is None:
        channel = guild.system_channel

    if channel is None:
        channel = guild.text_channels[0]

    return channel
# Buggy code
async def _repo_add(self, ctx, name: RepoName, repo_url: str, branch: str = None):
    """
    Add a new repo to Downloader.

    Name can only contain characters A-z, numbers and underscore
    Branch will default to master if not specified
    """
    try:
        # noinspection PyTypeChecker
        await self._repo_manager.add_repo(name=name, url=repo_url, branch=branch)
    except ExistingGitRepo:
        await ctx.send(_("That git repo has already been added under another name."))
    except CloningError:
        await ctx.send(_("Something went wrong during the cloning process."))
        log.exception(_("Something went wrong during the cloning process."))
    else:
        await ctx.send(_("Repo `{}` successfully added.").format(name))


# Traceback (downloader.errors.CloningError)
[31/12/2017 16:30] ERROR downloader _repo_add 218: Something went wrong during the cloning process.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/redbot/cogs/downloader/downloader.py", line 212, in _repo_add
branch=branch
File "/usr/local/lib/python3.6/site-packages/redbot/cogs/downloader/repo_manager.py", line 540, in add_repo
await r.clone()
File "/usr/local/lib/python3.6/site-packages/redbot/cogs/downloader/repo_manager.py", line 198, in clone
raise CloningError("Error when running git clone.")
downloader.errors.CloningError: Error when running git clone.

# Fixed code
async def _repo_add(self, ctx, name: str, repo_url: str, branch: str = None):
    """
    Add a new repo to Downloader.

    Name can only contain characters A-z, numbers and underscore
    Branch will default to master if not specified
    """
    try:
        # noinspection PyTypeChecker
        await self._repo_manager.add_repo(name=name, url=repo_url, branch=branch)
    except ExistingGitRepo:
        await ctx.send(_("That git repo has already been added under another name."))
    except CloningError:
        await ctx.send(_("Something went wrong during the cloning process."))
        log.exception(_("Something went wrong during the cloning process."))
    else:
        await ctx.send(_("Repo `{}` successfully added.").format(name))
# Buggy code
async def add_repo(self, url: str, name: str, branch: str = "master") -> Repo:
    """Add and clone a git repository.

    Parameters
    ----------
    url : str
        URL to the git repository.
    name : str
        Internal name of the repository.
    branch : str
        Name of the default branch to checkout into.

    Returns
    -------
    Repo
        New Repo object representing the cloned repository.

    """
    name = self.validate_and_normalize_repo_name(name)
    if self.does_repo_exist(name):
        raise InvalidRepoName(
            "That repo name you provided already exists. Please choose another."
        )

    # noinspection PyTypeChecker
    r = Repo(url=url, name=name, branch=branch, folder_path=self.repos_folder / name)
    await r.clone()

    self._repos[name] = r

    return r


# Traceback (downloader.errors.CloningError)
[31/12/2017 16:30] ERROR downloader _repo_add 218: Something went wrong during the cloning process.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/redbot/cogs/downloader/downloader.py", line 212, in _repo_add
branch=branch
File "/usr/local/lib/python3.6/site-packages/redbot/cogs/downloader/repo_manager.py", line 540, in add_repo
await r.clone()
File "/usr/local/lib/python3.6/site-packages/redbot/cogs/downloader/repo_manager.py", line 198, in clone
raise CloningError("Error when running git clone.")
downloader.errors.CloningError: Error when running git clone.

# Fixed code
async def add_repo(self, url: str, name: str, branch: str = "master") -> Repo:
    """Add and clone a git repository.

    Parameters
    ----------
    url : str
        URL to the git repository.
    name : str
        Internal name of the repository.
    branch : str
        Name of the default branch to checkout into.

    Returns
    -------
    Repo
        New Repo object representing the cloned repository.

    """
    if self.does_repo_exist(name):
        raise InvalidRepoName(
            "That repo name you provided already exists. Please choose another."
        )

    # noinspection PyTypeChecker
    r = Repo(url=url, name=name, branch=branch, folder_path=self.repos_folder / name)
    await r.clone()

    self._repos[name] = r

    return r
# Buggy code
def to_json(self):
    return {"location": self._location.relative_to(Path.cwd()).parts}


# Traceback (ValueError)
[11/11/2017 19:58] ERROR events on_command_error 159: Exception in command 'repo add'
Traceback (most recent call last):
File "c:\program files\python36\lib\site-packages\discord\ext\commands\core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\downloader.py", line 212, in _repo_add
branch=branch
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 541, in add_repo
await self._save_repos()
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in _save_repos
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in <dictcomp>
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 475, in to_json
"folder_path": self.folder_path.relative_to(Path.cwd()).parts,
File "c:\program files\python36\lib\pathlib.py", line 870, in relative_to
.format(str(self), str(formatted)))
ValueError: 'E:\\github\\Testbot\\cogs\\RepoManager\\repos\\trusty' does not start with 'C:\\Users\\Trusty'

# Fixed code
def to_json(self):
    data_path = data_manager.cog_data_path()
    return {"location": self._location.relative_to(data_path).parts}
# Buggy code
def from_json(cls, data: dict):
    location = Path.cwd() / Path(*data["location"])
    return cls(location=location)


# Traceback (ValueError)
[11/11/2017 19:58] ERROR events on_command_error 159: Exception in command 'repo add'
Traceback (most recent call last):
File "c:\program files\python36\lib\site-packages\discord\ext\commands\core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\downloader.py", line 212, in _repo_add
branch=branch
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 541, in add_repo
await self._save_repos()
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in _save_repos
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in <dictcomp>
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 475, in to_json
"folder_path": self.folder_path.relative_to(Path.cwd()).parts,
File "c:\program files\python36\lib\pathlib.py", line 870, in relative_to
.format(str(self), str(formatted)))
ValueError: 'E:\\github\\Testbot\\cogs\\RepoManager\\repos\\trusty' does not start with 'C:\\Users\\Trusty'

# Fixed code
def from_json(cls, data: dict):
    data_path = data_manager.cog_data_path()
    location = data_path / Path(*data["location"])
    return cls(location=location)
# Buggy code
def to_json(self):
    return {
        "url": self.url,
        "name": self.name,
        "branch": self.branch,
        "folder_path": self.folder_path.relative_to(Path.cwd()).parts,
        "available_modules": [m.to_json() for m in self.available_modules],
    }


# Traceback (ValueError)
[11/11/2017 19:58] ERROR events on_command_error 159: Exception in command 'repo add'
Traceback (most recent call last):
File "c:\program files\python36\lib\site-packages\discord\ext\commands\core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\downloader.py", line 212, in _repo_add
branch=branch
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 541, in add_repo
await self._save_repos()
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in _save_repos
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in <dictcomp>
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 475, in to_json
"folder_path": self.folder_path.relative_to(Path.cwd()).parts,
File "c:\program files\python36\lib\pathlib.py", line 870, in relative_to
.format(str(self), str(formatted)))
ValueError: 'E:\\github\\Testbot\\cogs\\RepoManager\\repos\\trusty' does not start with 'C:\\Users\\Trusty'

# Fixed code
def to_json(self):
    data_path = data_manager.cog_data_path()
    return {
        "url": self.url,
        "name": self.name,
        "branch": self.branch,
        "folder_path": self.folder_path.relative_to(data_path).parts,
        "available_modules": [m.to_json() for m in self.available_modules],
    }
# Buggy code
def from_json(cls, data):
    # noinspection PyTypeChecker
    return Repo(
        data["name"],
        data["url"],
        data["branch"],
        Path.cwd() / Path(*data["folder_path"]),
        tuple([Installable.from_json(m) for m in data["available_modules"]]),
    )


# Traceback (ValueError)
[11/11/2017 19:58] ERROR events on_command_error 159: Exception in command 'repo add'
Traceback (most recent call last):
File "c:\program files\python36\lib\site-packages\discord\ext\commands\core.py", line 62, in wrapped
ret = yield from coro(*args, **kwargs)
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\downloader.py", line 212, in _repo_add
branch=branch
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 541, in add_repo
await self._save_repos()
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in _save_repos
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 628, in <dictcomp>
repo_json_info = {name: r.to_json() for name, r in self._repos.items()}
File "C:\Program Files\Python36\Lib\site-packages\redbot\cogs\downloader\repo_manager.py", line 475, in to_json
"folder_path": self.folder_path.relative_to(Path.cwd()).parts,
File "c:\program files\python36\lib\pathlib.py", line 870, in relative_to
.format(str(self), str(formatted)))
ValueError: 'E:\\github\\Testbot\\cogs\\RepoManager\\repos\\trusty' does not start with 'C:\\Users\\Trusty'

# Fixed code
def from_json(cls, data):
    data_path = data_manager.cog_data_path()
    # noinspection PyTypeChecker
    return Repo(
        data["name"],
        data["url"],
        data["branch"],
        data_path / Path(*data["folder_path"]),
        tuple([Installable.from_json(m) for m in data["available_modules"]]),
    )
# Buggy code
def patch_notes_handler(self, repo_cog_hash_pairs):
    for repo, cog, oldhash in repo_cog_hash_pairs:
        pathsplit = self.repos[repo][cog]["file"].split("/")
        repo_path = os.path.join(*pathsplit[:-2])
        cogfile = os.path.join(*pathsplit[-2:])
        cmd = [
            "git",
            "-C",
            repo_path,
            "log",
            "--relative-date",
            "--reverse",
            oldhash + "..",
            cogfile,
        ]
        try:
            log = run(cmd, stdout=PIPE).stdout.decode().strip()
            yield self.format_patch(repo, cog, log)
        except:
            pass


# Traceback (ValueError)
Traceback (most recent call last):
File "lib\discord\ext\commands\core.py", line 50, in wrapped
ret = yield from coro(args, **kwargs)
File "C:\Users\bot\Downloads\X\cogs\downloader.py", line 243, in update
name, updates, oldhash = await f
File "C:\Users\bot\AppData\Local\Programs\Python\Python36\lib\asyncio\tasks.py", line 452, in _wait_for_one
return f.result()  # May raise f.exception().
File "C:\Users\bot\AppData\Local\Programs\Python\Python36\lib\concurrent\futures\thread.py", line 55, in run
result = self.fn(self.args, **self.kwargs)
File "C:\Users\bot\Downloads\X\cogs\downloader.py", line 615, in update_repo
status, cogpath = f.split('\t')
ValueError: too many values to unpack (expected 2)

# Fixed code
def patch_notes_handler(self, repo_cog_hash_pairs):
    for repo, cog, oldhash in repo_cog_hash_pairs:
        pathsplit = self.repos[repo][cog]["file"].split("/")
        repo_path = os.path.join(*pathsplit[:-2])
        cogfile = os.path.join(*pathsplit[-2:])
        cmd = [
            "git",
            "-C",
            repo_path,
            "log",
            "--relative-date",
            "--reverse",
            oldhash + "..",
            cogfile,
        ]
        try:
            log = sp_run(cmd, stdout=PIPE).stdout.decode().strip()
            yield self.format_patch(repo, cog, log)
        except:
            pass
# Buggy code
def install(self):
    """Initialize installation process and show install widget."""
    self.setup(integration=False, welcome=False, installation=True)
    self._installation_thread.cancelled = False
    self._installation_thread.install()


# Traceback (TypeError)
File "D:\AbdullahAli\Anaconda\lib\site-packages\spyder\plugins\completion\kite\widgets\install.py", line 308, in install
self.setup(integration=False, welcome=False, installation=True)
TypeError: setup() got an unexpected keyword argument 'welcome'
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 404, 'json': {'message': 'Not Found', 'documentation_url': 'https://docs.github.com/rest/reference/issues#create-an-issue'}}

# Fixed code
def install(self):
    """Initialize installation process and show install widget."""
    self.setup(integration=False, installation=True)
    self._installation_thread.cancelled = False
    self._installation_thread.install()
# Buggy code
def update_editor(self, items, editor=None):
    """
    Update the outline explorer for `editor` preserving the tree
    state.
    """
    plugin_base = self.parent().parent()
    if editor is None:
        editor = self.current_editor
    editor_id = editor.get_id()
    language = editor.get_language()
    update = self.update_tree(items, editor_id, language)

    if getattr(plugin_base, "_isvisible", True) and update:
        self.save_expanded_state()
        self.restore_expanded_state()
        self.do_follow_cursor()


# Traceback (TypeError)
File "C:\arc_pro\bin\Python\envs\arcgispro-py3\lib\site-packages\spyder\plugins\outlineexplorer\widgets.py", line 433, in toggle_variables
self.update_editor(editor.info, editor)
File "C:\arc_pro\bin\Python\envs\arcgispro-py3\lib\site-packages\spyder\plugins\outlineexplorer\widgets.py", line 615, in update_editor
update = self.update_tree(items, editor_id, language)
File "C:\arc_pro\bin\Python\envs\arcgispro-py3\lib\site-packages\spyder\plugins\outlineexplorer\widgets.py", line 645, in update_tree
for symbol in items:
TypeError: 'NoneType' object is not iterable
Traceback (most recent call last):
File "C:\arc_pro\bin\Python\envs\arcgispro-py3\lib\site-packages\spyder\plugins\outlineexplorer\widgets.py", line 433, in toggle_variables
self.update_editor(editor.info, editor)
File "C:\arc_pro\bin\Python\envs\arcgispro-py3\lib\site-packages\spyder\plugins\outlineexplorer\widgets.py", line 615, in update_editor
update = self.update_tree(items, editor_id, language)
File "C:\arc_pro\bin\Python\envs\arcgispro-py3\lib\site-packages\spyder\plugins\outlineexplorer\widgets.py", line 645, in update_tree
for symbol in items:
TypeError: 'NoneType' object is not iterable

# Fixed code
def update_editor(self, items, editor=None):
    """
    Update the outline explorer for `editor` preserving the tree
    state.
    """
    if items is None:
        return

    plugin_base = self.parent().parent()
    if editor is None:
        editor = self.current_editor
    editor_id = editor.get_id()
    language = editor.get_language()
    update = self.update_tree(items, editor_id, language)

    if getattr(plugin_base, "_isvisible", True) and update:
        self.save_expanded_state()
        self.restore_expanded_state()
        self.do_follow_cursor()