gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _destination_and_source(af, where, port, source, source_port, default_to_inet=True):
    # Apply defaults and compute destination and source tuples
    # suitable for use in connect(), sendto(), or bind().
    if af is None:
        try:
            af = dns.inet.af_for_address(where)
        except Exception:
            if default_to_inet:
                af = dns.inet.AF_INET
    if af == dns.inet.AF_INET:
        destination = (where, port)
        if source is not None or source_port != 0:
            if source is None:
                source = "0.0.0.0"
            source = (source, source_port)
    elif af == dns.inet.AF_INET6:
        destination = (where, port, 0, 0)
        if source is not None or source_port != 0:
            if source is None:
                source = "::"
            source = (source, source_port, 0, 0)
    else:
        source = None
        destination = None
    return (af, destination, source)


# Traceback (dns.exception.Timeout)
% python3
Python 3.6.3 (default, Oct  7 2017, 10:06:24)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import dns.resolver

r=dns.resolver.Resolver()
r.nameservers=['fe80::20c:29ff:fe66:3eac%en1']
r.lifetime=2
r.query('yahoo.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/farrokhi/workspace/dnsdiag/.venv/lib/python3.6/site-packages/dns/resolver.py", line 949, in query
timeout = self._compute_timeout(start)
File "/Users/farrokhi/workspace/dnsdiag/.venv/lib/python3.6/site-packages/dns/resolver.py", line 858, in _compute_timeout
raise Timeout(timeout=duration)
dns.exception.Timeout: The DNS operation timed out after 2.0031638145446777 seconds


# Fixed code
def _destination_and_source(af, where, port, source, source_port, default_to_inet=True):
    # Apply defaults and compute destination and source tuples
    # suitable for use in connect(), sendto(), or bind().
    if af is None:
        try:
            af = dns.inet.af_for_address(where)
        except Exception:
            if default_to_inet:
                af = dns.inet.AF_INET
    if af == dns.inet.AF_INET:
        destination = (where, port)
        if source is not None or source_port != 0:
            if source is None:
                source = "0.0.0.0"
            source = (source, source_port)
    elif af == dns.inet.AF_INET6:
        ai_flags = socket.AI_NUMERICHOST
        ((*_, destination), *_) = socket.getaddrinfo(where, port, flags=ai_flags)
        if source is not None or source_port != 0:
            if source is None:
                source = "::"
            ((*_, source), *_) = socket.getaddrinfo(source, source_port, flags=ai_flags)
    else:
        source = None
        destination = None
    return (af, destination, source)
# Buggy code
def __init__(self, rdclass, rdtype, strings):
    super(TXTBase, self).__init__(rdclass, rdtype)
    if isinstance(strings, str):
        strings = [strings]
    self.strings = strings[:]


# Traceback (TypeError)
from dns.rdtypes.txtbase import TXTBase
tb = TXTBase(rdtype='bar', rdclass='ham', strings='foo')
tb.to_digestable()
Traceback (most recent call last):
..../python3.5/site-packages/dns/rdtypes/txtbase.py", line 75, in to_wire
file.write(s)
TypeError: a bytes-like object is required, not 'str'

# Fixed code
def __init__(self, rdclass, rdtype, strings):
    super(TXTBase, self).__init__(rdclass, rdtype)
    if isinstance(strings, binary_type) or isinstance(strings, string_types):
        strings = [strings]
    self.strings = []
    for string in strings:
        if isinstance(string, string_types):
            string = string.encode()
        self.strings.append(string)
# Buggy code
def __init__(self, origin, rdclass=dns.rdataclass.IN, relativize=True):
    """Initialize a zone object.

    @param origin: The origin of the zone.
    @type origin: dns.name.Name object
    @param rdclass: The zone's rdata class; the default is class IN.
    @type rdclass: int"""

    if isinstance(origin, string_types):
        origin = dns.name.from_text(origin)
    elif not isinstance(origin, dns.name.Name):
        raise ValueError("origin parameter must be convertable to a DNS name")
    if not origin.is_absolute():
        raise ValueError("origin parameter must be an absolute name")
    self.origin = origin
    self.rdclass = rdclass
    self.nodes = {}
    self.relativize = relativize


# Traceback (ValueError)
ValueError                                Traceback (most recent call last)
<ipython-input-7-58a197c0fdca> in <module>()
7 print zone_text
8
----> 9 zone = dns.zone.from_text(zone_text)

/Users/graham/venvs/dnspython-testin/lib/python2.7/site-packages/dns/zone.pyc in from_text(text, origin, rdclass, relativize, zone_factory, filename, allow_include, check_origin)
964     reader = _MasterReader(tok, origin, rdclass, relativize, zone_factory,
965                            allow_include=allow_include,
--> 966                            check_origin=check_origin)
967     reader.read()
968     return reader.zone

/Users/graham/venvs/dnspython-testin/lib/python2.7/site-packages/dns/zone.pyc in __init__(self, tok, origin, rdclass, relativize, zone_factory, allow_include, check_origin)
597         self.ttl = 0
598         self.last_name = self.current_origin
--> 599         self.zone = zone_factory(origin, rdclass, relativize=relativize)
600         self.saved_state = []
601         self.current_file = None

/Users/graham/venvs/dnspython-testin/lib/python2.7/site-packages/dns/zone.pyc in __init__(self, origin, rdclass, relativize)
94             origin = dns.name.from_text(origin)
95         elif not isinstance(origin, dns.name.Name):
---> 96             raise ValueError("origin parameter must be convertable to a "
97                              "DNS name")
98         if not origin.is_absolute():

ValueError: origin parameter must be convertable to a DNS name

# Fixed code
def __init__(self, origin, rdclass=dns.rdataclass.IN, relativize=True):
    """Initialize a zone object.

    @param origin: The origin of the zone.
    @type origin: dns.name.Name object
    @param rdclass: The zone's rdata class; the default is class IN.
    @type rdclass: int"""

    if origin is not None:
        if isinstance(origin, string_types):
            origin = dns.name.from_text(origin)
        elif not isinstance(origin, dns.name.Name):
            raise ValueError("origin parameter must be convertable to a DNS name")
        if not origin.is_absolute():
            raise ValueError("origin parameter must be an absolute name")
    self.origin = origin
    self.rdclass = rdclass
    self.nodes = {}
    self.relativize = relativize
# Buggy code
def _create_tag(self, tag_str):
    """Create a Tag object from a tag string."""
    tag_hierarchy = tag_str.split(self.hierarchy_separator)
    tag_prefix = ""
    parent_tag = None
    for sub_tag in tag_hierarchy:
        # Get or create subtag.
        tag_name = tag_prefix + self._scrub_tag_name(sub_tag)
        tag = self._get_tag(tag_name)
        if not tag:
            tag = self._create_tag_instance(tag_name)
        # Set tag parent.
        tag.parent = parent_tag
        # Update parent and tag prefix.
        parent_tag = tag
        tag_prefix = tag.name + self.hierarchy_separator
    return tag


# Traceback (TypeError)
galaxy.web.framework.decorators ERROR 2021-02-23 12:24:13,429 [p:203,w:1,m:0] [uWSGIWorker1Core2] Uncaught exception in exposed API method:
Traceback (most recent call last):
File "lib/galaxy/web/framework/decorators.py", line 305, in decorator
rval = func(self, trans, *args, **kwargs)
File "lib/galaxy/webapps/galaxy/api/histories.py", line 471, in update
self.deserializer.deserialize(history, payload, user=trans.user, trans=trans)
File "lib/galaxy/managers/base.py", line 741, in deserialize
new_dict[key] = self.deserializers[key](item, key, val, **context)
File "lib/galaxy/managers/taggable.py", line 93, in deserialize_tags
_tags_from_strings(item, self.app.tag_handler, new_tags_list, user=user)
File "lib/galaxy/managers/taggable.py", line 44, in _tags_from_strings
tag_handler.apply_item_tags(user, item, unicodify(new_tags_str, 'utf-8'))
File "lib/galaxy/model/tags.py", line 193, in apply_item_tags
self.apply_item_tag(user, item, name, value, flush=flush)
File "lib/galaxy/model/tags.py", line 165, in apply_item_tag
tag = self._get_or_create_tag(lc_name)
File "lib/galaxy/model/tags.py", line 253, in _get_or_create_tag
tag = self._create_tag(scrubbed_tag_str)
File "lib/galaxy/model/tags.py", line 226, in _create_tag
tag_name = tag_prefix + self._scrub_tag_name(sub_tag)
TypeError: must be str, not NoneType

# Fixed code
def _create_tag(self, tag_str: str):
    """Create a Tag object from a tag string."""
    tag_hierarchy = tag_str.split(self.hierarchy_separator)
    tag_prefix = ""
    parent_tag = None
    tag = None
    for sub_tag in tag_hierarchy:
        # Get or create subtag.
        sub_tag_name = self._scrub_tag_name(sub_tag)
        if sub_tag_name:
            tag_name = tag_prefix + sub_tag_name
            tag = self._get_tag(tag_name)
            if not tag:
                tag = self._create_tag_instance(tag_name)
            # Set tag parent.
            tag.parent = parent_tag
            # Update parent and tag prefix.
            parent_tag = tag
            tag_prefix = tag.name + self.hierarchy_separator
    return tag
# Buggy code
def cached_container_description(self, targets, namespace, hash_func, resolution_cache):
    return docker_cached_container_description(
        targets, namespace, hash_func, resolution_cache
    )


# Traceback (FileNotFoundError)
urllib3.connectionpool DEBUG 2021-01-13 15:26:00,421 https://quay.io:443 "GET /api/v1/repository/biocontainers/porechop HTTP/1.1" 200 4033
galaxy.tool_util.deps.containers ERROR 2021-01-13 15:26:00,499 Could not get container description for tool 'toolshed.g2.bx.psu.edu/repos/iuc/porechop/porechop/0.2.3'
Traceback (most recent call last):
File "/galaxy/server/lib/galaxy/tool_util/deps/containers.py", line 243, in find_best_container_description
resolved_container_description = self.resolve(enabled_container_types, tool_info, **kwds)
File "/galaxy/server/lib/galaxy/tool_util/deps/containers.py", line 265, in resolve
container_description = container_resolver.resolve(enabled_container_types, tool_info, install=install, resolution_cache=resolution_cache, session=session)
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 410, in resolve
if install and not self.cached_container_description(
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 385, in cached_container_description
return docker_cached_container_description(targets, namespace, hash_func, resolution_cache)
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 202, in docker_cached_container_description
cached_images = list_docker_cached_mulled_images(namespace, hash_func=hash_func, resolution_cache=resolution_cache)
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 71, in list_docker_cached_mulled_images
images_and_versions = unicodify(subprocess.check_output(command)).strip().splitlines()
File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.8/subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'docker'

# Fixed code
def cached_container_description(self, targets, namespace, hash_func, resolution_cache):
    try:
        return docker_cached_container_description(
            targets, namespace, hash_func, resolution_cache
        )
    except subprocess.CalledProcessError:
        # We should only get here if a docker binary is available, but command quits with a non-zero exit code,
        # e.g if the docker daemon is not available
        log.exception(
            "An error occured while listing cached docker image. Docker daemon may need to be restarted."
        )
        return None
# Buggy code
def pull(self, container):
    command = container.build_pull_command()
    shell(command)


# Traceback (FileNotFoundError)
urllib3.connectionpool DEBUG 2021-01-13 15:26:00,421 https://quay.io:443 "GET /api/v1/repository/biocontainers/porechop HTTP/1.1" 200 4033
galaxy.tool_util.deps.containers ERROR 2021-01-13 15:26:00,499 Could not get container description for tool 'toolshed.g2.bx.psu.edu/repos/iuc/porechop/porechop/0.2.3'
Traceback (most recent call last):
File "/galaxy/server/lib/galaxy/tool_util/deps/containers.py", line 243, in find_best_container_description
resolved_container_description = self.resolve(enabled_container_types, tool_info, **kwds)
File "/galaxy/server/lib/galaxy/tool_util/deps/containers.py", line 265, in resolve
container_description = container_resolver.resolve(enabled_container_types, tool_info, install=install, resolution_cache=resolution_cache, session=session)
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 410, in resolve
if install and not self.cached_container_description(
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 385, in cached_container_description
return docker_cached_container_description(targets, namespace, hash_func, resolution_cache)
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 202, in docker_cached_container_description
cached_images = list_docker_cached_mulled_images(namespace, hash_func=hash_func, resolution_cache=resolution_cache)
File "/galaxy/server/lib/galaxy/tool_util/deps/container_resolvers/mulled.py", line 71, in list_docker_cached_mulled_images
images_and_versions = unicodify(subprocess.check_output(command)).strip().splitlines()
File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.8/subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'docker'

# Fixed code
def pull(self, container):
    if self.docker_cli_available:
        command = container.build_pull_command()
        shell(command)
# Buggy code
def parse_xml(file_name, check_exists=True):
    """Returns a parsed xml tree with comments intact."""
    error_message = ""
    if check_exists and not os.path.exists(file_name):
        return None, "File does not exist %s" % str(file_name)

    with open(file_name, "r") as fobj:
        try:
            tree = XmlET.parse(
                fobj, parser=XmlET.XMLParser(target=Py27CommentedTreeBuilder())
            )
        except Exception as e:
            error_message = "Exception attempting to parse %s: %s" % (
                str(file_name),
                str(e),
            )
            log.exception(error_message)
            return None, error_message
    return tree, error_message


# Traceback (xml.etree.ElementTree.ParseError)
tool_shed.util.xml_util ERROR 2019-09-12 19:47:44,334 [p:54106,w:1,m:0] [uWSGIWorker1Core1] Exception attempting to parse GLXFOLDER/tool-data/TOOLSHED/repos/USER/REPO/REVISION/tool_data_table_conf.xml: multiple elements on top level
Traceback (most recent call last):
File "lib/tool_shed/util/xml_util.py", line 87, in parse_xml
tree = XmlET.parse(fobj, parser=XmlET.XMLParser(target=Py27CommentedTreeBuilder()))
File "PYTHON3.7/lib/python3.7/xml/etree/ElementTree.py", line 1197, in parse
tree.parse(source, parser)
File "PYTHON3.7/lib/python3.7/xml/etree/ElementTree.py", line 604, in parse
parser.feed(data)
File "<string>", line None
xml.etree.ElementTree.ParseError: multiple elements on top level

# Fixed code
def parse_xml(file_name, check_exists=True):
    """Returns a parsed xml tree with comments intact."""
    error_message = ""
    if check_exists and not os.path.exists(file_name):
        return None, "File does not exist %s" % str(file_name)

    with open(file_name, "r") as fobj:
        try:
            tree = XmlET.parse(
                fobj, parser=XmlET.XMLParser(target=CommentedTreeBuilder())
            )
        except Exception as e:
            error_message = "Exception attempting to parse %s: %s" % (
                str(file_name),
                str(e),
            )
            log.exception(error_message)
            return None, error_message
    return tree, error_message
# Buggy code
def comment(self, data):
    self.start(XmlET.Comment, {})
    self.data(data)
    self.end(XmlET.Comment)


# Traceback (xml.etree.ElementTree.ParseError)
tool_shed.util.xml_util ERROR 2019-09-12 19:47:44,334 [p:54106,w:1,m:0] [uWSGIWorker1Core1] Exception attempting to parse GLXFOLDER/tool-data/TOOLSHED/repos/USER/REPO/REVISION/tool_data_table_conf.xml: multiple elements on top level
Traceback (most recent call last):
File "lib/tool_shed/util/xml_util.py", line 87, in parse_xml
tree = XmlET.parse(fobj, parser=XmlET.XMLParser(target=Py27CommentedTreeBuilder()))
File "PYTHON3.7/lib/python3.7/xml/etree/ElementTree.py", line 1197, in parse
tree.parse(source, parser)
File "PYTHON3.7/lib/python3.7/xml/etree/ElementTree.py", line 604, in parse
parser.feed(data)
File "<string>", line None
xml.etree.ElementTree.ParseError: multiple elements on top level

# Fixed code
def comment(self, data):
    if self.non_comment_seen:
        # Cannot start XML file with comment
        self.start(XmlET.Comment, {})
        self.data(data)
        self.end(XmlET.Comment)
# Buggy code
def _xml_replace(query, targets, parent_map):
    # parent_el = query.find('..') ## Something like this would be better with newer xml library
    parent_el = parent_map[query]
    matching_index = -1
    # for index, el in enumerate(parent_el.iter('.')):  ## Something like this for newer implementation
    for index, el in enumerate(list(parent_el)):
        if el == query:
            matching_index = index
            break
    assert matching_index >= 0
    current_index = matching_index
    for target in targets:
        current_index += 1
        parent_el.insert(current_index, target)
    parent_el.remove(query)


# Traceback (AssertionError)
galaxy.tools.toolbox.base ERROR 2019-10-15 10:55:57,876 Failed to load potential tool /Users/scholtalbers/workspace/je-suite/src/galaxy/je-clip.xml.
Traceback (most recent call last):
File "/private/var/folders/cf/k7c5rjhj1sggk6x8z1jnw4b80000gp/T/tmpFw8KvW/galaxy-dev/lib/galaxy/tools/toolbox/base.py", line 772, in quick_load
tool = self.load_tool(tool_file)
File "/private/var/folders/cf/k7c5rjhj1sggk6x8z1jnw4b80000gp/T/tmpFw8KvW/galaxy-dev/lib/galaxy/tools/toolbox/base.py", line 808, in load_tool
tool = self.create_tool(config_file=config_file, tool_shed_repository=tool_shed_repository, guid=guid, **kwds)
File "/private/var/folders/cf/k7c5rjhj1sggk6x8z1jnw4b80000gp/T/tmpFw8KvW/galaxy-dev/lib/galaxy/tools/__init__.py", line 274, in create_tool
raise e
AssertionError
galaxy.tools.toolbox.base ERROR 2019-10-15 10:55:57,887 Failed to load potential tool /Users/scholtalbers/workspace/je-suite/src/galaxy/je-demultiplex.xml.
Traceback (most recent call last):
File "/private/var/folders/cf/k7c5rjhj1sggk6x8z1jnw4b80000gp/T/tmpFw8KvW/galaxy-dev/lib/galaxy/tools/toolbox/base.py", line 772, in quick_load
tool = self.load_tool(tool_file)
File "/private/var/folders/cf/k7c5rjhj1sggk6x8z1jnw4b80000gp/T/tmpFw8KvW/galaxy-dev/lib/galaxy/tools/toolbox/base.py", line 808, in load_tool
tool = self.create_tool(config_file=config_file, tool_shed_repository=tool_shed_repository, guid=guid, **kwds)
File "/private/var/folders/cf/k7c5rjhj1sggk6x8z1jnw4b80000gp/T/tmpFw8KvW/galaxy-dev/lib/galaxy/tools/__init__.py", line 274, in create_tool
raise e
AssertionError

# Fixed code
def _xml_replace(query, targets, parent_map):
    # parent_el = query.find('..') ## Something like this would be better with newer xml library
    parent_el = parent_map[query]
    matching_index = -1
    # for index, el in enumerate(parent_el.iter('.')):  ## Something like this for newer implementation
    for index, el in enumerate(list(parent_el)):
        if el == query:
            matching_index = index
            break
    assert matching_index >= 0
    current_index = matching_index
    for target in targets:
        current_index += 1
        parent_el.insert(current_index, deepcopy(target))
    parent_el.remove(query)
# Buggy code
def __init__(self, **kwd):
    Binary.__init__(self, **kwd)

    """The header file. Provides information about dimensions, identification, and processing history."""
    self.add_composite_file(
        "hdr", description="The Analyze75 header file.", is_binary=False
    )

    """The image file.  Image data, whose data type and ordering are described by the header file."""
    self.add_composite_file(
        "img", description="The Analyze75 image file.", is_binary=True
    )

    """The optional t2m file."""
    self.add_composite_file(
        "t2m", description="The Analyze75 t2m file.", optional="True", is_binary=True
    )


# Traceback (UnicodeDecodeError)
Fatal error: Exit code 1 ()
Traceback (most recent call last):
File "/cvmfs/main.galaxyproject.org/galaxy/tools/data_source/upload.py", line 329, in <module>
__main__()
File "/cvmfs/main.galaxyproject.org/galaxy/tools/data_source/upload.py", line 320, in __main__
metadata.append(add_composite_file(dataset, registry, output_path, files_path))
File "/cvmfs/main.galaxyproject.org/galaxy/tools/data_source/upload.py", line 243, in add_composite_file
stage_file(name, composite_file_path, value.is_binary)
File "/cvmfs/main.galaxyproject.org/galaxy/tools/data_source/upload.py", line 223, in stage_file
sniff.convert_newlines(dp, tmp_dir=tmpdir, tmp_prefix=tmp_prefix)
File "/cvmfs/main.galaxyproject.org/galaxy/lib/galaxy/datatypes/sniff.py", line 122, in convert_newlines
for i, line in enumerate(io.open(fname, mode="U", encoding='utf-8')):
File "/cvmfs/main.galaxyproject.org/venv/lib/python2.7/codecs.py", line 314, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte

# Fixed code
def __init__(self, **kwd):
    Binary.__init__(self, **kwd)

    """The header file. Provides information about dimensions, identification, and processing history."""
    self.add_composite_file(
        "hdr", description="The Analyze75 header file.", is_binary=True
    )

    """The image file.  Image data, whose data type and ordering are described by the header file."""
    self.add_composite_file(
        "img", description="The Analyze75 image file.", is_binary=True
    )

    """The optional t2m file."""
    self.add_composite_file(
        "t2m", description="The Analyze75 t2m file.", optional=True, is_binary=True
    )
# Buggy code
def tool_shed_repositories(self):
    try:
        repositories = self.cache.repositories
    except AttributeError:
        self.rebuild()
        repositories = self.cache.repositories
    if repositories and not repositories[0]._sa_instance_state._attached:
        self.rebuild()
        repositories = self.cache.repositories
    return repositories


# Traceback (AttributeError)
galaxy.tools.toolbox.base ERROR 2019-05-21 18:57:13,924 [p:1,w:0,m:0] [MainThread] Error reading tool from path: toolshed.g2.bx.psu.edu/repos/devteam/sam_pileup/890d97772e2a/sam_pileup/sam_pileup.xml
Traceback (most recent call last):
File "/galaxy/server/lib/galaxy/tools/toolbox/base.py", line 605, in _load_tool_tag_set
tool_shed_repository = self.get_tool_repository_from_xml_item(item, path)
File "/galaxy/server/lib/galaxy/tools/toolbox/base.py", line 652, in get_tool_repository_from_xml_item
installed_changeset_revision=installed_changeset_revision)
File "/galaxy/server/lib/galaxy/tools/__init__.py", line 339, in _get_tool_shed_repository
installed_changeset_revision=installed_changeset_revision
File "/galaxy/server/lib/tool_shed/util/repository_util.py", line 374, in get_installed_repository
repository_id=repository_id)
File "/galaxy/server/lib/galaxy/tools/cache.py", line 165, in get_installed_repository
repository_id=repository_id)
File "/galaxy/server/lib/galaxy/tools/cache.py", line 182, in _get_installed_repository
repos = [repo for repo in self.tool_shed_repositories if repo.tool_shed == tool_shed and repo.owner == owner and repo.name == name]
File "/galaxy/server/lib/galaxy/tools/cache.py", line 150, in tool_shed_repositories
if repositories and not repositories[0]._sa_instance_state._attached:
AttributeError: 'ToolConfRepository' object has no attribute '_sa_instance_state'

