gurudesh/pytracebugs huggingface dataset:
# Buggy code
def disconnect(self):
    """Disconnect session, close socket if needed."""
    if self.session is not None:
        try:
            self._eagain(self.session.disconnect)
        except Exception:
            pass
    if self.sock is not None and not self.sock.closed:
        self.sock.close()


# Traceback (ValueError)
Traceback (most recent call last):
File "./aws-instances", line 172, in <module>
main()
File "./aws-instances", line 73, in main
facts = remote_facts(ips)
File "./aws-instances", line 146, in remote_facts
out_kern = client.run_command('uname -r')
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 223, in run_command
greenlet_timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 96, in run_command
self.get_output(cmd, output, timeout=greenlet_timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/base_pssh.py", line 141, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get(timeout=timeout)
File "src/gevent/greenlet.py", line 709, in gevent._greenlet.Greenlet.get
File "src/gevent/greenlet.py", line 317, in gevent._greenlet.Greenlet._raise_exception
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/_compat.py", line 47, in reraise
raise value.with_traceback(tb)
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 237, in _run_command
raise ex
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/parallel.py", line 233, in _run_command
use_pty=use_pty, encoding=encoding, timeout=timeout)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 442, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 324, in execute
channel = self.open_session() if channel is None else channel
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/pssh/clients/native/single.py", line 297, in open_session
wait_select(self.session)
File "pssh/native/_ssh2.pyx", line 171, in pssh.native._ssh2.wait_select
File "/home/user/do-aws-ec2-facts/aws/lib64/python3.6/site-packages/gevent/select.py", line 145, in select
sel_results = _original_select(rlist, wlist, xlist, 0)
ValueError: filedescriptor out of range in select()

# Fixed code
def disconnect(self):
    """Disconnect session, close socket if needed."""
    logger.debug("Disconnecting client for host %s", self.host)
    if self.session is not None:
        try:
            self._eagain(self.session.disconnect)
        except Exception:
            pass
    if self.sock is not None and not self.sock.closed:
        self.sock.close()
        logger.debug("Client socket closed for host %s", self.host)
# Buggy code
def _start_tunnel(self, host):
    if host in self._tunnels:
        return self._tunnels[host]
    tunnel = Tunnel(
        self.proxy_host,
        host,
        self.port,
        user=self.proxy_user,
        password=self.proxy_password,
        port=self.proxy_port,
        pkey=self.proxy_pkey,
        num_retries=self.num_retries,
        timeout=self.timeout,
        retry_delay=self.retry_delay,
        allow_agent=self.allow_agent,
    )
    tunnel.daemon = True
    tunnel.start()
    self._tunnels[host] = tunnel
    while not tunnel.tunnel_open.is_set():
        logger.debug("Waiting for tunnel to become active")
        sleep(0.1)
        if not tunnel.is_alive():
            msg = "Proxy authentication failed"
            logger.error(msg)
            raise ProxyError(msg)
    return tunnel


# Traceback (SessionError)
Exception in thread Thread-360:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/tunnel.py", line 123, in run
self._init_tunnel_client()
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/tunnel.py", line 119, in _init_tunnel_client
timeout=self.timeout)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 120, in __init__
THREAD_POOL.apply(self._init)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/gevent/pool.py", line 324, in apply
return func(*args, **kwds)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 158, in _init
return self._connect_init_retry(retries)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 148, in _connect_init_retry
return self._init(retries=retries)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 160, in _init
raise SessionError(msg, self.host, self.port, ex)
SessionError: ('Error connecting to host %s:%s - %s', 'proxy.example.com', 22, Timeout())

# Fixed code
def _start_tunnel(self, host):
    if host in self._tunnels:
        return self._tunnels[host]
    tunnel = Tunnel(
        self.proxy_host,
        host,
        self.port,
        user=self.proxy_user,
        password=self.proxy_password,
        port=self.proxy_port,
        pkey=self.proxy_pkey,
        num_retries=self.num_retries,
        timeout=self.timeout,
        retry_delay=self.retry_delay,
        allow_agent=self.allow_agent,
    )
    tunnel.daemon = True
    tunnel.start()
    while not tunnel.tunnel_open.is_set():
        logger.debug("Waiting for tunnel to become active")
        sleep(0.1)
        if not tunnel.is_alive():
            msg = "Proxy authentication failed. Exception from tunnel client: %s"
            logger.error(msg, tunnel.exception)
            raise ProxyError(msg, tunnel.exception)
    self._tunnels[host] = tunnel
    return tunnel
# Buggy code
def __init__(
    self,
    host,
    fw_host,
    fw_port,
    user=None,
    password=None,
    port=None,
    pkey=None,
    num_retries=DEFAULT_RETRIES,
    retry_delay=RETRY_DELAY,
    allow_agent=True,
    timeout=None,
    listen_port=0,
):
    Thread.__init__(self)
    self.client = None
    self.session = None
    self.socket = None
    self.listen_port = listen_port
    self.fw_host = fw_host
    self.fw_port = fw_port if fw_port else 22
    self.channel = None
    self.forward_sock = None
    self.host = host
    self.port = port
    self.user = user
    self.password = password
    self.pkey = pkey
    self.num_retries = num_retries
    self.retry_delay = retry_delay
    self.allow_agent = allow_agent
    self.timeout = timeout
    self.tunnel_open = Event()


