gurudesh/pytracebugs huggingface dataset:
# Buggy code
def list_cache_contents(cmd):
    from glob import glob

    directory = _get_cache_directory(cmd.cli_ctx)
    contents = []
    rg_paths = glob(os.path.join(directory, "*"))
    for rg_path in rg_paths:
        rg_name = os.path.split(rg_path)[1]
        for dir_name, _, file_list in os.walk(rg_path):
            if not file_list:
                continue
            resource_type = os.path.split(dir_name)[1]
            for f in file_list:
                with open(os.path.join(dir_name, f), "r") as cache_file:
                    cache_obj = json.loads(cache_file.read())
                contents.append(
                    {
                        "resourceGroup": rg_name,
                        "resourceType": resource_type,
                        "name": f.split(".", 1)[0],
                        "lastTouched": cache_obj["_last_touched"],
                    }
                )
    return contents


# Traceback (TypeError)
join() argument must be str or bytes, not 'NoneType'
Traceback (most recent call last):
python3.7/site-packages/knack/cli.py, ln 206, in invoke
cmd_result = self.invocation.execute(args)
cli/core/commands/__init__.py, ln 523, in execute
raise ex
cli/core/commands/__init__.py, ln 581, in _run_jobs_serially
results.append(self._run_job(expanded_arg, cmd_copy))
cli/core/commands/__init__.py, ln 574, in _run_job
six.reraise(*sys.exc_info())
...
cli/command_modules/configure/custom.py, ln 194, in show_cache_contents
item_path = os.path.join(directory, resource_group_name, resource_type, '{}.json'.format(item_name))
../lib/python3.7/posixpath.py, ln 94, in join
genericpath._check_arg_types('join', a, *p)
../lib/python3.7/genericpath.py, ln 149, in _check_arg_types
(funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'NoneType'

# Fixed code
def list_cache_contents(cmd):
    from glob import glob

    directory = _get_cache_directory(cmd.cli_ctx)
    contents = []
    rg_paths = glob(os.path.join(directory, "*"))
    for rg_path in rg_paths:
        rg_name = os.path.split(rg_path)[1]
        for dir_name, _, file_list in os.walk(rg_path):
            if not file_list:
                continue
            resource_type = os.path.split(dir_name)[1]
            for f in file_list:
                file_path = os.path.join(dir_name, f)
                try:
                    with open(file_path, "r") as cache_file:
                        cache_obj = json.loads(cache_file.read())
                        contents.append(
                            {
                                "resourceGroup": rg_name,
                                "resourceType": resource_type,
                                "name": f.split(".", 1)[0],
                                "lastSaved": cache_obj["last_saved"],
                            }
                        )
                except KeyError:
                    # invalid cache entry
                    logger.debug("Removing corrupt cache file: %s", file_path)
                    os.remove(file_path)
    return contents
# Buggy code
def show_cache_contents(
    cmd, resource_group_name=None, item_name=None, resource_type=None
):
    directory = _get_cache_directory(cmd.cli_ctx)
    item_path = os.path.join(
        directory, resource_group_name, resource_type, "{}.json".format(item_name)
    )
    try:
        with open(item_path, "r") as cache_file:
            cache_obj = json.loads(cache_file.read())
    except OSError:
        raise CLIError("Not found in cache: {}".format(item_path))
    return cache_obj["_payload"]


# Traceback (TypeError)
join() argument must be str or bytes, not 'NoneType'
Traceback (most recent call last):
python3.7/site-packages/knack/cli.py, ln 206, in invoke
cmd_result = self.invocation.execute(args)
cli/core/commands/__init__.py, ln 523, in execute
raise ex
cli/core/commands/__init__.py, ln 581, in _run_jobs_serially
results.append(self._run_job(expanded_arg, cmd_copy))
cli/core/commands/__init__.py, ln 574, in _run_job
six.reraise(*sys.exc_info())
...
cli/command_modules/configure/custom.py, ln 194, in show_cache_contents
item_path = os.path.join(directory, resource_group_name, resource_type, '{}.json'.format(item_name))
../lib/python3.7/posixpath.py, ln 94, in join
genericpath._check_arg_types('join', a, *p)
../lib/python3.7/genericpath.py, ln 149, in _check_arg_types
(funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'NoneType'

# Fixed code
def show_cache_contents(cmd, resource_group_name, item_name, resource_type):
    directory = _get_cache_directory(cmd.cli_ctx)
    item_path = os.path.join(
        directory, resource_group_name, resource_type, "{}.json".format(item_name)
    )
    try:
        with open(item_path, "r") as cache_file:
            cache_obj = json.loads(cache_file.read())
    except (OSError, IOError):
        raise CLIError("Not found in cache: {}".format(item_path))
    return cache_obj["_payload"]
# Buggy code
def delete_cache_contents(
    cmd, resource_group_name=None, item_name=None, resource_type=None
):
    directory = _get_cache_directory(cmd.cli_ctx)
    item_path = os.path.join(
        directory, resource_group_name, resource_type, "{}.json".format(item_name)
    )
    try:
        os.remove(item_path)
    except OSError:
        logger.info("%s not found in object cache.", item_path)


# Traceback (TypeError)
join() argument must be str or bytes, not 'NoneType'
Traceback (most recent call last):
python3.7/site-packages/knack/cli.py, ln 206, in invoke
cmd_result = self.invocation.execute(args)
cli/core/commands/__init__.py, ln 523, in execute
raise ex
cli/core/commands/__init__.py, ln 581, in _run_jobs_serially
results.append(self._run_job(expanded_arg, cmd_copy))
cli/core/commands/__init__.py, ln 574, in _run_job
six.reraise(*sys.exc_info())
...
cli/command_modules/configure/custom.py, ln 194, in show_cache_contents
item_path = os.path.join(directory, resource_group_name, resource_type, '{}.json'.format(item_name))
../lib/python3.7/posixpath.py, ln 94, in join
genericpath._check_arg_types('join', a, *p)
../lib/python3.7/genericpath.py, ln 149, in _check_arg_types
(funcname, s.__class__.__name__)) from None
TypeError: join() argument must be str or bytes, not 'NoneType'

# Fixed code
def delete_cache_contents(cmd, resource_group_name, item_name, resource_type):
    directory = _get_cache_directory(cmd.cli_ctx)
    item_path = os.path.join(
        directory, resource_group_name, resource_type, "{}.json".format(item_name)
    )
    try:
        os.remove(item_path)
    except (OSError, IOError):
        logger.info("%s not found in object cache.", item_path)
# Buggy code
def _get_fx_version(cmd, resource_group_name, name, slot=None):
    site_config = get_site_configs(cmd, resource_group_name, name, slot)
    return site_config.linux_fx_version or site_config.windows_fx_version


# Traceback (AttributeError)
'NoneType' object has no attribute 'strip'
Traceback (most recent call last):
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/knack/cli.py", line 197, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/azure/cli/core/commands/__init__.py", line 372, in execute
six.reraise(*sys.exc_info())
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/six.py", line 693, in reraise
raise value
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/azure/cli/core/commands/__init__.py", line 346, in execute
result = cmd(params)
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/azure/cli/core/commands/__init__.py", line 182, in __call__
return self.handler(*args, **kwargs)
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/azure/cli/core/__init__.py", line 436, in default_command_handler
result = op(**command_args)
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/azure/cli/command_modules/appservice/custom.py", line 805, in update_container_settings
return _mask_creds_related_appsettings(_filter_for_container_settings(cmd, resource_group_name, name, settings))
File "/usr/local/Cellar/azure-cli/2.0.49/libexec/lib/python3.7/site-packages/azure/cli/command_modules/appservice/custom.py", line 843, in _filter_for_container_settings
fx_version = _get_fx_version(cmd, resource_group_name, name, slot).strip()
AttributeError: 'NoneType' object has no attribute 'strip'

# Fixed code
def _get_fx_version(cmd, resource_group_name, name, slot=None):
    site_config = get_site_configs(cmd, resource_group_name, name, slot)
    return site_config.linux_fx_version or site_config.windows_fx_version or ""
# Buggy code
def open_page_in_browser(url):
    import subprocess
    import webbrowser

    platform_name, release = _get_platform_info()

    if _is_wsl(platform_name, release):  # windows 10 linux subsystem
        try:
            return subprocess.call(
                ["cmd.exe", "/c", "start {}".format(url.replace("&", "^&"))]
            )
        except FileNotFoundError:  # WSL might be too old
            pass
    elif platform_name == "darwin":
        # handle 2 things:
        # a. On OSX sierra, 'python -m webbrowser -t <url>' emits out "execution error: <url> doesn't
        #    understand the "open location" message"
        # b. Python 2.x can't sniff out the default browser
        return subprocess.Popen(["open", url])
    return webbrowser.open(url, new=2)  # 2 means: open in a new tab, if possible


# Traceback (TypeError)
$ az login
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "./virtualenv-az/lib/python3.7/site-packages/azure/cli/core/_profile.py", line 1033, in _get_authorization_code_worker
succ = open_page_in_browser(url)
File "./virtualenv-az/lib/python3.7/site-packages/azure/cli/core/util.py", line 266, in open_page_in_browser
return webbrowser.open(url, new=2) # 2 means: open in a new tab, if possible
File "/usr/lib64/python3.7/webbrowser.py", line 75, in open
register_standard_browsers()
File "/usr/lib64/python3.7/webbrowser.py", line 567, in register_standard_browsers
cmd = _synthesize(cmdline, -1)
File "/usr/lib64/python3.7/webbrowser.py", line 116, in _synthesize
register(browser, None, controller, update_tryorder)
TypeError: register() takes from 2 to 3 positional arguments but 4 were given

# Fixed code
def open_page_in_browser(url):
    import subprocess
    import webbrowser

    platform_name, release = _get_platform_info()

    if _is_wsl(platform_name, release):  # windows 10 linux subsystem
        try:
            return subprocess.call(
                ["cmd.exe", "/c", "start {}".format(url.replace("&", "^&"))]
            )
        except FileNotFoundError:  # WSL might be too old
            pass
    elif platform_name == "darwin":
        # handle 2 things:
        # a. On OSX sierra, 'python -m webbrowser -t <url>' emits out "execution error: <url> doesn't
        #    understand the "open location" message"
        # b. Python 2.x can't sniff out the default browser
        return subprocess.Popen(["open", url])
    try:
        return webbrowser.open(url, new=2)  # 2 means: open in a new tab, if possible
    except TypeError:  # See https://bugs.python.org/msg322439
        return webbrowser.open(url, new=2)
# Buggy code
def _get_child(parent, collection_name, item_name, collection_key):
    items = getattr(parent, collection_name)
    result = next(
        (
            x
            for x in items
            if getattr(x, collection_key, "").lower() == item_name.lower()
        ),
        None,
    )
    if not result:
        raise CLIError(
            "Property '{}' does not exist for key '{}'.".format(
                item_name, collection_key
            )
        )
    else:
        return result


# Traceback (AttributeError)
az network lb frontend-ip update \
--ids /subscriptions/xxxx/resourceGroups/yyyy/providers/Microsoft.Network/loadBalancers/kubernetes \
--public-ip-address /subscriptions/xxxx/resourceGroups/zzzz/providers/Microsoft.Network/publicIPAddresses/foo

'NoneType' object has no attribute 'lower'
Traceback (most recent call last):
File "/home/foo/.virtualenvs/kubernetes/local/lib/python2.7/site-packages/knack/cli.py", line 197, in invoke
cmd_result = self.invocation.execute(args)
File "/home/foo/.virtualenvs/kubernetes/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 369, in execute
six.reraise(*sys.exc_info())
File "/home/foo/.virtualenvs/kubernetes/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 343, in execute
result = cmd(params)
File "/home/foo/.virtualenvs/kubernetes/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 182, in __call__
return self.handler(*args, **kwargs)
File "/home/foo/.virtualenvs/kubernetes/local/lib/python2.7/site-packages/azure/cli/core/commands/arm.py", line 469, in handler
child_collection_key
File "/home/foo/.virtualenvs/kubernetes/local/lib/python2.7/site-packages/azure/cli/core/commands/arm.py", line 335, in _get_child
item_name.lower()), None)
File "/home/foo/.virtualenvs/kubernetes/local/lib/python2.7/site-packages/azure/cli/core/commands/arm.py", line 335, in <genexpr>
item_name.lower()), None)
AttributeError: 'NoneType' object has no attribute 'lower'