# Fixed code
def tool_shed_repositories(self):
    try:
        repositories = self.cache.repositories
    except AttributeError:
        self.rebuild()
        repositories = self.cache.repositories
    tool_shed_repositories = [
        repo
        for repo in repositories
        if isinstance(repo, self.app.install_model.ToolShedRepository)
    ]
    if tool_shed_repositories and inspect(tool_shed_repositories[0]).detached:
        self.rebuild()
        repositories = self.cache.repositories
    return repositories
# Buggy code
def resend_verification(self, trans):
    """
    Exposed function for use outside of the class. E.g. when user click on the resend link in the masthead.
    """
    message, status = self.resend_activation_email(trans, None, None)
    if status == "done":
        return trans.show_ok_message(message)
    else:
        return trans.show_error_message(message)


# Traceback (AttributeError)
Traceback (most recent call last):
File "lib/galaxy/web/framework/decorators.py", line 283, in decorator
rval = func(self, trans, *args, **kwargs)
File "lib/galaxy/webapps/galaxy/controllers/user.py", line 114, in login
return self.__validate_login(trans, payload, **kwd)
File "lib/galaxy/webapps/galaxy/controllers/user.py", line 135, in __validate_login
message, status, user, success = self.__autoregistration(trans, login, password, status, kwd)
File "lib/galaxy/webapps/galaxy/controllers/user.py", line 90, in __autoregistration
message, status, user, success = self.__register(trans, **kwd)
AttributeError: 'User' object has no attribute '_User__register'