# Traceback (SessionError)
Exception in thread Thread-360:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/tunnel.py", line 123, in run
self._init_tunnel_client()
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/tunnel.py", line 119, in _init_tunnel_client
timeout=self.timeout)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 120, in __init__
THREAD_POOL.apply(self._init)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/gevent/pool.py", line 324, in apply
return func(*args, **kwds)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 158, in _init
return self._connect_init_retry(retries)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 148, in _connect_init_retry
return self._init(retries=retries)
File "/Users/PATH_TO_APP/venv/lib/python2.7/site-packages/pssh/clients/native/single.py", line 160, in _init
raise SessionError(msg, self.host, self.port, ex)
SessionError: ('Error connecting to host %s:%s - %s', 'proxy.example.com', 22, Timeout())

# Fixed code
def __init__(
    self,
    host,
    fw_host,
    fw_port,
    user=None,
    password=None,
    port=None,
    pkey=None,
    num_retries=DEFAULT_RETRIES,
    retry_delay=RETRY_DELAY,
    allow_agent=True,
    timeout=None,
    listen_port=0,
):
    Thread.__init__(self)
    self.client = None
    self.session = None
    self.socket = None
    self.listen_port = listen_port
    self.fw_host = fw_host
    self.fw_port = fw_port if fw_port else 22
    self.channel = None
    self.forward_sock = None
    self.host = host
    self.port = port
    self.user = user
    self.password = password
    self.pkey = pkey
    self.num_retries = num_retries
    self.retry_delay = retry_delay
    self.allow_agent = allow_agent
    self.timeout = timeout
    self.exception = None
    self.tunnel_open = Event()
# Buggy code
def __init__(self, *args, **kwargs):
    """Initialize an Apache Configurator.

    :param tup version: version of Apache as a tuple (2, 4, 7)
        (used mostly for unittesting)

    """
    version = kwargs.pop("version", None)
    super(ApacheConfigurator, self).__init__(*args, **kwargs)

    # Add name_server association dict
    self.assoc = dict()
    # Outstanding challenges
    self._chall_out = set()
    # Maps enhancements to vhosts we've enabled the enhancement for
    self._enhanced_vhosts = defaultdict(set)

    # These will be set in the prepare function
    self.parser = None
    self.version = version
    self.vhosts = None
    self._enhance_func = {
        "redirect": self._enable_redirect,
        "ensure-http-header": self._set_http_header,
        "staple-ocsp": self._enable_ocsp_stapling,
    }


# Traceback (PluginError)
Cannot find a cert or key directive in /files/etc/apache2/sites-available/default-ssl.conf/IfModule/VirtualHost. VirtualHost was not modified
Encountered exception:
Traceback (most recent call last):
File "/home/bmw/src/certbot/certbot/client.py", line 439, in deploy_certificate
fullchain_path=fullchain_path)
File "/home/bmw/src/certbot/certbot-apache/certbot_apache/configurator.py", line 269, in deploy_cert
"Unable to find cert and/or key directives")
PluginError: Unable to find cert and/or key directives

Calling registered functions
Reporting to user: Unable to install the certificate
Exiting abnormally:
Traceback (most recent call last):
File "/usr/local/bin/certbot", line 11, in <module>
load_entry_point('certbot', 'console_scripts', 'certbot')()
File "/home/bmw/src/certbot/certbot/main.py", line 743, in main
return config.func(config, plugins)
File "/home/bmw/src/certbot/certbot/main.py", line 604, in run
_install_cert(config, le_client, domains, new_lineage)
File "/home/bmw/src/certbot/certbot/main.py", line 469, in _install_cert
path_provider.cert_path, path_provider.chain_path, path_provider.fullchain_path)
File "/home/bmw/src/certbot/certbot/client.py", line 439, in deploy_certificate
fullchain_path=fullchain_path)
File "/home/bmw/src/certbot/certbot-apache/certbot_apache/configurator.py", line 269, in deploy_cert
"Unable to find cert and/or key directives")
PluginError: Unable to find cert and/or key directives

# Fixed code
def __init__(self, *args, **kwargs):
    """Initialize an Apache Configurator.

    :param tup version: version of Apache as a tuple (2, 4, 7)
        (used mostly for unittesting)

    """
    version = kwargs.pop("version", None)
    super(ApacheConfigurator, self).__init__(*args, **kwargs)

    # Add name_server association dict
    self.assoc = dict()
    # Outstanding challenges
    self._chall_out = set()
    # Maps enhancements to vhosts we've enabled the enhancement for
    self._enhanced_vhosts = defaultdict(set)

    # These will be set in the prepare function
    self.parser = None
    self.version = version
    self.vhosts = None
    self.vhostroot = None
    self._enhance_func = {
        "redirect": self._enable_redirect,
        "ensure-http-header": self._set_http_header,
        "staple-ocsp": self._enable_ocsp_stapling,
    }
# Buggy code
def _get_ssl_vhost_path(self, non_ssl_vh_fp):
    # Get filepath of new ssl_vhost
    if non_ssl_vh_fp.endswith(".conf"):
        return non_ssl_vh_fp[: -(len(".conf"))] + self.conf("le_vhost_ext")
    else:
        return non_ssl_vh_fp + self.conf("le_vhost_ext")


# Traceback (PluginError)
Cannot find a cert or key directive in /files/etc/apache2/sites-available/default-ssl.conf/IfModule/VirtualHost. VirtualHost was not modified
Encountered exception:
Traceback (most recent call last):
File "/home/bmw/src/certbot/certbot/client.py", line 439, in deploy_certificate
fullchain_path=fullchain_path)
File "/home/bmw/src/certbot/certbot-apache/certbot_apache/configurator.py", line 269, in deploy_cert
"Unable to find cert and/or key directives")
PluginError: Unable to find cert and/or key directives