# Fixed code
def _get_child(parent, collection_name, item_name, collection_key):
    if not item_name:
        raise CLIError(
            "Name property for collection '{}' not provided. Check your input.".format(
                collection_name
            )
        )
    items = getattr(parent, collection_name)
    result = next(
        (
            x
            for x in items
            if getattr(x, collection_key, "").lower() == item_name.lower()
        ),
        None,
    )
    if not result:
        raise CLIError(
            "Property '{}' does not exist for key '{}'.".format(
                item_name, collection_key
            )
        )
    return result
# Buggy code
def load(self, filename, max_age=0):
    self.filename = filename
    self.data = {}
    try:
        if max_age > 0:
            st = os.stat(self.filename)
            if st.st_mtime + max_age < time.clock():
                self.save()
        with codecs_open(self.filename, "r", encoding=self._encoding) as f:
            self.data = json.load(f)
    except (OSError, IOError):
        self.save()


# Traceback (json.decoder.JSONDecodeError)
Traceback (most recent call last):
File 'runpy.py', line 193, in _run_module_as_main
File 'runpy.py', line 85, in _run_code
File 'C:\\Users\\trdai\\AppData\\Local\\Temp\\pip-install-8jgnm5o1\\azure-cli\\azure\\cli\\__main__.py', line 32, in <module>
File 'C:\\Users\\trdai\\AppData\\Local\\Temp\\pip-install-8jgnm5o1\\azure-cli-core\\azure\\cli\\core\\__init__.py', line 509, in get_default_cli
File 'C:\\Users\\trdai\\AppData\\Local\\Temp\\pip-install-8jgnm5o1\\azure-cli-core\\azure\\cli\\core\\__init__.py', line 52, in __init__
File 'C:\\Users\\trdai\\AppData\\Local\\Temp\\pip-install-8jgnm5o1\\azure-cli-core\\azure\\cli\\core\\_session.py', line 40, in load
File 'json\\__init__.py', line 299, in load
File 'json\\__init__.py', line 354, in loads
File 'json\\decoder.py', line 339, in decode
File 'json\\decoder.py', line 357, in raw_decode
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