# Fixed code
def resend_verification(self, trans):
    """
    Exposed function for use outside of the class. E.g. when user click on the resend link in the masthead.
    """
    message, status = self.resend_activation_email(trans, None, None)
    if status:
        return trans.show_ok_message(message)
    else:
        return trans.show_error_message(message)
# Buggy code
def create(self, trans, payload={}, **kwd):
    if not payload:
        payload = kwd
    message = trans.check_csrf_token(payload)
    if message:
        return self.message_exception(trans, message)
    user, message = self.user_manager.register(trans, **payload)
    if message:
        return self.message_exception(trans, message, sanitize=False)
    elif user and not trans.user_is_admin:
        trans.handle_user_login(user)
        trans.log_event("User created a new account")
        trans.log_event("User logged in")
    return {"message": "Success."}


# Traceback (AttributeError)
Traceback (most recent call last):
File "lib/galaxy/web/framework/decorators.py", line 283, in decorator
rval = func(self, trans, *args, **kwargs)
File "lib/galaxy/webapps/galaxy/controllers/user.py", line 114, in login
return self.__validate_login(trans, payload, **kwd)
File "lib/galaxy/webapps/galaxy/controllers/user.py", line 135, in __validate_login
message, status, user, success = self.__autoregistration(trans, login, password, status, kwd)
File "lib/galaxy/webapps/galaxy/controllers/user.py", line 90, in __autoregistration
message, status, user, success = self.__register(trans, **kwd)
AttributeError: 'User' object has no attribute '_User__register'