Calling registered functions
Reporting to user: Unable to install the certificate
Exiting abnormally:
Traceback (most recent call last):
File "/usr/local/bin/certbot", line 11, in <module>
load_entry_point('certbot', 'console_scripts', 'certbot')()
File "/home/bmw/src/certbot/certbot/main.py", line 743, in main
return config.func(config, plugins)
File "/home/bmw/src/certbot/certbot/main.py", line 604, in run
_install_cert(config, le_client, domains, new_lineage)
File "/home/bmw/src/certbot/certbot/main.py", line 469, in _install_cert
path_provider.cert_path, path_provider.chain_path, path_provider.fullchain_path)
File "/home/bmw/src/certbot/certbot/client.py", line 439, in deploy_certificate
fullchain_path=fullchain_path)
File "/home/bmw/src/certbot/certbot-apache/certbot_apache/configurator.py", line 269, in deploy_cert
"Unable to find cert and/or key directives")
PluginError: Unable to find cert and/or key directives

# Fixed code
def _get_ssl_vhost_path(self, non_ssl_vh_fp):
    """Get a file path for SSL vhost, uses user defined path as priority,
    but if the value is invalid or not defined, will fall back to non-ssl
    vhost filepath.

    :param str non_ssl_vh_fp: Filepath of non-SSL vhost

    :returns: Filepath for SSL vhost
    :rtype: str
    """

    if self.conf("vhost-root") and os.path.exists(self.conf("vhost-root")):
        # Defined by user on CLI

        fp = os.path.join(
            os.path.realpath(self.vhostroot), os.path.basename(non_ssl_vh_fp)
        )
    else:
        # Use non-ssl filepath
        fp = os.path.realpath(non_ssl_vh_fp)

    if fp.endswith(".conf"):
        return fp[: -(len(".conf"))] + self.conf("le_vhost_ext")
    else:
        return fp + self.conf("le_vhost_ext")
# Buggy code
def __init__(self, regr, key, meta=None):
    self.key = key
    self.regr = regr
    self.meta = (
        self.Meta(
            # pyrfc3339 drops microseconds, make sure __eq__ is sane
            creation_dt=datetime.datetime.now(tz=pytz.UTC).replace(microsecond=0),
            creation_host=socket.getfqdn(),
        )
        if meta is None
        else meta
    )

    self.id = hashlib.md5(
        self.key.key.public_key().public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.SubjectPublicKeyInfo,
        )
    ).hexdigest()


# Traceback (ValueError)
Traceback (most recent call last):
File "/root/letsencrypt/venv/bin/letsencrypt", line 9, in <module>
load_entry_point('letsencrypt==0.1.0.dev0', 'console_scripts', 'letsencrypt')()
File "/root/letsencrypt/letsencrypt/cli.py", line 1002, in main
return args.func(args, config, plugins)
File "/root/letsencrypt/letsencrypt/cli.py", line 376, in auth
le_client = _init_le_client(args, config, authenticator, installer)
File "/root/letsencrypt/letsencrypt/cli.py", line 160, in _init_le_client
acc, acme = _determine_account(args, config)
File "/root/letsencrypt/letsencrypt/cli.py", line 147, in _determine_account
config, account_storage, tos_cb=_tos_cb)
File "/root/letsencrypt/letsencrypt/client.py", line 98, in register
acc = account.Account(regr, key)
File "/root/letsencrypt/letsencrypt/account.py", line 60, in __init__
format=serialization.PublicFormat.SubjectPublicKeyInfo)
File "/root/letsencrypt/venv/local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 614, in public_bytes
self._rsa_cdata
File "/root/letsencrypt/venv/local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1199, in _public_key_bytes
raise ValueError("Only PEM encoding is supported by this backend")
ValueError: Only PEM encoding is supported by this backend

# Fixed code
def __init__(self, regr, key, meta=None):
    self.key = key
    self.regr = regr
    self.meta = (
        self.Meta(
            # pyrfc3339 drops microseconds, make sure __eq__ is sane
            creation_dt=datetime.datetime.now(tz=pytz.UTC).replace(microsecond=0),
            creation_host=socket.getfqdn(),
        )
        if meta is None
        else meta
    )

    self.id = hashlib.md5(
        self.key.key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo,
        )
    ).hexdigest()
# Buggy code
def _parse_radius(radius):
    try:
        angle = commons.parse_radius(radius)
        # find the most appropriate unit - d, m or s
        index = min([i for (i, val) in enumerate(angle.dms) if int(val) > 0])
        unit = ("d", "m", "s")[index]
        if unit == "d":
            return str(int(angle.degree)) + unit
        if unit == "m":
            sec_to_min = abs(angle.dms[2]) * u.arcsec.to(u.arcmin)
            total_min = abs(angle.dms[1]) + sec_to_min
            return str(total_min) + unit
        if unit == "s":
            return str(abs(angle.dms[2])) + unit
    except (coord.errors.UnitsError, AttributeError):
        raise ValueError("Radius specified incorrectly")