# Fixed code
def load(self, filename, max_age=0):
    self.filename = filename
    self.data = {}
    try:
        if max_age > 0:
            st = os.stat(self.filename)
            if st.st_mtime + max_age < time.clock():
                self.save()
        with codecs_open(self.filename, "r", encoding=self._encoding) as f:
            self.data = json.load(f)
    except (OSError, IOError, t_JSONDecodeError):
        get_logger(__name__).warning(
            "Fail to load or parse file %s. It is overridden by default settings.",
            self.filename,
        )
        self.save()
# Buggy code
def parse_quotes(cmd, quotes=True, string=True):
    """parses quotes"""
    import shlex

    if quotes:
        args = shlex.split(cmd)
    else:
        args = cmd.split()

    if string:
        str_args = []
        for arg in args:
            str_args.append(str(arg))
        return str_args
    return args


# Traceback (ValueError)
az>> \
No escaped character
Traceback (most recent call last):
File "C:\Users\wilx\azure-cli\env36\lib\site-packages\knack\cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 347, in execute
six.reraise(*sys.exc_info())
File "C:\Users\wilx\azure-cli\env36\lib\site-packages\six.py", line 693, in reraise
raise value
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 319, in execute
result = cmd(params)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 180, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "C:\Users\wilx\azure-cli\env36\lib\site-packages\knack\commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\__init__.py", line 418, in default_command_handler
result = op(**command_args)
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\__init__.py", line 13, in start_shell
AzInteractiveShell(cmd.cli_ctx, style)()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 144, in __call__
self.run()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 715, in run
b_flag, c_flag, outside, cmd = self._special_cases(cmd, outside)
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 470, in _special_cases
args = parse_quotes(cmd)
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\util.py", line 59, in parse_quotes
args = shlex.split(cmd)
File "C:\Users\wilx\AppData\Local\Programs\Python\Python36-32\lib\shlex.py", line 305, in split
return list(lex)
File "C:\Users\wilx\AppData\Local\Programs\Python\Python36-32\lib\shlex.py", line 295, in __next__
token = self.get_token()
File "C:\Users\wilx\AppData\Local\Programs\Python\Python36-32\lib\shlex.py", line 105, in get_token
raw = self.read_token()
File "C:\Users\wilx\AppData\Local\Programs\Python\Python36-32\lib\shlex.py", line 206, in read_token
raise ValueError("No escaped character")
ValueError: No escaped character