# Fixed code
def create(self, trans, payload={}, **kwd):
    if not payload:
        payload = kwd
    message = trans.check_csrf_token(payload)
    if message:
        return self.message_exception(trans, message)
    user, message = self.user_manager.register(
        trans, **_filtered_registration_params_dict(payload)
    )
    if message:
        return self.message_exception(trans, message, sanitize=False)
    elif user and not trans.user_is_admin:
        trans.handle_user_login(user)
        trans.log_event("User created a new account")
        trans.log_event("User logged in")
    return {"message": "Success."}
# Buggy code
def url_get(base_url, password_mgr=None, pathspec=None, params=None):
    """Make contact with the uri provided and return any contents."""
    # Uses system proxy settings if they exist.
    proxy = urlrequest.ProxyHandler()
    if password_mgr is not None:
        auth = urlrequest.HTTPDigestAuthHandler(password_mgr)
        urlopener = urlrequest.build_opener(proxy, auth)
    else:
        urlopener = urlrequest.build_opener(proxy)
    urlrequest.install_opener(urlopener)
    full_url = build_url(base_url, pathspec=pathspec, params=params)
    response = urlopener.open(full_url)
    content = response.read()
    response.close()
    return content


# Traceback (TypeError)
Traceback (most recent call last):
File "lib/galaxy/web/framework/middleware/error.py", line 154, in __call__
app_iter = self.application(environ, sr_checker)
File "/home/nate/work/galaxy2/.venv/lib/python3.5/site-packages/paste/recursive.py", line 85, in __call__
return self.application(environ, start_response)
File "/home/nate/work/galaxy2/.venv/lib/python3.5/site-packages/paste/httpexceptions.py", line 640, in __call__
return self.application(environ, start_response)
File "lib/galaxy/web/framework/base.py", line 143, in __call__
return self.handle_request(environ, start_response)
File "lib/galaxy/web/framework/base.py", line 222, in handle_request
body = method(trans, **kwargs)
File "lib/galaxy/web/framework/decorators.py", line 101, in decorator
return func(self, trans, *args, **kwargs)
File "lib/galaxy/webapps/galaxy/controllers/admin_toolshed.py", line 892, in prepare_for_install
repo_information_dict = json.loads(raw_text)
File "/usr/lib/python3.5/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