# Traceback (ValueError)
result = astroquery.simbad.Simbad.query_region(coord.ICRS("00h00m0.0s 00h00m0.0s"), radius=1.0 * u.marcsec, equinox=2000.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/egeland/Code/sunstardb/lib/python2.7/site-packages/astroquery-0.2.dev1928-py2.7.egg/astroquery/simbad/core.py", line 440, in query_region
equinox=equinox, epoch=epoch)
File "/Users/egeland/Code/sunstardb/lib/python2.7/site-packages/astroquery-0.2.dev1928-py2.7.egg/astroquery/simbad/core.py", line 470, in query_region_async
caller='query_region_async')
File "/Users/egeland/Code/sunstardb/lib/python2.7/site-packages/astroquery-0.2.dev1928-py2.7.egg/astroquery/simbad/core.py", line 44, in wrapper
return func(*args, **kwargs)
File "/Users/egeland/Code/sunstardb/lib/python2.7/site-packages/astroquery-0.2.dev1928-py2.7.egg/astroquery/simbad/core.py", line 60, in wrapper
return func(*args, **kwargs)
File "/Users/egeland/Code/sunstardb/lib/python2.7/site-packages/astroquery-0.2.dev1928-py2.7.egg/astroquery/simbad/core.py", line 681, in _args_to_payload
kwargs['radius'] = _parse_radius(kwargs['radius'])
File "/Users/egeland/Code/sunstardb/lib/python2.7/site-packages/astroquery-0.2.dev1928-py2.7.egg/astroquery/simbad/core.py", line 765, in _parse_radius
index = min([i for (i,val) in enumerate(angle.dms) if int(val) > 0])
ValueError: min() arg is an empty sequence
result = astroquery.simbad.Simbad.query_region(coord.ICRS("00h00m0.0s 00h00m0.0s"), radius=1.0 * u.marcsec, equinox=2000.0, epoch='J2000')

# Fixed code
def _parse_radius(radius):
    try:
        angle = commons.parse_radius(radius)
        # find the most appropriate unit - d, m or s
        nonzero_indices = [i for (i, val) in enumerate(angle.dms) if int(val) > 0]
        if len(nonzero_indices) > 0:
            index = min(nonzero_indices)
        else:
            index = 2  # use arcseconds when radius smaller than 1 arcsecond
        unit = ("d", "m", "s")[index]
        if unit == "d":
            return str(int(angle.degree)) + unit
        if unit == "m":
            sec_to_min = abs(angle.dms[2]) * u.arcsec.to(u.arcmin)
            total_min = abs(angle.dms[1]) + sec_to_min
            return str(total_min) + unit
        if unit == "s":
            return str(abs(angle.dms[2])) + unit
    except (coord.errors.UnitsError, AttributeError):
        raise ValueError("Radius specified incorrectly")
# Buggy code
def check_download(self):
    check = self.scan_download({"dl_limit": self.DL_LIMIT_PATTERN})

    if check == "dl_limit":
        self.log_warning(self._("Free download limit reached"))
        os.remove(self.last_download)
        self.retry(wait=10800, msg=self._("Free download limit reached"))

    return super().check_download()


# Traceback (TypeError)
[2021-02-16 19:16:44]  DEBUG               pyload  Chunk 1 download finished
[2021-02-16 19:16:45]  INFO                pyload  DOWNLOADER UploadedTo[6]: File saved
[2021-02-16 19:16:45]  INFO                pyload  DOWNLOADER UploadedTo[6]: Checking download...
[2021-02-16 19:16:45]  INFO                pyload  DOWNLOADER UploadedTo[6]: File is OK
[2021-02-16 19:16:45]  DEBUG               pyload  ADDON ExternalScripts: No script found under folder `download_processed`
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/pyload/core/threads/download_thread.py", line 56, in run
pyfile.plugin.preprocessing(self)
File "/home/pi/.local/lib/python3.7/site-packages/pyload/plugins/base/hoster.py", line 300, in preprocessing
return self._process(*args, **kwargs)
File "/home/pi/.local/lib/python3.7/site-packages/pyload/plugins/base/downloader.py", line 107, in _process
self._check_download()
File "/home/pi/.local/lib/python3.7/site-packages/pyload/plugins/base/simple_downloader.py", line 315, in _check_download
self.check_download()
File "/home/pi/.local/lib/python3.7/site-packages/pyload/plugins/downloaders/UploadedTo.py", line 113, in check_download
check = self.scan_download({"dl_limit": self.DL_LIMIT_PATTERN})
File "/home/pi/.local/lib/python3.7/site-packages/pyload/plugins/base/downloader.py", line 370, in scan_download
if rule in content:
TypeError: a bytes-like object is required, not 'str'

# Fixed code
def check_download(self):
    check = self.scan_download({"dl_limit": to_bytes(self.DL_LIMIT_PATTERN)})

    if check == "dl_limit":
        self.log_warning(self._("Free download limit reached"))
        os.remove(self.last_download)
        self.retry(wait=10800, msg=self._("Free download limit reached"))

    return super().check_download()
# Buggy code
def stop(self):
    try:
        self.log.debug("Stopping core...")
        # self.evm.fire('pyload:stopping')

        for thread in self.thread_manager.threads:
            thread.put("quit")

        for pyfile in self.files.cache.values():
            pyfile.abort_download()

        self.addon_manager.core_exiting()

    finally:
        self.files.sync_save()
        self._running.clear()