# Fixed code
def parse_quotes(cmd, quotes=True, string=True):
    """parses quotes"""
    import shlex

    try:
        args = shlex.split(cmd) if quotes else cmd.split()
    except ValueError as exception:
        logger.error(exception)
        return []

    return [str(arg) for arg in args] if string else args
# Buggy code
def _get_vault_id_from_name(cli_ctx, client, vault_name):
    group_name = _get_resource_group_from_vault_name(cli_ctx, vault_name)
    vault = client.get(group_name, vault_name)
    return vault.id


# Traceback (msrest.exceptions.ValidationError)
I am following these steps to try to build a LINUX VM with SSL certificate.

https://docs.microsoft.com/en-us/azure/virtual-machines/linux/tutorial-secure-web-server

But I am failing at following step.

$ secret=$(az keyvault secret list-versions --vault-name WebSvrCert --name WebCert --query "[?attributes.enabled].id" --output tsv)

$ echo $secret
https://websvrcert.vault.azure.net/secrets/WebCert/d79e98486c5f42a6a12c863608b3a6e8

$ vm_secret=$(az vm secret format --secret "$secret")
Parameter 'resource_group_name' can not be None.
Traceback (most recent call last):
File "/opt/az/lib/python3.6/site-packages/knack/cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/init.py", line 331, in execute
six.reraise(*sys.exc_info())
File "/opt/az/lib/python3.6/site-packages/six.py", line 693, in reraise
raise value
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/init.py", line 304, in execute
result = cmd(params)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/commands/init.py", line 168, in call
return super(AzCliCommand, self).call(*args, **kwargs)
File "/opt/az/lib/python3.6/site-packages/knack/commands.py", line 109, in call
return self.handler(*args, **kwargs)
File "/opt/az/lib/python3.6/site-packages/azure/cli/core/init.py", line 348, in default_command_handler
result = op(**command_args)
File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/vm/custom.py", line 1429, in get_vm_format_secret
'id': _get_vault_id_from_name(cmd.cli_ctx, client, vault_name)
File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/vm/custom.py", line 1406, in _get_vault_id_from_name
vault = client.get(group_name, vault_name)
File "/opt/az/lib/python3.6/site-packages/azure/mgmt/keyvault/operations/vaults_operations.py", line 193, in get
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
File "/opt/az/lib/python3.6/site-packages/msrest/serialization.py", line 488, in url
data = self.validate(data, name, required=True, **kwargs)
File "/opt/az/lib/python3.6/site-packages/msrest/serialization.py", line 558, in validate
raise ValidationError("required", name, True)
msrest.exceptions.ValidationError: Parameter 'resource_group_name' can not be None.
chi@Azure:~/clouddrive$