# Fixed code
def url_get(base_url, password_mgr=None, pathspec=None, params=None):
    """Make contact with the uri provided and return any contents."""
    # Uses system proxy settings if they exist.
    proxy = urlrequest.ProxyHandler()
    if password_mgr is not None:
        auth = urlrequest.HTTPDigestAuthHandler(password_mgr)
        urlopener = urlrequest.build_opener(proxy, auth)
    else:
        urlopener = urlrequest.build_opener(proxy)
    urlrequest.install_opener(urlopener)
    full_url = build_url(base_url, pathspec=pathspec, params=params)
    response = urlopener.open(full_url)
    content = response.read()
    response.close()
    return unicodify(content)
# Buggy code
def __int__(self):
    return int(str(self))


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/local/galaxy/galaxy-dist/lib/galaxy/jobs/runners/__init__.py", line 163, in prepare_job
job_wrapper.prepare()
File "/usr/local/galaxy/galaxy-dist/lib/galaxy/jobs/__init__.py", line 862, in prepare
self.command_line, self.extra_filenames, self.environment_variables = tool_evaluator.build()
File "/usr/local/galaxy/galaxy-dist/lib/galaxy/tools/evaluation.py", line 422, in build
raise e
ValueError: invalid literal for int() with base 10: '-1.0'