# Traceback (RuntimeError)
[2020-09-20 06:49:22]  INFO                pyload  Download aborted: PC_Games_Extended_Magazin_No_06_Juni_2020.pdf
[2020-09-20 06:49:22]  DEBUG         pyload.webui  500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Traceback (most recent call last):
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/webui/app/blueprints/json_blueprint.py", line 116, in abort_link
api.stop_downloads([id])
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/core/api/__init__.py", line 80, in wrapper
return func(self, *args, **kwargs)
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/core/api/__init__.py", line 886, in stop_downloads
for pyfile in pyfiles:
RuntimeError: dictionary changed size during iteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/webui/app/helpers.py", line 181, in wrapper
response = func(*args, **kwargs)
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/webui/app/blueprints/json_blueprint.py", line 119, in abort_link
flask.abort(500)
File "/usr/local/lib/python3.8/dist-packages/werkzeug/exceptions.py", line 822, in abort
return _aborter(status, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/werkzeug/exceptions.py", line 807, in __call__
raise self.mapping[code](*args, **kwargs)
werkzeug.exceptions.InternalServerError: 500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

# Fixed code
def stop(self):
    try:
        self.log.debug("Stopping core...")
        # self.evm.fire('pyload:stopping')

        for thread in self.thread_manager.threads:
            thread.put("quit")

        for pyfile in list(self.files.cache.values()):
            pyfile.abort_download()

        self.addon_manager.core_exiting()

    finally:
        self.files.sync_save()
        self._running.clear()
# Buggy code
def stop_all_downloads(self):
    """
    Aborts all running downloads.
    """
    pyfiles = self.pyload.files.cache.values()
    for pyfile in pyfiles:
        pyfile.abort_download()


# Traceback (RuntimeError)
[2020-09-20 06:49:22]  INFO                pyload  Download aborted: PC_Games_Extended_Magazin_No_06_Juni_2020.pdf
[2020-09-20 06:49:22]  DEBUG         pyload.webui  500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Traceback (most recent call last):
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/webui/app/blueprints/json_blueprint.py", line 116, in abort_link
api.stop_downloads([id])
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/core/api/__init__.py", line 80, in wrapper
return func(self, *args, **kwargs)
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/core/api/__init__.py", line 886, in stop_downloads
for pyfile in pyfiles:
RuntimeError: dictionary changed size during iteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/webui/app/helpers.py", line 181, in wrapper
response = func(*args, **kwargs)
File "/home/ozzie/.local/lib/python3.8/site-packages/pyload/webui/app/blueprints/json_blueprint.py", line 119, in abort_link
flask.abort(500)
File "/usr/local/lib/python3.8/dist-packages/werkzeug/exceptions.py", line 822, in abort
return _aborter(status, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/werkzeug/exceptions.py", line 807, in __call__
raise self.mapping[code](*args, **kwargs)
werkzeug.exceptions.InternalServerError: 500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

# Fixed code
def stop_all_downloads(self):
    """
    Aborts all running downloads.
    """
    pyfiles = list(self.pyload.files.cache.values())
    for pyfile in pyfiles:
        pyfile.abort_download()
# Buggy code
def _delete_cookie(self):
    self.request["set_cookie"] = True
    self.cookie[self.key] = self.id
    if self._domain:
        self.cookie[self.key]["domain"] = self._domain
    if self.secure:
        self.cookie[self.key]["secure"] = True
    self.cookie[self.key]["path"] = "/"
    expires = datetime.today().replace(year=2003)
    self.cookie[self.key]["expires"] = expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
    self.request["cookie_out"] = self.cookie[self.key].output(header="")
    self.request["set_cookie"] = True


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/share/pyload/module/lib/bottle.py", line 733, in _handle
return route.call(**args)
File "/usr/share/pyload/module/lib/bottle.py", line 1448, in wrapper
rv = callback(*a, **ka)
File "/usr/share/pyload/module/web/pyload_app.py", line 235, in logout
s.delete()
File "/usr/share/pyload/module/lib/beaker/session.py", line 594, in delete
self._session().delete()
File "/usr/share/pyload/module/lib/beaker/session.py", line 196, in delete
self._delete_cookie()
File "/usr/share/pyload/module/lib/beaker/session.py", line 186, in _delete_cookie
expires = datetime.today().replace(year=2003)
ValueError: day is out of range for month

# Fixed code
def _delete_cookie(self):
    self.request["set_cookie"] = True
    self.cookie[self.key] = self.id
    if self._domain:
        self.cookie[self.key]["domain"] = self._domain
    if self.secure:
        self.cookie[self.key]["secure"] = True
    self.cookie[self.key]["path"] = "/"
    expires = datetime.today().replace(day=1, year=2003)
    self.cookie[self.key]["expires"] = expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT")
    self.request["cookie_out"] = self.cookie[self.key].output(header="")
    self.request["set_cookie"] = True
# Buggy code
def recognize(self, audio):
    """Audio decoding - more info could be found at https://launchpad.net/adecaptcha"""
    # print "!!!CAPTCHA :", audio
    if adecaptcha_available:
        cfg_file = os.path.join(os.path.split(clslib.__file__)[0], "ulozto.cfg")
        text = clslib.classify_audio_file(audio, cfg_file)
        return text
    else:
        pass


# Traceback (ValueError)
7.03.2016 05:56:12 INFO      Starting payload 0.4.9
07.03.2016 05:56:12 INFO      Using home directory: /opt/etc/pyload
07.03.2016 05:56:12 DEBUG     Remote activated: False
07.03.2016 05:56:13 DEBUG     created index of plugins
07.03.2016 05:56:13 INFO      ExternalScripts: Installed scripts for download_finished: ExternalScript.sh, SCRIPTS
07.03.2016 05:56:13 INFO      ExtractArchive: Activated UnRar
07.03.2016 05:56:14 INFO      Activated plugins: CaptchaTrader, ClickAndLoad, ExternalScripts, ExtractArchive, UpdateManager
07.03.2016 05:56:14 INFO      Deactivate plugins: Ev0InFetcher, HotFolder, IRCInterface, MergeFiles, MultiHome, MultishareCz, RealdebridCom, RehostTo, XMPPInterface
07.03.2016 05:56:14 INFO      Downloadtime: True
07.03.2016 05:56:14 INFO      Free space: 1.81 TiB
07.03.2016 05:56:14 INFO      Activating Accounts...
07.03.2016 05:56:14 INFO      Activating Plugins...
07.03.2016 05:56:14 INFO      pyLoad is up and running
07.03.2016 05:56:14 INFO      Starting threaded webserver: 0.0.0.0:8000
07.03.2016 05:56:16 INFO      UpdateManager: No Updates for payload
Exception in thread Thread-16:
Traceback (most recent call last):
File "/opt/lib/python2.5/threading.py", line 486, in __bootstrap_inner
self.run()
File "/opt/share/pyload/module/PluginThread.py", line 466, in run
self.f(*self.args, **self.kwargs)
File "/opt/share/pyload/module/plugins/hooks/UpdateManager.py", line 52, in periodical
self.checkPlugins(updates)
File "/opt/share/pyload/module/plugins/hooks/UpdateManager.py", line 136, in checkPlugins
"version": float(version)
ValueError: empty string for float()

# Fixed code
def recognize(self, audio):
    """Audio decoding - more info could be found at https://launchpad.net/adecaptcha"""
    # print "!!!CAPTCHA :", audio
    try:
        cfg_file = os.path.join(os.path.split(clslib.__file__)[0], "ulozto.cfg")
        text = clslib.classify_audio_file(audio, cfg_file)
        return text

    except NameError:
        self.log_error(
            _("Unable to decode audio captcha"),
            _(
                "Please install adecaptcha library from https://github.com/izderadicka/adecaptcha"
            ),
        )
# Buggy code
def apiInfo(cls, url="", get={}, post={}):
    info = super(UploadedTo, cls).apiInfo(url)

    for _i in xrange(5):
        html = getURL(
            "http://uploaded.net/api/filemultiple",
            get={
                "apikey": cls.API_KEY,
                "id_0": re.match(cls.__pattern__, url).group("ID"),
            },
            decode=True,
        )

        if html != "can't find request":
            api = html.split(",", 4)
            if api[0] == "online":
                info.update({"name": api[4], "size": api[2], "status": 2})
            else:
                info["status"] = 1
            break
        else:
            sleep(3)

    return info


# Traceback (IOError)
02.02.2015 11:16:56 DEBUG     UploadedTo: File name: curl-7.40.0.zip
| File size: 6127024

02.02.2015 11:17:09 DEBUG     Error removing chunk: curl object not on this multi-stack
02.02.2015 11:17:09 WARNING   Download failed: curl-7.40.0.zip
| [Errno 22] invalid mode ('wb') or filename: u'd:\\downloads\\curl-7.40.0.zip\n.chunk0'
Traceback (most recent call last):
File "D:\Projekte\Coding\pyload\module\PluginThread.py", line 187, in run
pyfile.plugin.preprocessing(self)
File "D:\Projekte\Coding\pyload\module\plugins\Plugin.py", line 237, in preprocessing
return self.process(self.pyfile)
File "D:\Projekte\Coding\pyload\module\plugins\internal\SimpleHoster.py", line 490, in process
self.downloadLink(self.link)
File "D:\Projekte\Coding\pyload\module\plugins\internal\SimpleHoster.py", line 503, in downloadLink
self.download(link, ref=False, disposition=disposition)
File "D:\Projekte\Coding\pyload\module\plugins\Plugin.py", line 503, in download
progressNotify=self.pyfile.setProgress, disposition=disposition)
File "D:\Projekte\Coding\pyload\module\network\Browser.py", line 88, in httpDownload
name = self.dl.download(chunks, resume)
File "D:\Projekte\Coding\pyload\module\network\HTTPDownload.py", line 129, in download
self._download(chunks, resume)
File "D:\Projekte\Coding\pyload\module\network\HTTPDownload.py", line 160, in _download
self.m.add_handle(init.getHandle())
File "D:\Projekte\Coding\pyload\module\network\HTTPChunk.py", line 201, in getHandle
self.fp = open(fs_name, "wb")
IOError: [Errno 22] invalid mode ('wb') or filename: u'd:\\downloads\\curl-7.40.0.zip\n.chunk0'
02.02.2015 11:17:10 INFO      Debug Report written to debug_UploadedTo_02-02-2015_11-17-10.zip

# Fixed code
def apiInfo(cls, url="", get={}, post={}):
    info = super(UploadedTo, cls).apiInfo(url)

    for _i in xrange(5):
        html = getURL(
            "http://uploaded.net/api/filemultiple",
            get={
                "apikey": cls.API_KEY,
                "id_0": re.match(cls.__pattern__, url).group("ID"),
            },
            decode=True,
        )

        if html != "can't find request":
            api = html.split(",", 4)
            if api[0] == "online":
                info.update({"name": api[4].strip(), "size": api[2], "status": 2})
            else:
                info["status"] = 1
            break
        else:
            sleep(3)

    return info
# Buggy code
def checkNameSize(self, getinfo=True):
    if not self.info or getinfo:
        self.logDebug("File info (BEFORE): %s" % self.info)
        self.info.update(self.getInfo(self.pyfile.url, self.html))
        self.logDebug("File info (AFTER): %s" % self.info)

    try:
        url = self.info["url"]
        name = self.info["name"]
        if name and name != url:
            self.pyfile.name = name

    except Exception:
        pass

    try:
        folder = self.info["folder"] = self.pyfile.name

    except Exception:
        pass

    self.logDebug(
        "File name: %s" % self.pyfile.name, "File folder: %s" % self.pyfile.name
    )


# Traceback (IOError)
02.02.2015 11:16:56 DEBUG     UploadedTo: File name: curl-7.40.0.zip
| File size: 6127024

02.02.2015 11:17:09 DEBUG     Error removing chunk: curl object not on this multi-stack
02.02.2015 11:17:09 WARNING   Download failed: curl-7.40.0.zip
| [Errno 22] invalid mode ('wb') or filename: u'd:\\downloads\\curl-7.40.0.zip\n.chunk0'
Traceback (most recent call last):
File "D:\Projekte\Coding\pyload\module\PluginThread.py", line 187, in run
pyfile.plugin.preprocessing(self)
File "D:\Projekte\Coding\pyload\module\plugins\Plugin.py", line 237, in preprocessing
return self.process(self.pyfile)
File "D:\Projekte\Coding\pyload\module\plugins\internal\SimpleHoster.py", line 490, in process
self.downloadLink(self.link)
File "D:\Projekte\Coding\pyload\module\plugins\internal\SimpleHoster.py", line 503, in downloadLink
self.download(link, ref=False, disposition=disposition)
File "D:\Projekte\Coding\pyload\module\plugins\Plugin.py", line 503, in download
progressNotify=self.pyfile.setProgress, disposition=disposition)
File "D:\Projekte\Coding\pyload\module\network\Browser.py", line 88, in httpDownload
name = self.dl.download(chunks, resume)
File "D:\Projekte\Coding\pyload\module\network\HTTPDownload.py", line 129, in download
self._download(chunks, resume)
File "D:\Projekte\Coding\pyload\module\network\HTTPDownload.py", line 160, in _download
self.m.add_handle(init.getHandle())
File "D:\Projekte\Coding\pyload\module\network\HTTPChunk.py", line 201, in getHandle
self.fp = open(fs_name, "wb")
IOError: [Errno 22] invalid mode ('wb') or filename: u'd:\\downloads\\curl-7.40.0.zip\n.chunk0'
02.02.2015 11:17:10 INFO      Debug Report written to debug_UploadedTo_02-02-2015_11-17-10.zip