# Fixed code
def _get_vault_id_from_name(cli_ctx, client, vault_name):
    group_name = _get_resource_group_from_vault_name(cli_ctx, vault_name)
    if not group_name:
        raise CLIError(
            "unable to find vault '{}' in current subscription.".format(vault_name)
        )
    vault = client.get(group_name, vault_name)
    return vault.id
# Buggy code
def _pick_working_subscription(subscriptions):
    from azure.mgmt.resource.subscriptions.models import SubscriptionState

    s = next(
        (x for x in subscriptions if x["state"] == SubscriptionState.enabled.value),
        None,
    )
    return s or subscriptions[0]


# Traceback (KeyError)
$  az account list
'state'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/knack/cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 347, in execute
six.reraise(*sys.exc_info())
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 319, in execute
result = cmd(params)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 180, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/knack/commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/__init__.py", line 418, in default_command_handler
result = op(**command_args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/command_modules/profile/custom.py", line 42, in list_subscriptions
enabled_ones = [s for s in subscriptions if s['state'] == 'Enabled']
KeyError: 'state'

# Fixed code
def _pick_working_subscription(subscriptions):
    from azure.mgmt.resource.subscriptions.models import SubscriptionState

    s = next(
        (x for x in subscriptions if x.get(_STATE) == SubscriptionState.enabled.value),
        None,
    )
    return s or subscriptions[0]
# Buggy code
def find_from_user_account(self, username, password, tenant, resource):
    context = self._create_auth_context(tenant)
    if password:
        token_entry = context.acquire_token_with_username_password(
            resource, username, password, _CLIENT_ID
        )
    else:  # when refresh account, we will leverage local cached tokens
        token_entry = context.acquire_token(resource, username, _CLIENT_ID)

    self.user_id = token_entry[_TOKEN_ENTRY_USER_ID]

    if tenant is None:
        result = self._find_using_common_tenant(token_entry[_ACCESS_TOKEN], resource)
    else:
        result = self._find_using_specific_tenant(tenant, token_entry[_ACCESS_TOKEN])
    return result


# Traceback (KeyError)
$  az account list
'state'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/knack/cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 347, in execute
six.reraise(*sys.exc_info())
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 319, in execute
result = cmd(params)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 180, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/knack/commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/__init__.py", line 418, in default_command_handler
result = op(**command_args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/command_modules/profile/custom.py", line 42, in list_subscriptions
enabled_ones = [s for s in subscriptions if s['state'] == 'Enabled']
KeyError: 'state'

# Fixed code
def find_from_user_account(self, username, password, tenant, resource):
    context = self._create_auth_context(tenant)
    if password:
        token_entry = context.acquire_token_with_username_password(
            resource, username, password, _CLIENT_ID
        )
    else:  # when refresh account, we will leverage local cached tokens
        token_entry = context.acquire_token(resource, username, _CLIENT_ID)

    if not token_entry:
        return []
    self.user_id = token_entry[_TOKEN_ENTRY_USER_ID]

    if tenant is None:
        result = self._find_using_common_tenant(token_entry[_ACCESS_TOKEN], resource)
    else:
        result = self._find_using_specific_tenant(tenant, token_entry[_ACCESS_TOKEN])
    return result
# Buggy code
def transform_account_list(result):
    transformed = []
    for r in result:
        res = OrderedDict(
            [
                ("Name", r["name"]),
                ("CloudName", r["cloudName"]),
                ("SubscriptionId", r["id"]),
                ("State", r["state"]),
                ("IsDefault", r["isDefault"]),
            ]
        )
        transformed.append(res)
    return transformed


# Traceback (KeyError)
$  az account list
'state'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/knack/cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 347, in execute
six.reraise(*sys.exc_info())
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 319, in execute
result = cmd(params)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 180, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/knack/commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/__init__.py", line 418, in default_command_handler
result = op(**command_args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/command_modules/profile/custom.py", line 42, in list_subscriptions
enabled_ones = [s for s in subscriptions if s['state'] == 'Enabled']
KeyError: 'state'

# Fixed code
def transform_account_list(result):
    transformed = []
    for r in result:
        res = OrderedDict(
            [
                ("Name", r["name"]),
                ("CloudName", r["cloudName"]),
                ("SubscriptionId", r["id"]),
                ("State", r.get("state")),
                ("IsDefault", r["isDefault"]),
            ]
        )
        transformed.append(res)
    return transformed
# Buggy code
def list_subscriptions(cmd, all=False, refresh=False):  # pylint: disable=redefined-builtin
    """List the imported subscriptions."""
    subscriptions = _load_subscriptions(cmd.cli_ctx, all_clouds=all, refresh=refresh)
    if not subscriptions:
        logger.warning('Please run "az login" to access your accounts.')
    for sub in subscriptions:
        sub["cloudName"] = sub.pop("environmentName", None)
    if not all:
        enabled_ones = [s for s in subscriptions if s["state"] == "Enabled"]
        if len(enabled_ones) != len(subscriptions):
            logger.warning(
                "A few accounts are skipped as they don't have 'Enabled' state. "
                "Use '--all' to display them."
            )
            subscriptions = enabled_ones
    return subscriptions


# Traceback (KeyError)
$  az account list
'state'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/knack/cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 347, in execute
six.reraise(*sys.exc_info())
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 319, in execute
result = cmd(params)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 180, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/knack/commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/azure/cli/core/__init__.py", line 418, in default_command_handler
result = op(**command_args)
File "/usr/local/lib/python2.7/site-packages/azure/cli/command_modules/profile/custom.py", line 42, in list_subscriptions
enabled_ones = [s for s in subscriptions if s['state'] == 'Enabled']
KeyError: 'state'

# Fixed code
def list_subscriptions(cmd, all=False, refresh=False):  # pylint: disable=redefined-builtin
    """List the imported subscriptions."""
    subscriptions = _load_subscriptions(cmd.cli_ctx, all_clouds=all, refresh=refresh)
    if not subscriptions:
        logger.warning('Please run "az login" to access your accounts.')
    for sub in subscriptions:
        sub["cloudName"] = sub.pop("environmentName", None)
    if not all:
        enabled_ones = [s for s in subscriptions if s.get("state") == "Enabled"]
        if len(enabled_ones) != len(subscriptions):
            logger.warning(
                "A few accounts are skipped as they don't have 'Enabled' state. "
                "Use '--all' to display them."
            )
            subscriptions = enabled_ones
    return subscriptions
# Buggy code
def load_command_table(self, args):
    with self.command_group(
        "", operations_tmpl="azure.cli.command_modules.interactive#{}"
    ) as g:
        g.command("interactive", "start_shell")
    return self.command_table


# Traceback (AssertionError)
(env36b) C:\Users\wilx\azure-cli>az interactive -s primary

Traceback (most recent call last):
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\knack\cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 347, in execute
six.reraise(*sys.exc_info())
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\six.py", line 693, in reraise
raise value
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 319, in execute
result = cmd(params)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 180, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\knack\commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\__init__.py", line 418, in default_command_handler
result = op(**command_args)
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\__init__.py", line 13, in start_shell
AzInteractiveShell(cmd.cli_ctx, style)()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 144, in __call__
self.run()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 690, in run
self.cli.buffers['symbols'].reset(
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 151, in cli
self._cli = self.create_interface()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 369, in create_interface
application=self.create_application(),
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 362, in create_application
buffers=buffers,
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\prompt_toolkit\application.py", line 121, in __init__
assert style is None or isinstance(style, Style)
AssertionError

# Fixed code
def load_command_table(self, _):
    with self.command_group(
        "", operations_tmpl="azure.cli.command_modules.interactive#{}"
    ) as g:
        g.command("interactive", "start_shell")
    return self.command_table
# Buggy code
def load_arguments(self, command):
    from azure.cli.command_modules.interactive.azclishell.color_styles import (
        get_options as style_options,
    )

    with self.argument_context("interactive") as c:
        c.argument(
            "style",
            options_list=["--style", "-s"],
            help="The colors of the shell.",
            choices=style_options(),
        )


# Traceback (AssertionError)
(env36b) C:\Users\wilx\azure-cli>az interactive -s primary

Traceback (most recent call last):
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\knack\cli.py", line 194, in invoke
cmd_result = self.invocation.execute(args)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 347, in execute
six.reraise(*sys.exc_info())
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\six.py", line 693, in reraise
raise value
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 319, in execute
result = cmd(params)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\commands\__init__.py", line 180, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\knack\commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "c:\users\wilx\azure-cli\src\azure-cli-core\azure\cli\core\__init__.py", line 418, in default_command_handler
result = op(**command_args)
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\__init__.py", line 13, in start_shell
AzInteractiveShell(cmd.cli_ctx, style)()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 144, in __call__
self.run()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 690, in run
self.cli.buffers['symbols'].reset(
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 151, in cli
self._cli = self.create_interface()
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 369, in create_interface
application=self.create_application(),
File "c:\users\wilx\azure-cli\src\command_modules\azure-cli-interactive\azure\cli\command_modules\interactive\azclishell\app.py", line 362, in create_application
buffers=buffers,
File "C:\Users\wilx\azure-cli\env36b\lib\site-packages\prompt_toolkit\application.py", line 121, in __init__
assert style is None or isinstance(style, Style)
AssertionError

# Fixed code
def load_arguments(self, _):
    from azure.cli.command_modules.interactive.azclishell.color_styles import (
        get_options as style_options,
    )

    with self.argument_context("interactive") as c:
        c.argument(
            "style",
            options_list=["--style", "-s"],
            help="The colors of the shell.",
            choices=style_options(),
        )
# Buggy code
def _download_blob(blob_service, container, destination_folder, blob_name):
    import os

    # TODO: try catch IO exception
    destination_path = os.path.join(destination_folder, blob_name)
    destination_folder = os.path.dirname(destination_path)
    if not os.path.exists(destination_folder):
        mkdir_p(destination_folder)

    blob = blob_service.get_blob_to_path(
        container, blob_name, destination_path, progress_callback=progress_callback
    )
    return blob.name


# Traceback (TypeError)
az --verbose storage blob download --name test.csv --file a --start-range 0 --end-range 10 --container-name *** --connection-string 'DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=***;AccountKey=***'

unsupported operand type(s) for -: 'str' and 'str'
Traceback (most recent call last):
File "az_virtenv/lib/python3.4/site-packages/knack/cli.py", line 193, in invoke
cmd_result = self.invocation.execute(args)
File "az_virtenv/lib/python3.4/site-packages/azure/cli/core/commands/__init__.py", line 319, in execute
six.reraise(*sys.exc_info())
File "az_virtenv/lib/python3.4/site-packages/six.py", line 693, in reraise
raise value
File "az_virtenv/lib/python3.4/site-packages/azure/cli/core/commands/__init__.py", line 292, in execute
result = cmd(params)
File "az_virtenv/lib/python3.4/site-packages/azure/cli/core/commands/__init__.py", line 169, in __call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "az_virtenv/lib/python3.4/site-packages/knack/commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "az_virtenv/lib/python3.4/site-packages/azure/cli/core/__init__.py", line 328, in default_command_handler
result = op(**command_args)
File "az_virtenv/lib/python3.4/site-packages/azure/multiapi/storage/v2017_04_17/blob/baseblobservice.py", line 1784, in get_blob_to_path
timeout)
File "az_virtenv/lib/python3.4/site-packages/azure/multiapi/storage/v2017_04_17/blob/baseblobservice.py", line 1915, in get_blob_to_stream
if end_range and end_range - start_range < first_get_size:
TypeError: unsupported operand type(s) for -: 'str' and 'str'

# Fixed code
def _download_blob(blob_service, container, destination_folder, blob_name):
    import os

    # TODO: try catch IO exception
    destination_path = os.path.join(destination_folder, blob_name)
    destination_folder = os.path.dirname(destination_path)
    if not os.path.exists(destination_folder):
        mkdir_p(destination_folder)

    blob = blob_service.get_blob_to_path(
        container,
        blob_name,
        destination_path,
        max_connections=max_connections,
        progress_callback=progress_callback,
    )
    return blob.name
# Buggy code
def _build_os_profile():
    os_profile = {"computerName": name, "adminUsername": admin_username}

    if admin_password:
        os_profile["adminPassword"] = admin_password

    if custom_data:
        os_profile["customData"] = b64encode(custom_data)

    if ssh_key_value and ssh_key_path:
        os_profile["linuxConfiguration"] = {
            "disablePasswordAuthentication": True,
            "ssh": {"publicKeys": [{"keyData": ssh_key_value, "path": ssh_key_path}]},
        }

    if secrets:
        os_profile["secrets"] = secrets

    return os_profile


# Traceback (FileNotFoundError)
(env) C:\Users\trpresco\Documents\github\azure-cli>run_tests --module network --parallel
The run_tests command is going to be replaced by 'azdev test' command.

Traceback (most recent call last):
File "C:\Users\trpresco\Documents\github\azure-cli\env\Scripts\run_tests-script.py", line 11, in <module>
load_entry_point('azure-cli-dev-tools', 'console_scripts', 'run_tests')()
File "c:\users\trpresco\documents\github\azure-cli\tools\automation\tests\__init__.py", line 79, in legacy_entry_point
args.func(args)
File "c:\users\trpresco\documents\github\azure-cli\tools\automation\tests\__init__.py", line 20, in execute
current_profile = check_output(shlex.split('az cloud show --query profile -otsv')).decode('utf-8').strip()
File "C:\Users\trpresco\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 336, in check_output
**kwargs).stdout
File "C:\Users\trpresco\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\trpresco\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 707, in __init__
restore_signals, start_new_session)
File "C:\Users\trpresco\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 990, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

# Fixed code
def _build_os_profile():
    os_profile = {"computerName": name, "adminUsername": admin_username}

    if admin_password:
        os_profile["adminPassword"] = "[parameters('adminPassword')]"

    if custom_data:
        os_profile["customData"] = b64encode(custom_data)

    if ssh_key_value and ssh_key_path:
        os_profile["linuxConfiguration"] = {
            "disablePasswordAuthentication": True,
            "ssh": {"publicKeys": [{"keyData": ssh_key_value, "path": ssh_key_path}]},
        }

    if secrets:
        os_profile["secrets"] = secrets

    return os_profile
# Buggy code
def firsttime(self):
    """sets it as already done"""
    self.config.set("DEFAULT", "firsttime", "no")
    if self.config.getboolean("core", "collect_telemetry", fallback=False):
        print(PRIVACY_STATEMENT)
    else:
        self.cli_config.set_value("core", "collect_telemetry", ask_user_for_telemetry())

    self.update()


# Traceback (TypeError)
getboolean() got an unexpected keyword argument 'fallback'
Traceback (most recent call last):
File "/usr/lib64/az/lib/python2.7/site-packages/knack/cli.py", line 193, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 319, inexecute
six.reraise(*sys.exc_info())
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 292, inexecute
result = cmd(params)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 169, in__call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "/usr/lib64/az/lib/python2.7/site-packages/knack/commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/__init__.py", line 328, in default_command_handler
result = op(**command_args)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/command_modules/interactive/__init__.py", line 13, in start_shell
AzInteractiveShell(cmd.cli_ctx, style)()
File "/usr/lib64/az/lib/python2.7/site-packages/azclishell/app.py", line 149, in __call__
self.config.firsttime()
File "/usr/lib64/az/lib/python2.7/site-packages/azclishell/configuration.py", line 104, in firsttime
if self.config.getboolean('core', 'collect_telemetry', fallback=False):
TypeError: getboolean() got an unexpected keyword argument 'fallback'

# Fixed code
def firsttime(self):
    """sets it as already done"""
    self.config.set("DEFAULT", "firsttime", "no")
    if self.cli_config.getboolean("core", "collect_telemetry", fallback=False):
        print(PRIVACY_STATEMENT)
    else:
        self.cli_config.set_value("core", "collect_telemetry", ask_user_for_telemetry())

    self.update()
# Buggy code
def has_feedback(self):
    """returns whether user has given feedback"""
    return self.config.getboolean("core", "given feedback", fallback="false")


# Traceback (TypeError)
getboolean() got an unexpected keyword argument 'fallback'
Traceback (most recent call last):
File "/usr/lib64/az/lib/python2.7/site-packages/knack/cli.py", line 193, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 319, inexecute
six.reraise(*sys.exc_info())
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 292, inexecute
result = cmd(params)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/commands/__init__.py", line 169, in__call__
return super(AzCliCommand, self).__call__(*args, **kwargs)
File "/usr/lib64/az/lib/python2.7/site-packages/knack/commands.py", line 109, in __call__
return self.handler(*args, **kwargs)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/core/__init__.py", line 328, in default_command_handler
result = op(**command_args)
File "/usr/lib64/az/lib/python2.7/site-packages/azure/cli/command_modules/interactive/__init__.py", line 13, in start_shell
AzInteractiveShell(cmd.cli_ctx, style)()
File "/usr/lib64/az/lib/python2.7/site-packages/azclishell/app.py", line 149, in __call__
self.config.firsttime()
File "/usr/lib64/az/lib/python2.7/site-packages/azclishell/configuration.py", line 104, in firsttime
if self.config.getboolean('core', 'collect_telemetry', fallback=False):
TypeError: getboolean() got an unexpected keyword argument 'fallback'

# Fixed code
def has_feedback(self):
    """returns whether user has given feedback"""
    return self.cli_config.getboolean("core", "given feedback", fallback="false")