# Fixed code
def __int__(self):
    return int(float(self))
# Buggy code
def execute(
    self,
    cmd,
    persist=False,
    timeout=DEFAULT_TIMEOUT,
    timeout_check_interval=DEFAULT_TIMEOUT_CHECK_INTERVAL,
    **kwds,
):
    outf = TemporaryFile()
    p = Popen(cmd, stdin=None, stdout=outf, stderr=PIPE)
    # poll until timeout

    for i in range(int(timeout / timeout_check_interval)):
        sleep(0.1)  # For fast returning commands
        r = p.poll()
        if r is not None:
            break
        sleep(timeout_check_interval)
    else:
        kill_pid(p.pid)
        return Bunch(
            stdout="", stderr=TIMEOUT_ERROR_MESSAGE, returncode=TIMEOUT_RETURN_CODE
        )
    outf.seek(0)
    return Bunch(
        stdout=_read_str(outf), stderr=_read_str(p.stderr), returncode=p.returncode
    )


# Traceback (OSError)
galaxy.jobs.runners.cli DEBUG 2019-01-25 19:13:53,789 [p:3868,w:1,m:0] [ShellRunner.work_thread-0] (5) submitting file: /opt/galaxy/database/jobs_directory/000/5/galaxy_5.s
h
galaxy.jobs.runners ERROR 2019-01-25 19:13:53,964 [p:3868,w:1,m:0] [ShellRunner.work_thread-0] (5) Unhandled exception calling queue_job
Traceback (most recent call last):
File "lib/galaxy/jobs/runners/__init__.py", line 113, in run_next
method(arg)
File "lib/galaxy/jobs/runners/cli.py", line 98, in queue_job
returncode, stdout = self.submit(shell, job_interface, ajs.job_file, galaxy_id_tag, retry=MAX_SUBMIT_RETRY)
File "lib/galaxy/jobs/runners/cli.py", line 130, in submit
cmd_out = shell.execute(job_interface.submit(job_file))
File "lib/galaxy/jobs/runners/util/cli/shell/local.py", line 47, in execute
p = Popen(cmd, stdin=None, stdout=outf, stderr=PIPE)
File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

# Fixed code
def execute(
    self,
    cmd,
    persist=False,
    timeout=DEFAULT_TIMEOUT,
    timeout_check_interval=DEFAULT_TIMEOUT_CHECK_INTERVAL,
    **kwds,
):
    is_cmd_string = isinstance(cmd, six.string_types)
    outf = TemporaryFile()
    p = Popen(cmd, stdin=None, stdout=outf, stderr=PIPE, shell=is_cmd_string)
    # poll until timeout

    for i in range(int(timeout / timeout_check_interval)):
        sleep(0.1)  # For fast returning commands
        r = p.poll()
        if r is not None:
            break
        sleep(timeout_check_interval)
    else:
        kill_pid(p.pid)
        return Bunch(
            stdout="", stderr=TIMEOUT_ERROR_MESSAGE, returncode=TIMEOUT_RETURN_CODE
        )
    outf.seek(0)
    return Bunch(
        stdout=_read_str(outf), stderr=_read_str(p.stderr), returncode=p.returncode
    )
# Buggy code
def top_level_workflow(self):
    """If this workflow is not attached to stored workflow directly,
    recursively grab its parents until it is the top level workflow
    which must have a stored workflow associated with it.
    """
    top_level_workflow = self
    if self.stored_workflow is None:
        # TODO: enforce this at creation...
        assert len(self.parent_workflow_steps) == 1
        return self.parent_workflow_steps[0].workflow.top_level_workflow
    return top_level_workflow


# Traceback (AssertionError)
Traceback (most recent call last):
File "/Users/mvandenb/src/galaxy/lib/galaxy/web/framework/decorators.py", line 283, in decorator
rval = func(self, trans, *args, **kwargs)
File "/Users/mvandenb/src/galaxy/lib/galaxy/webapps/galaxy/api/workflows.py", line 545, in update
**from_dict_kwds
File "/Users/mvandenb/src/galaxy/lib/galaxy/managers/workflows.py", line 362, in update_workflow_from_raw_description
**kwds
File "/Users/mvandenb/src/galaxy/lib/galaxy/managers/workflows.py", line 417, in _workflow_from_raw_description
self.__load_subworkflows(trans, step_dict, subworkflow_id_map, **kwds)
File "/Users/mvandenb/src/galaxy/lib/galaxy/managers/workflows.py", line 1069, in __load_subworkflows
trans, step_dict, subworkflow_id_map, **kwds
File "/Users/mvandenb/src/galaxy/lib/galaxy/managers/workflows.py", line 1151, in __load_subworkflow_from_step_dict
trans, subworkflow_id
File "/Users/mvandenb/src/galaxy/lib/galaxy/managers/workflows.py", line 105, in get_owned_workflow
self.check_security(trans, workflow, check_ownership=True)
File "/Users/mvandenb/src/galaxy/lib/galaxy/managers/workflows.py", line 128, in check_security
stored_workflow = has_workflow.top_level_stored_workflow
File "/Users/mvandenb/src/galaxy/lib/galaxy/model/__init__.py", line 4063, in top_level_stored_workflow
return self.top_level_workflow.stored_workflow
File "/Users/mvandenb/src/galaxy/lib/galaxy/model/__init__.py", line 4052, in top_level_workflow
assert len(self.parent_workflow_steps) == 1
AssertionError