# Fixed code
def checkNameSize(self, getinfo=True):
    if not self.info or getinfo:
        self.logDebug("File info (BEFORE): %s" % self.info)
        self.info.update(self.getInfo(self.pyfile.url, self.html))
        self.logDebug("File info (AFTER): %s" % self.info)

    try:
        url = self.info["url"].strip()
        name = self.info["name"].strip()
        if name and name != url:
            self.pyfile.name = name

    except Exception:
        pass

    try:
        folder = self.info["folder"] = self.pyfile.name

    except Exception:
        pass

    self.logDebug(
        "File name: %s" % self.pyfile.name, "File folder: %s" % self.pyfile.name
    )
# Buggy code
def glob_files_remotely(cmd, client, share_name, pattern):
    """glob the files in remote file share based on the given pattern"""
    from collections import deque

    t_dir, t_file = cmd.get_models("file.models#Directory", "file.models#File")

    queue = deque([""])
    while queue:
        current_dir = queue.pop()
        for f in client.list_directories_and_files(share_name, current_dir):
            if isinstance(f, t_file):
                if not pattern or _match_path(
                    os.path.join(current_dir, f.name), pattern
                ):
                    yield current_dir, f.name
            elif isinstance(f, t_dir):
                queue.appendleft(os.path.join(current_dir, f.name))


# Traceback (azure.common.AzureMissingResourceHttpError)
The specified resource does not exist. ErrorCode: ResourceNotFound
<?xml version="1.0" encoding="utf-8"?><Error><Code>ResourceNotFound</Code><Message>The specified resource does not exist.
RequestId:321ffe99-801a-0056-2d7d-3c7264000000
Time:2019-07-17T08:56:12.4562505Z</Message></Error>
Traceback (most recent call last):
python3.6/site-packages/knack/cli.py, ln 206, in invoke
cmd_result = self.invocation.execute(args)
...
azure.common.AzureMissingResourceHttpError: The specified resource does not exist. ErrorCode: ResourceNotFound
<?xml version="1.0" encoding="utf-8"?><Error><Code>ResourceNotFound</Code><Message>The specified resource does not exist.
RequestId:321ffe99-801a-0056-2d7d-3c7264000000
Time:2019-07-17T08:56:12.4562505Z</Message></Error>

# Fixed code
def glob_files_remotely(cmd, client, share_name, pattern, snapshot=None):
    """glob the files in remote file share based on the given pattern"""
    from collections import deque

    t_dir, t_file = cmd.get_models("file.models#Directory", "file.models#File")

    queue = deque([""])
    while queue:
        current_dir = queue.pop()
        for f in client.list_directories_and_files(
            share_name, current_dir, snapshot=snapshot
        ):
            if isinstance(f, t_file):
                if not pattern or _match_path(
                    os.path.join(current_dir, f.name), pattern
                ):
                    yield current_dir, f.name
            elif isinstance(f, t_dir):
                queue.appendleft(os.path.join(current_dir, f.name))
# Buggy code
def _is_linux_os(vm):
    os_type = (
        vm.storage_profile.os_disk.os_type
        if vm.storage_profile.os_disk.os_type
        else None
    )
    if os_type:
        return os_type.lower() == "linux"
    # the os_type could be None for VM scaleset, let us check out os configurations
    if vm.os_profile.linux_configuration:
        return bool(vm.os_profile.linux_configuration)
    return False