# Fixed code
def top_level_workflow(self):
    """If this workflow is not attached to stored workflow directly,
    recursively grab its parents until it is the top level workflow
    which must have a stored workflow associated with it.
    """
    top_level_workflow = self
    if self.stored_workflow is None:
        # TODO: enforce this at creation...
        assert len(set(w.uuid for w in self.parent_workflow_steps)) == 1
        return self.parent_workflow_steps[0].workflow.top_level_workflow
    return top_level_workflow
# Buggy code
def update_permissions(self, trans, dataset_id, payload, **kwd):
    """
    PUT /api/datasets/{encoded_dataset_id}/permissions
    Updates permissions of a dataset.

    :rtype:     dict
    :returns:   dictionary containing new permissions
    """
    if payload:
        kwd.update(payload)
    hda_ldda = kwd.get("hda_ldda", "hda")
    dataset_assoc = self.get_hda_or_ldda(
        trans, hda_ldda=hda_ldda, dataset_id=dataset_id
    )
    if hda_ldda == "hda":
        self.hda_manager.update_permissions(trans, dataset_assoc, **kwd)
        return self.hda_manager.serialize_dataset_association_roles(
            trans, dataset_assoc
        )
    else:
        self.ldda_manager.update_permissions(trans, dataset_assoc, **kwd)
        return self.hda_manager.serialize_dataset_association_roles(
            trans, dataset_assoc
        )


# Traceback (AttributeError)
Traceback (most recent call last):
File "lib/galaxy/web/framework/decorators.py", line 283, in decorator    rval = func(self, trans, *args, **kwargs)  File "lib/galaxy/webapps/galaxy/api/library_datasets.py", line 125, in show_roles    return self._get_current_roles(trans, library_dataset)
File "lib/galaxy/webapps/galaxy/api/library_datasets.py", line 158, in _get_current_roles    return self.serialize_dataset_association_roles(library_dataset)AttributeError: 'LibraryDatasetsController' object has no attribute 'serialize_dataset_association_roles'

# Fixed code
def update_permissions(self, trans, dataset_id, payload, **kwd):
    """
    PUT /api/datasets/{encoded_dataset_id}/permissions
    Updates permissions of a dataset.

    :rtype:     dict
    :returns:   dictionary containing new permissions
    """
    if payload:
        kwd.update(payload)
    hda_ldda = kwd.get("hda_ldda", "hda")
    dataset_assoc = self.get_hda_or_ldda(
        trans, hda_ldda=hda_ldda, dataset_id=dataset_id
    )
    if hda_ldda == "hda":
        self.hda_manager.update_permissions(trans, dataset_assoc, **kwd)
        return self.hda_manager.serialize_dataset_association_roles(
            trans, dataset_assoc
        )
    else:
        self.ldda_manager.update_permissions(trans, dataset_assoc, **kwd)
        return self.ldda_manager.serialize_dataset_association_roles(
            trans, dataset_assoc
        )
# Buggy code
def _get_current_roles(self, trans, library_dataset):
    """
    Find all roles currently connected to relevant permissions
    on the library dataset and the underlying dataset.

    :param  library_dataset:      the model object
    :type   library_dataset:      LibraryDataset

    :rtype:     dictionary
    :returns:   dict of current roles for all available permission types
    """
    return self.serialize_dataset_association_roles(library_dataset)


# Traceback (AttributeError)
Traceback (most recent call last):
File "lib/galaxy/web/framework/decorators.py", line 283, in decorator    rval = func(self, trans, *args, **kwargs)  File "lib/galaxy/webapps/galaxy/api/library_datasets.py", line 125, in show_roles    return self._get_current_roles(trans, library_dataset)
File "lib/galaxy/webapps/galaxy/api/library_datasets.py", line 158, in _get_current_roles    return self.serialize_dataset_association_roles(library_dataset)AttributeError: 'LibraryDatasetsController' object has no attribute 'serialize_dataset_association_roles'

# Fixed code
def _get_current_roles(self, trans, library_dataset):
    """
    Find all roles currently connected to relevant permissions
    on the library dataset and the underlying dataset.

    :param  library_dataset:      the model object
    :type   library_dataset:      LibraryDataset

    :rtype:     dictionary
    :returns:   dict of current roles for all available permission types
    """
    return self.ldda_manager.serialize_dataset_association_roles(trans, library_dataset)
# Buggy code
def process_key(incoming_key, d):
    key_parts = incoming_key.split("|")
    if len(key_parts) == 1:
        # Regular parameter
        d[incoming_key] = object()
    elif key_parts[0].rsplit("_", 1)[-1].isdigit():
        # Repeat
        input_name_index = key_parts[0].rsplit("_", 1)
        input_name, index = input_name_index
        if input_name not in d:
            d[input_name] = []
        subdict = {}
        d[input_name].append(subdict)
        process_key("|".join(key_parts[1:]), d=subdict)
    else:
        # Section / Conditional
        input_name = key_parts[0]
        subdict = {}
        d[input_name] = subdict
        process_key("|".join(key_parts[1:]), d=subdict)


# Traceback (AttributeError)
Traceback (most recent call last):
File "lib/galaxy/web/framework/decorators.py", line 283, in decorator
rval = func(self, trans, *args, **kwargs)
File "lib/galaxy/webapps/galaxy/api/tools.py", line 418, in create
return self._create(trans, payload, **kwd)
File "lib/galaxy/webapps/galaxy/api/tools.py", line 476, in _create
vars = tool.handle_input(trans, incoming, history=target_history, use_cached_job=use_cached_job)
File "lib/galaxy/tools/__init__.py", line 1385, in handle_input
all_params, all_errors, rerun_remap_job_id, collection_info = self.expand_incoming(trans=trans, incoming=incoming, request_context=request_context)
File "lib/galaxy/tools/__init__.py", line 1340, in expand_incoming
expanded_incomings, collection_info = expand_meta_parameters(trans, self, incoming)
File "lib/galaxy/tools/parameters/meta.py", line 118, in expand_meta_parameters
process_key(incoming_key, d=nested_dict)
File "lib/galaxy/tools/parameters/meta.py", line 87, in process_key
d[input_name].append(subdict)
AttributeError: 'object' object has no attribute 'append'