# Traceback (AttributeError)
'NoneType' object has no attribute 'storage_profile'
Traceback (most recent call last):
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/knack/cli.py", line 215, in invoke
cmd_result = self.invocation.execute(args)
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/core/commands/__init__.py", line 654, in execute
raise ex
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/core/commands/__init__.py", line 718, in _run_jobs_serially
results.append(self._run_job(expanded_arg, cmd_copy))
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/core/commands/__init__.py", line 711, in _run_job
six.reraise(*sys.exc_info())
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/six.py", line 703, in reraise
raise value
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/core/commands/__init__.py", line 688, in _run_job
result = cmd_copy(params)
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/core/commands/__init__.py", line 325, in __call__
return self.handler(*args, **kwargs)
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/core/__init__.py", line 782, in default_command_handler
return op(**command_args)
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/command_modules/vm/custom.py", line 2878, in set_vmss_diagnostics_extension
is_linux_os = _is_linux_os(vmss.virtual_machine_profile)
File "/usr/local/Cellar/azure-cli/2.11.1/libexec/lib/python3.8/site-packages/azure/cli/command_modules/vm/custom.py", line 173, in _is_linux_os
os_type = vm.storage_profile.os_disk.os_type.value if vm.storage_profile.os_disk.os_type else None
AttributeError: 'NoneType' object has no attribute 'storage_profile'

# Fixed code
def _is_linux_os(vm):
    os_type = None
    if (
        vm
        and vm.storage_profile
        and vm.storage_profile.os_disk
        and vm.storage_profile.os_disk.os_type
    ):
        os_type = vm.storage_profile.os_disk.os_type
    if os_type:
        return os_type.lower() == "linux"
    # the os_type could be None for VM scaleset, let us check out os configurations
    if vm.os_profile.linux_configuration:
        return bool(vm.os_profile.linux_configuration)
    return False
# Buggy code
def purge_vault_or_hsm(
    cmd, client, location=None, vault_name=None, hsm_name=None, no_wait=False
):
    if is_azure_stack_profile(cmd) or vault_name:
        return sdk_no_wait(
            no_wait,
            client.begin_purge_deleted,
            location=location,
            vault_name=vault_name,
        )

    assert hsm_name
    hsm_client = get_client_factory(ResourceType.MGMT_KEYVAULT, Clients.managed_hsms)(
        cmd.cli_ctx, None
    )
    return hsm_client.purge_deleted(rlocation=location, name=hsm_name)


# Traceback (AttributeError)
'ManagedHsmsOperations' object has no attribute 'list_deleted'
Traceback (most recent call last):
python3.6/site-packages/knack/cli.py, ln 215, in invoke
cmd_result = self.invocation.execute(args)
cli/core/commands/__init__.py, ln 654, in execute
raise ex
cli/core/commands/__init__.py, ln 718, in _run_jobs_serially
results.append(self._run_job(expanded_arg, cmd_copy))
cli/core/commands/__init__.py, ln 711, in _run_job
six.reraise(*sys.exc_info())
...
cli/core/commands/__init__.py, ln 325, in __call__
return self.handler(*args, **kwargs)
azure/cli/core/__init__.py, ln 784, in default_command_handler
return op(**command_args)
cli/command_modules/keyvault/custom.py, ln 250, in list_deleted_vault_or_hsm
return hsm_client.list_deleted()
AttributeError: 'ManagedHsmsOperations' object has no attribute 'list_deleted'

# Fixed code
def purge_vault_or_hsm(
    cmd,
    client,
    location=None,
    vault_name=None,
    hsm_name=None,  # pylint: disable=unused-argument
    no_wait=False,
):
    if is_azure_stack_profile(cmd) or vault_name:
        return sdk_no_wait(
            no_wait,
            client.begin_purge_deleted,
            location=location,
            vault_name=vault_name,
        )
    return None
# Buggy code
def list_deleted_vault_or_hsm(cmd, client, resource_type=None):
    if is_azure_stack_profile(cmd):
        return client.list_deleted()

    if resource_type is None:
        hsm_client = get_client_factory(
            ResourceType.MGMT_KEYVAULT, Clients.managed_hsms
        )(cmd.cli_ctx, None)
        deleted_resources = []
        try:
            deleted_resources.extend(client.list_deleted())
            deleted_resources.extend(hsm_client.list_deleted())
        except:  # pylint: disable=bare-except
            pass

        return deleted_resources

    if resource_type == "hsm":
        hsm_client = get_client_factory(
            ResourceType.MGMT_KEYVAULT, Clients.managed_hsms
        )(cmd.cli_ctx, None)
        return hsm_client.list_deleted()

    if resource_type == "vault":
        return client.list_deleted()

    raise CLIError("Unsupported resource type: {}".format(resource_type))


# Traceback (AttributeError)
'ManagedHsmsOperations' object has no attribute 'list_deleted'
Traceback (most recent call last):
python3.6/site-packages/knack/cli.py, ln 215, in invoke
cmd_result = self.invocation.execute(args)
cli/core/commands/__init__.py, ln 654, in execute
raise ex
cli/core/commands/__init__.py, ln 718, in _run_jobs_serially
results.append(self._run_job(expanded_arg, cmd_copy))
cli/core/commands/__init__.py, ln 711, in _run_job
six.reraise(*sys.exc_info())
...
cli/core/commands/__init__.py, ln 325, in __call__
return self.handler(*args, **kwargs)
azure/cli/core/__init__.py, ln 784, in default_command_handler
return op(**command_args)
cli/command_modules/keyvault/custom.py, ln 250, in list_deleted_vault_or_hsm
return hsm_client.list_deleted()
AttributeError: 'ManagedHsmsOperations' object has no attribute 'list_deleted'

# Fixed code
def list_deleted_vault_or_hsm(cmd, client, resource_type=None):
    if is_azure_stack_profile(cmd):
        return client.list_deleted()

    if resource_type is None:
        return client.list_deleted()

    if resource_type == "hsm":
        raise InvalidArgumentValueError(
            'Operation "list-deleted" has not been supported for HSM.'
        )

    if resource_type == "vault":
        return client.list_deleted()

    raise CLIError("Unsupported resource type: {}".format(resource_type))