# Fixed code
def process_key(incoming_key, incoming_value, d):
    key_parts = incoming_key.split("|")
    if len(key_parts) == 1:
        # Regular parameter
        d[incoming_key] = incoming_value
    elif key_parts[0].rsplit("_", 1)[-1].isdigit():
        # Repeat
        input_name_index = key_parts[0].rsplit("_", 1)
        input_name, index = input_name_index
        index = int(index)
        if input_name not in d:
            d[input_name] = []
        if len(d[input_name]) > index:
            subdict = d[input_name][index]
        else:
            subdict = {}
            d[input_name].append(subdict)
        process_key("|".join(key_parts[1:]), incoming_value=incoming_value, d=subdict)
    else:
        # Section / Conditional
        input_name = key_parts[0]
        subdict = {}
        d[input_name] = subdict
        process_key("|".join(key_parts[1:]), incoming_value=incoming_value, d=subdict)
# Buggy code
def get_private_user_role(self, user, auto_create=False):
    role = (
        self.sa_session.query(self.model.Role)
        .filter(
            and_(
                self.model.Role.table.c.name == user.email,
                self.model.Role.table.c.type == self.model.Role.types.PRIVATE,
            )
        )
        .first()
    )
    if not role:
        if auto_create:
            return self.create_private_user_role(user)
        else:
            return None
    return role


# Traceback (AttributeError)
galaxy.web.framework.decorators ERROR 2018-09-21 22:02:02,371 [p:10163,w:3,m:0] [uWSGIWorker3Core1] Uncaught exception in exposed API method:
Traceback (most recent call last):
File "/work/project/w4m/galaxy4metabolomics/galaxy/lib/galaxy/web/framework/decorators.py", line 154, in decorator
rval = func(self, trans, *args, **kwargs)
File "/work/project/w4m/galaxy4metabolomics/galaxy/lib/galaxy/webapps/galaxy/controllers/dataset.py", line 282, in get_edit
all_roles = [(r.name, trans.security.encode_id(r.id)) for r in trans.app.security_agent.get_legitimate_roles(trans, data.dataset, 'root')]
File "/work/project/w4m/galaxy4metabolomics/galaxy/lib/galaxy/security/__init__.py", line 345, in get_legitimate_roles
return self.get_all_roles(trans, cntrller)
File "/work/project/w4m/galaxy4metabolomics/galaxy/lib/galaxy/security/__init__.py", line 211, in get_all_roles
return self.sort_by_attr([role for role in roles], 'name')
File "/work/project/w4m/galaxy4metabolomics/galaxy/lib/galaxy/security/__init__.py", line 177, in sort_by_attr
intermed = [(getattr(v, attr), i, v) for i, v in enumerate(seq)]
AttributeError: 'NoneType' object has no attribute 'name'

# Fixed code
def get_private_user_role(self, user, auto_create=False):
    role = (
        self.sa_session.query(self.model.Role)
        .filter(
            and_(
                self.model.UserRoleAssociation.table.c.user_id == user.id,
                self.model.Role.table.c.id
                == self.model.UserRoleAssociation.table.c.role_id,
                self.model.Role.table.c.type == self.model.Role.types.PRIVATE,
            )
        )
        .first()
    )
    if not role:
        if auto_create:
            return self.create_private_user_role(user)
        else:
            return None
    return role
# Buggy code
def __init__(self):
    self._hash_by_tool_paths = {}
    self._tools_by_path = {}
    self._tool_paths_by_id = {}
    self._macro_paths_by_id = {}
    self._tool_ids_by_macro_paths = {}
    self._mod_time_by_path = {}
    self._new_tool_ids = set()
    self._removed_tool_ids = set()


# Traceback (KeyError)
galaxy.tools.toolbox.base INFO 2018-08-09 10:57:04,513 Parsing the tool configuration /private/var/folders/df/6xqpqpcd7h73b6jpx9t6cwhw0000gn/T/tmpicezz6xb/tool_conf.xml
galaxy.tools.toolbox.base ERROR 2018-08-09 10:57:04,519 Error reading tool from path: /Users/mvandenb/src/tools-iuc/tools/fastp/fastp.xml
Traceback (most recent call last):
File "/private/var/folders/df/6xqpqpcd7h73b6jpx9t6cwhw0000gn/T/tmpicezz6xb/galaxy-dev/lib/galaxy/tools/toolbox/base.py", line 567, in _load_tool_tag_set
tool = self.load_tool(concrete_path, use_cached=False)
File "/private/var/folders/df/6xqpqpcd7h73b6jpx9t6cwhw0000gn/T/tmpicezz6xb/galaxy-dev/lib/galaxy/tools/toolbox/base.py", line 751, in load_tool
tool = self.create_tool(config_file=config_file, repository_id=repository_id, guid=guid, **kwds)
File "/private/var/folders/df/6xqpqpcd7h73b6jpx9t6cwhw0000gn/T/tmpicezz6xb/galaxy-dev/lib/galaxy/tools/__init__.py", line 270, in create_tool
raise e
KeyError: 'adapter_trimming_options'

# Fixed code
def __init__(self):
    self._hash_by_tool_paths = {}
    self._tools_by_path = {}
    self._tool_paths_by_id = {}
    self._macro_paths_by_id = {}
    self._tool_ids_by_macro_paths = {}
    self._mod_time_by_path = {}
    self._new_tool_ids = set()
    self._removed_tool_ids = set()
    self._removed_tools_by_path = {}