index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46,379 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 24,25 | 12,35 | to_dict | BaseField | 25,35 | 25,35 | class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("disabled", False)
if "optional" in kwds:
self.optional = asbool(kwds.get("optional"))
else:
... | class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("disabled", False)
if "optional" in kwds:
self.optional = asbool(kwds.get("optional"))
else:
... | return {
"name": self.name,
"label": self.label,
"disabled": self.disabled,
"optional": self.optional,
"value": self.value,
"help": self.help,
}
| return {
"name": self.name,
"label": self.label,
"disabled": self.disabled,
"optional": self.optional,
"value": self.value,
"help": self.help,
}
| 15 | 151 | 73 | 224 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,380 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 74,76 | 69,86 | is_checked | CheckboxField | 76,80 | 76,80 | class CheckboxField(BaseField):
"""
A checkbox (boolean input)
"""
@staticmethod
def is_checked(value):
FILL_FUNC_BODY def to_dict(self):
d = super().to_dict()
d["type"] = "boolean"
return d
| class CheckboxField(BaseField):
"""
A checkbox (boolean input)
"""
@staticmethod
def is_checked(value):
FILL_FUNC_BODY def to_dict(self):
d = super().to_dict()
d["type"] = "boolean"
return d
| if value in [True, "True", "true"]:
return True
return False
| if value in [True, "True", "true"]:
return True
return False
| 10 | 84 | 28 | 112 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,381 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 193,194 | 186,202 | to_dict | HistoryField | 194,202 | 194,202 | class HistoryField(BaseField):
def __init__(self, name, user=None, value=None, security=None, **kwds):
super().__init__(name, value, **kwds)
self.user = user
self.value = value
self.security = security
def to_dict(self):
FILL_FUNC_BODY | class HistoryField(BaseField):
def __init__(self, name, user=None, value=None, security=None, **kwds):
super().__init__(name, value, **kwds)
self.user = user
self.value = value
self.security = security
def to_dict(self):
FILL_FUNC_BODY | d = super().to_dict()
d["type"] = "select"
d["data"] = [{"label": "New History", "value": "new"}]
if self.user and self.security:
for a in self.user.histories:
if not a.deleted:
d["data"].append({"label": a.name, "value": self.security.enco... | d = super().to_dict()
d["type"] = "select"
d["data"] = [{"label": "New History", "value": "new"}]
if self.user and self.security:
for a in self.user.histories:
if not a.deleted:
d["data"].append({"label": a.name, "value": self.security.enco... | 30 | 90 | 116 | 206 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,382 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 51,52 | 46,57 | to_dict | PasswordField | 52,57 | 52,57 | class PasswordField(BaseField):
"""
A password input box. text appears as "******"
"""
def to_dict(self):
FILL_FUNC_BODY | class PasswordField(BaseField):
"""
A password input box. text appears as "******"
"""
def to_dict(self):
FILL_FUNC_BODY | d = super().to_dict()
d["type"] = "password"
return d
| d = super().to_dict()
d["type"] = "password"
return d
| 8 | 49 | 31 | 80 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,383 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 119,120 | 86,131 | to_dict | SelectField | 120,131 | 120,131 | class SelectField(BaseField):
"""
A select field.
"""
def __init__(
self,
name,
multiple=None,
display=None,
field_id=None,
value=None,
selectlist=None,
refresh_on_change=False,
**kwds,
):
super().__init__(name, value, ... | class SelectField(BaseField):
"""
A select field.
"""
def __init__(
self,
name,
multiple=None,
display=None,
field_id=None,
value=None,
selectlist=None,
refresh_on_change=False,
**kwds,
):
super().__init__(name, value, ... | d = super().to_dict()
d["type"] = "select"
d["display"] = self.display
d["multiple"] = self.multiple
d["data"] = []
for value in self.selectlist:
d["data"].append({"label": value, "value": value})
d["options"] = [{"label": t[0], "value": t[1]} for t in... | d = super().to_dict()
d["type"] = "select"
d["display"] = self.display
d["multiple"] = self.multiple
d["data"] = []
for value in self.selectlist:
d["data"].append({"label": value, "value": value})
d["options"] = [{"label": t[0], "value": t[1]} for t in... | 35 | 292 | 124 | 416 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,384 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 62,63 | 57,69 | to_dict | TextArea | 63,69 | 63,69 | class TextArea(BaseField):
"""
A standard text area box.
"""
def to_dict(self):
FILL_FUNC_BODY | class TextArea(BaseField):
"""
A standard text area box.
"""
def to_dict(self):
FILL_FUNC_BODY | d = super().to_dict()
d["type"] = "text"
d["area"] = True
return d
| d = super().to_dict()
d["type"] = "text"
d["area"] = True
return d
| 11 | 42 | 40 | 82 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,385 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 40,41 | 35,46 | to_dict | TextField | 41,46 | 41,46 | class TextField(BaseField):
"""
A standard text input box.
"""
def to_dict(self):
FILL_FUNC_BODY | class TextField(BaseField):
"""
A standard text input box.
"""
def to_dict(self):
FILL_FUNC_BODY | d = super().to_dict()
d["type"] = "text"
return d
| d = super().to_dict()
d["type"] = "text"
return d
| 8 | 42 | 31 | 73 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,386 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/form_builder.py | 169,170 | 162,180 | to_dict | WorkflowField | 170,180 | 170,180 | class WorkflowField(BaseField):
def __init__(self, name, user=None, value=None, security=None, **kwds):
super().__init__(name, value, **kwds)
self.user = user
self.value = value
self.security = security
def to_dict(self):
FILL_FUNC_BODY | class WorkflowField(BaseField):
def __init__(self, name, user=None, value=None, security=None, **kwds):
super().__init__(name, value, **kwds)
self.user = user
self.value = value
self.security = security
def to_dict(self):
FILL_FUNC_BODY | d = super().to_dict()
d["type"] = "select"
d["data"] = []
if self.user and self.security:
for a in self.user.stored_workflows:
if not a.deleted:
d["data"].append({"label": a.name, "value": self.security.encode_id(a.id)})
return d
| d = super().to_dict()
d["type"] = "select"
d["data"] = []
if self.user and self.security:
for a in self.user.stored_workflows:
if not a.deleted:
d["data"].append({"label": a.name, "value": self.security.encode_id(a.id)})
return d
| 26 | 91 | 110 | 201 | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... | """
Classes for generating HTML forms
"""
import logging
from galaxy.util import asbool
log = logging.getLogger(__name__)
class BaseField:
def __init__(self, name, value=None, label=None, **kwds):
self.name = name
self.label = label
self.value = value
self.disabled = kwds.get("d... |
46,387 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/hash_util.py | 60,66 | 1,167 | memory_bound_hexdigest | 66,85 | 66,85 | """
Utility functions for bi-directional Python version compatibility. Python 2.5
introduced hashlib which replaced sha in Python 2.4 and previous versions.
"""
import hashlib
import hmac
import logging
import os
from enum import Enum
from typing import (
Any,
Callable,
Dict,
List,
Optional,
T... | """
Utility functions for bi-directional Python version compatibility. Python 2.5
introduced hashlib which replaced sha in Python 2.4 and previous versions.
"""
import hashlib
import hmac
import logging
import os
from enum import Enum
from typing import (
Any,
Callable,
Dict,
List,
Optional,
T... | if hash_func is None:
assert hash_func_name is not None
hash_func = HASH_NAME_MAP[hash_func_name]
hasher = hash_func()
if file is None:
assert path is not None
file = open(path, "rb")
else:
assert path is None, "Cannot specify path and path keyword arguments."
... | if hash_func is None:
assert hash_func_name is not None
hash_func = HASH_NAME_MAP[hash_func_name]
hasher = hash_func()
if file is None:
assert path is not None
file = open(path, "rb")
else:
assert path is None, "Cannot specify path and path keyword arguments."
... | 52 | 1,366 | 170 | 1,536 | """
Utility functions for bi-directional Python version compatibility. Python 2.5
introduced hashlib which replaced sha in Python 2.4 and previous versions.
"""
import hashlib
import hmac
import logging
import os
from enum import Enum
from typing import (
Any,
Callable,
Dict,
List,
Optional,
T... | """
Utility functions for bi-directional Python version compatibility. Python 2.5
introduced hashlib which replaced sha in Python 2.4 and previous versions.
"""
import hashlib
import hmac
import logging
import os
from enum import Enum
from typing import (
Any,
Callable,
Dict,
List,
Optional,
T... | |
46,390 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/image_util.py | 18,19 | 1,41 | image_type | 19,36 | 19,36 | """Provides utilities for working with image files."""
import imghdr
import logging
from typing import (
List,
Optional,
)
try:
from PIL import Image
except ImportError:
Image = None # type: ignore[assignment, unused-ignore]
log = logging.getLogger(__name__)
def image_type(filename: str) -> Option... | """Provides utilities for working with image files."""
import imghdr
import logging
from typing import (
List,
Optional,
)
try:
from PIL import Image
except ImportError:
Image = None # type: ignore[assignment, unused-ignore]
log = logging.getLogger(__name__)
def image_type(filename: str) -> Option... | fmt = None
if Image is not None:
try:
with Image.open(filename) as im:
fmt = im.format
except Exception:
# We continue to try with imghdr, so this is a rare case of an
# exception we expect to happen frequently, so we're not logging
... | fmt = None
if Image is not None:
try:
with Image.open(filename) as im:
fmt = im.format
except Exception:
# We continue to try with imghdr, so this is a rare case of an
# exception we expect to happen frequently, so we're not logging
... | 58 | 156 | 137 | 293 | """Provides utilities for working with image files."""
import imghdr
import logging
from typing import (
List,
Optional,
)
try:
from PIL import Image
except ImportError:
Image = None # type: ignore[assignment, unused-ignore]
log = logging.getLogger(__name__)
def image_type(filename: str) -> Option... | """Provides utilities for working with image files."""
import imghdr
import logging
from typing import (
List,
Optional,
)
try:
from PIL import Image
except ImportError:
Image = None # type: ignore[assignment, unused-ignore]
log = logging.getLogger(__name__)
def image_type(filename: str) -> Option... | |
46,391 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/inflection.py | 85,86 | 13,143 | pluralize | Inflector | 87,89 | 86,89 | class Inflector:
"""
Inflector for pluralizing and singularizing English nouns.
"""
# This is a small subset of words that either have the same singular and plural form, or have no singular form
NONCHANGING_WORDS = {
"equipment",
"information",
"rice",
"money",
... | class Inflector:
"""
Inflector for pluralizing and singularizing English nouns.
"""
# This is a small subset of words that either have the same singular and plural form, or have no singular form
NONCHANGING_WORDS = {
"equipment",
"information",
"rice",
"money",
... | return self._transform(self.PLURALIZE_RULES, word)
| """Pluralizes nouns."""
return self._transform(self.PLURALIZE_RULES, word)
| 3 | 1,793 | 24 | 1,817 | #!/usr/bin/env python
# Copyright (c) 2006 Bermi Ferrer Martinez
#
# bermi a-t bermilabs - com
# See the end of this file for the free software, open source license (BSD-style).
#
# Modified by the Galaxy team.
import re
class Inflector:
"""
Inflector for pluralizing and singularizing English nouns.
"""... | #!/usr/bin/env python
# Copyright (c) 2006 Bermi Ferrer Martinez
#
# bermi a-t bermilabs - com
# See the end of this file for the free software, open source license (BSD-style).
#
# Modified by the Galaxy team.
import re
class Inflector:
"""
Inflector for pluralizing and singularizing English nouns.
"""... |
46,393 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/jstree.py | 131,132 | 93,153 | pretty | JSTree | 136,145 | 132,145 | class JSTree(dictobj.DictionaryObject):
"""
An immutable dictionary-like object that converts a list of "paths"
into a tree structure suitable for jQuery's jsTree.
"""
def __init__(self, paths, **kwargs):
"""
Take a list of paths and put them into a tree. Paths with the same prefix... | class JSTree(dictobj.DictionaryObject):
"""
An immutable dictionary-like object that converts a list of "paths"
into a tree structure suitable for jQuery's jsTree.
"""
def __init__(self, paths, **kwargs):
"""
Take a list of paths and put them into a tree. Paths with the same prefix... | if root is None:
root = self._root
fmt = "%s%s/" if root.children else "%s%s"
s = fmt % (" " * depth * spacing, root.text)
for child in root.children:
child = root.children[child]
s += f"\n{self.pretty(child, depth + 1, spacing)}"
return s
| """
Create a "pretty print" represenation of the tree with customized indentation at each
level of the tree.
"""
if root is None:
root = self._root
fmt = "%s%s/" if root.children else "%s%s"
s = fmt % (" " * depth * spacing, root.text)
for chil... | 41 | 567 | 107 | 674 | import copy
import os
from collections import namedtuple
import dictobj
Path = namedtuple("Path", ("path", "id", "options"))
class Node(dictobj.DictionaryObject):
"""
Copyright 2012 "Grim Apps"
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in com... | import copy
import os
from collections import namedtuple
import dictobj
Path = namedtuple("Path", ("path", "id", "options"))
class Node(dictobj.DictionaryObject):
"""
Copyright 2012 "Grim Apps"
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in com... |
46,394 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/jstree.py | 78,79 | 10,93 | jsonData | Node | 79,93 | 79,93 | class Node(dictobj.DictionaryObject):
"""
Copyright 2012 "Grim Apps"
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
... | class Node(dictobj.DictionaryObject):
"""
Copyright 2012 "Grim Apps"
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
... | children = [self.children[k].jsonData() for k in sorted(self.children)]
output = {}
for k in self._items:
if "children" == k:
continue
if isinstance(self._items[k], dictobj.DictionaryObject):
output[k] = self._items[k].asdict()
... | children = [self.children[k].jsonData() for k in sorted(self.children)]
output = {}
for k in self._items:
if "children" == k:
continue
if isinstance(self._items[k], dictobj.DictionaryObject):
output[k] = self._items[k].asdict()
... | 36 | 971 | 137 | 1,108 | import copy
import os
from collections import namedtuple
import dictobj
Path = namedtuple("Path", ("path", "id", "options"))
class Node(dictobj.DictionaryObject):
"""
Copyright 2012 "Grim Apps"
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in com... | import copy
import os
from collections import namedtuple
import dictobj
Path = namedtuple("Path", ("path", "id", "options"))
class Node(dictobj.DictionaryObject):
"""
Copyright 2012 "Grim Apps"
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in com... |
46,395 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/lazy_process.py | 25,26 | 6,44 | __start | LazyProcess | 26,29 | 26,29 | class LazyProcess:
"""Abstraction describing a command line launching a service - probably
as needed as functionality is accessed in Galaxy.
"""
def __init__(self, command_and_args):
self.command_and_args = command_and_args
self.thread_lock = threading.Lock()
self.allow_process_... | class LazyProcess:
"""Abstraction describing a command line launching a service - probably
as needed as functionality is accessed in Galaxy.
"""
def __init__(self, command_and_args):
self.command_and_args = command_and_args
self.thread_lock = threading.Lock()
self.allow_process_... | with self.thread_lock:
self.process = subprocess.Popen(self.command_and_args, close_fds=True)
| with self.thread_lock:
self.process = subprocess.Popen(self.command_and_args, close_fds=True)
| 6 | 303 | 40 | 343 | import subprocess
import threading
import time
class LazyProcess:
"""Abstraction describing a command line launching a service - probably
as needed as functionality is accessed in Galaxy.
"""
def __init__(self, command_and_args):
self.command_and_args = command_and_args
self.thread_lo... | import subprocess
import threading
import time
class LazyProcess:
"""Abstraction describing a command line launching a service - probably
as needed as functionality is accessed in Galaxy.
"""
def __init__(self, command_and_args):
self.command_and_args = command_and_args
self.thread_lo... |
46,396 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/lazy_process.py | 50,51 | 44,59 | start_process | NoOpLazyProcess | 51,53 | 51,53 | class NoOpLazyProcess:
"""LazyProcess abstraction meant to describe potentially optional
services, in those cases where one is not configured or valid, this
class can be used in place of LazyProcess.
"""
def start_process(self):
FILL_FUNC_BODY def shutdown(self):
return
@property
... | class NoOpLazyProcess:
"""LazyProcess abstraction meant to describe potentially optional
services, in those cases where one is not configured or valid, this
class can be used in place of LazyProcess.
"""
def start_process(self):
FILL_FUNC_BODY def shutdown(self):
return
@property
... | return
| return
| 1 | 99 | 6 | 105 | import subprocess
import threading
import time
class LazyProcess:
"""Abstraction describing a command line launching a service - probably
as needed as functionality is accessed in Galaxy.
"""
def __init__(self, command_and_args):
self.command_and_args = command_and_args
self.thread_lo... | import subprocess
import threading
import time
class LazyProcess:
"""Abstraction describing a command line launching a service - probably
as needed as functionality is accessed in Galaxy.
"""
def __init__(self, command_and_args):
self.command_and_args = command_and_args
self.thread_lo... |
46,397 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/markdown.py | 4,5 | 1,14 | literal_via_fence | 5,8 | 5,8 | """Common markdown formatting helpers for per-datatype rendering."""
def literal_via_fence(content):
FILL_FUNC_BODYdef indicate_data_truncated():
return "\n**Warning:** The above data has been truncated to be embedded in this document.\n\n"
def pre_formatted_contents(markdown):
return f"<pre>{markdown}</pre... | """Common markdown formatting helpers for per-datatype rendering."""
def literal_via_fence(content):
FILL_FUNC_BODYdef indicate_data_truncated():
return "\n**Warning:** The above data has been truncated to be embedded in this document.\n\n"
def pre_formatted_contents(markdown):
return f"<pre>{markdown}</pre... | return "\n{}\n".format("\n".join(f" {line}" for line in content.splitlines()))
| return "\n{}\n".format("\n".join(f" {line}" for line in content.splitlines()))
| 7 | 108 | 34 | 142 | """Common markdown formatting helpers for per-datatype rendering."""
def literal_via_fence(content):
FILL_FUNC_BODYdef indicate_data_truncated():
return "\n**Warning:** The above data has been truncated to be embedded in this document.\n\n"
def pre_formatted_contents(markdown):
return f"<pre>{markdown}</pre... | """Common markdown formatting helpers for per-datatype rendering."""
def literal_via_fence(content):
FILL_FUNC_BODYdef indicate_data_truncated():
return "\n**Warning:** The above data has been truncated to be embedded in this document.\n\n"
def pre_formatted_contents(markdown):
return f"<pre>{markdown}</pre... | |
46,398 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/monitors.py | 43,44 | 11,50 | shutdown_monitor | Monitors | 44,50 | 44,50 | class Monitors:
def _init_monitor_thread(self, name, target_name=None, target=None, start=False, config=None):
self.monitor_join_sleep = getattr(config, "monitor_thread_join_timeout", DEFAULT_MONITOR_THREAD_JOIN_TIMEOUT)
self.monitor_join = self.monitor_join_sleep > 0
self.monitor_running = ... | class Monitors:
def _init_monitor_thread(self, name, target_name=None, target=None, start=False, config=None):
self.monitor_join_sleep = getattr(config, "monitor_thread_join_timeout", DEFAULT_MONITOR_THREAD_JOIN_TIMEOUT)
self.monitor_join = self.monitor_join_sleep > 0
self.monitor_running = ... | self.stop_monitoring()
if self.sleeper is not None:
self.sleeper.wake()
if self.monitor_join:
log.debug("Joining monitor thread")
self.monitor_thread.join(self.monitor_join_sleep)
| self.stop_monitoring()
if self.sleeper is not None:
self.sleeper.wake()
if self.monitor_join:
log.debug("Joining monitor thread")
self.monitor_thread.join(self.monitor_join_sleep)
| 13 | 349 | 76 | 425 | import logging
import threading
from .sleeper import Sleeper
log = logging.getLogger(__name__)
DEFAULT_MONITOR_THREAD_JOIN_TIMEOUT = 5
class Monitors:
def _init_monitor_thread(self, name, target_name=None, target=None, start=False, config=None):
self.monitor_join_sleep = getattr(config, "monitor_thread... | import logging
import threading
from .sleeper import Sleeper
log = logging.getLogger(__name__)
DEFAULT_MONITOR_THREAD_JOIN_TIMEOUT = 5
class Monitors:
def _init_monitor_thread(self, name, target_name=None, target=None, start=False, config=None):
self.monitor_join_sleep = getattr(config, "monitor_thread... |
46,399 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/odict.py | 98,99 | 16,102 | insert | odict | 99,102 | 99,102 | class odict(UserDict):
"""
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
This dictionary class extends UserDict to record the order in which items are
added. Calling keys(), values(), items(), etc. will return results in this
order.
"""
def __init__(self, dict=None):
... | class odict(UserDict):
"""
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
This dictionary class extends UserDict to record the order in which items are
added. Calling keys(), values(), items(), etc. will return results in this
order.
"""
def __init__(self, dict=None):
... | if key not in self._keys:
self._keys.insert(index, key)
UserDict.__setitem__(self, key, item)
| if key not in self._keys:
self._keys.insert(index, key)
UserDict.__setitem__(self, key, item)
| 10 | 653 | 40 | 693 | """
Ordered dictionary implementation with `insert` functionality.
This is only used in one specific place in the codebase:
galaxy.tool_util.toolbox.panel
Whenever possible the stdlib `collections.OrderedDict` should be used instead of
this custom implementation.
"""
from collections import UserDict
dict_alias ... | """
Ordered dictionary implementation with `insert` functionality.
This is only used in one specific place in the codebase:
galaxy.tool_util.toolbox.panel
Whenever possible the stdlib `collections.OrderedDict` should be used instead of
this custom implementation.
"""
from collections import UserDict
dict_alias ... |
46,400 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/oset.py | 48,49 | 8,64 | pop | OrderedSet | 49,55 | 49,55 | class OrderedSet(MutableSet):
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} # key --> [key, prev, next]
if iterable is not None:
self |= iterable
def __len__(self):
return... | class OrderedSet(MutableSet):
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} # key --> [key, prev, next]
if iterable is not None:
self |= iterable
def __len__(self):
return... | if not self:
raise KeyError("set is empty")
key = self.end[1][0] if last else self.end[2][0]
self.discard(key)
return key
| if not self:
raise KeyError("set is empty")
key = self.end[1][0] if last else self.end[2][0]
self.discard(key)
return key
| 17 | 478 | 59 | 537 | """
Ordered set implementation from https://code.activestate.com/recipes/576694/
"""
from collections.abc import MutableSet
class OrderedSet(MutableSet):
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} #... | """
Ordered set implementation from https://code.activestate.com/recipes/576694/
"""
from collections.abc import MutableSet
class OrderedSet(MutableSet):
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} #... |
46,401 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/permutations.py | 45,46 | 1,122 | __split_inputs | 46,64 | 46,64 | """ There is some shared logic between matching/multiplying inputs in workflows
and tools. This module is meant to capture some general permutation logic that
can be applicable for both cases but will only be used in the newer tools case
first.
Maybe this doesn't make sense and maybe much of this stuff could be replac... | """ There is some shared logic between matching/multiplying inputs in workflows
and tools. This module is meant to capture some general permutation logic that
can be applicable for both cases but will only be used in the newer tools case
first.
Maybe this doesn't make sense and maybe much of this stuff could be replac... | key_filter = key_filter or (lambda x: True)
single_inputs: Dict[str, T] = {}
matched_multi_inputs: Dict[str, T] = {}
multiplied_multi_inputs: Dict[str, T] = {}
for input_key in filter(key_filter, inputs):
input_type, expanded_val = classifier(input_key)
if input_type == input_class... | key_filter = key_filter or (lambda x: True)
single_inputs: Dict[str, T] = {}
matched_multi_inputs: Dict[str, T] = {}
multiplied_multi_inputs: Dict[str, T] = {}
for input_key in filter(key_filter, inputs):
input_type, expanded_val = classifier(input_key)
if input_type == input_class... | 56 | 1,045 | 248 | 1,293 | """ There is some shared logic between matching/multiplying inputs in workflows
and tools. This module is meant to capture some general permutation logic that
can be applicable for both cases but will only be used in the newer tools case
first.
Maybe this doesn't make sense and maybe much of this stuff could be replac... | """ There is some shared logic between matching/multiplying inputs in workflows
and tools. This module is meant to capture some general permutation logic that
can be applicable for both cases but will only be used in the newer tools case
first.
Maybe this doesn't make sense and maybe much of this stuff could be replac... | |
46,402 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/plugin_config.py | 77,80 | 1,158 | __load_plugins_from_element | 80,99 | 80,99 | from pathlib import Path
from types import ModuleType
from typing import (
Any,
cast,
Dict,
Generator,
Iterable,
List,
NamedTuple,
Optional,
Type,
Union,
)
import yaml
from galaxy.util import parse_xml
from galaxy.util.submodules import import_submodules
PathT = Union[str, Pat... | from pathlib import Path
from types import ModuleType
from typing import (
Any,
cast,
Dict,
Generator,
Iterable,
List,
NamedTuple,
Optional,
Type,
Union,
)
import yaml
from galaxy.util import parse_xml
from galaxy.util.submodules import import_submodules
PathT = Union[str, Pat... | plugins = []
for plugin_element in plugins_element:
plugin_type = plugin_element.tag
plugin_kwds = dict(plugin_element.items())
plugin_kwds.update(extra_kwds)
try:
plugin_klazz = plugins_dict[plugin_type]
except KeyError:
template = "Failed to fin... | plugins = []
for plugin_element in plugins_element:
plugin_type = plugin_element.tag
plugin_kwds = dict(plugin_element.items())
plugin_kwds.update(extra_kwds)
try:
plugin_klazz = plugins_dict[plugin_type]
except KeyError:
template = "Failed to fin... | 48 | 1,336 | 182 | 1,518 | from pathlib import Path
from types import ModuleType
from typing import (
Any,
cast,
Dict,
Generator,
Iterable,
List,
NamedTuple,
Optional,
Type,
Union,
)
import yaml
from galaxy.util import parse_xml
from galaxy.util.submodules import import_submodules
PathT = Union[str, Pat... | from pathlib import Path
from types import ModuleType
from typing import (
Any,
cast,
Dict,
Generator,
Iterable,
List,
NamedTuple,
Optional,
Type,
Union,
)
import yaml
from galaxy.util import parse_xml
from galaxy.util.submodules import import_submodules
PathT = Union[str, Pat... | |
46,404 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/properties.py | 186,187 | 176,198 | defaults | NicerConfigParser | 192,198 | 187,198 | class NicerConfigParser(ConfigParser):
def __init__(self, filename, *args, **kw):
kw["interpolation"] = _InterpolateWrapper()
ConfigParser.__init__(self, *args, **kw)
self.filename = filename
def optionxform(self, optionstr: str) -> str:
# Don't lower-case keys
return st... | class NicerConfigParser(ConfigParser):
def __init__(self, filename, *args, **kw):
kw["interpolation"] = _InterpolateWrapper()
ConfigParser.__init__(self, *args, **kw)
self.filename = filename
def optionxform(self, optionstr: str) -> str:
# Don't lower-case keys
return st... | defaults = dict(ConfigParser.defaults(self))
for key, val in defaults.items():
defaults[key] = self.get("DEFAULT", key) or val
return defaults
| """Return the defaults, with their values interpolated (with the
defaults dict itself)
Mainly to support defaults using values such as %(here)s
"""
defaults = dict(ConfigParser.defaults(self))
for key, val in defaults.items():
defaults[key] = self.get("DEFAUL... | 16 | 166 | 53 | 219 | """ Module used to blend ini, environment, and explicit dictionary properties
to determine application configuration. Some hard coded defaults for Galaxy but
this should be reusable by tool shed and pulsar as well.
"""
import os
import os.path
import sys
from configparser import (
BasicInterpolation,
ConfigPar... | """ Module used to blend ini, environment, and explicit dictionary properties
to determine application configuration. Some hard coded defaults for Galaxy but
this should be reusable by tool shed and pulsar as well.
"""
import os
import os.path
import sys
from configparser import (
BasicInterpolation,
ConfigPar... |
46,405 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/properties.py | 164,165 | 163,176 | before_get | _InterpolateWrapper | 165,176 | 165,176 | class _InterpolateWrapper(BasicInterpolation):
def before_get(self, parser, section, option, value, defaults):
FILL_FUNC_BODY | class _InterpolateWrapper(BasicInterpolation):
def before_get(self, parser, section, option, value, defaults):
FILL_FUNC_BODY | try:
return super().before_get(parser, section, option, value, defaults)
except InterpolationError:
e = cast(InterpolationError, sys.exc_info()[1])
args = list(e.args)
args[0] = f"Error in file {parser.filename}: {e}"
e.args = tuple(args)
... | try:
return super().before_get(parser, section, option, value, defaults)
except InterpolationError:
e = cast(InterpolationError, sys.exc_info()[1])
args = list(e.args)
args[0] = f"Error in file {parser.filename}: {e}"
e.args = tuple(args)
... | 30 | 42 | 117 | 159 | """ Module used to blend ini, environment, and explicit dictionary properties
to determine application configuration. Some hard coded defaults for Galaxy but
this should be reusable by tool shed and pulsar as well.
"""
import os
import os.path
import sys
from configparser import (
BasicInterpolation,
ConfigPar... | """ Module used to blend ini, environment, and explicit dictionary properties
to determine application configuration. Some hard coded defaults for Galaxy but
this should be reusable by tool shed and pulsar as well.
"""
import os
import os.path
import sys
from configparser import (
BasicInterpolation,
ConfigPar... |
46,406 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/resources.py | 33,34 | 1,49 | resource_string | 39,42 | 34,42 | """Provide a consistent interface into and utilities for importlib file resources.
"""
import sys
if sys.version_info >= (3, 9):
from importlib.resources import (
as_file,
files,
Package as Anchor,
)
if sys.version_info >= (3, 12):
from importlib.resources.abc import Trave... | """Provide a consistent interface into and utilities for importlib file resources.
"""
import sys
if sys.version_info >= (3, 9):
from importlib.resources import (
as_file,
files,
Package as Anchor,
)
if sys.version_info >= (3, 12):
from importlib.resources.abc import Trave... | return resource_path(package_or_requirement, resource_name).read_text()
| """
Return specified resource as a string.
Replacement function for pkg_resources.resource_string, but returns unicode string instead of bytestring.
"""
return resource_path(package_or_requirement, resource_name).read_text()
| 3 | 344 | 27 | 371 | """Provide a consistent interface into and utilities for importlib file resources.
"""
import sys
if sys.version_info >= (3, 9):
from importlib.resources import (
as_file,
files,
Package as Anchor,
)
if sys.version_info >= (3, 12):
from importlib.resources.abc import Trave... | """Provide a consistent interface into and utilities for importlib file resources.
"""
import sys
if sys.version_info >= (3, 9):
from importlib.resources import (
as_file,
files,
Package as Anchor,
)
if sys.version_info >= (3, 12):
from importlib.resources.abc import Trave... | |
46,407 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/rst_to_html.py | 28,30 | 1,69 | get_publisher | 30,60 | 30,60 | import functools
import os
try:
import docutils.core
import docutils.io
import docutils.utils
import docutils.writers.html4css1
except ImportError:
docutils = None # type: ignore[assignment]
from .custom_logging import get_logger
class FakeStream:
def __init__(self, error):
self.__e... | import functools
import os
try:
import docutils.core
import docutils.io
import docutils.utils
import docutils.writers.html4css1
except ImportError:
docutils = None # type: ignore[assignment]
from .custom_logging import get_logger
class FakeStream:
def __init__(self, error):
self.__e... | docutils_writer = docutils.writers.html4css1.Writer()
docutils_template_path = os.path.join(os.path.dirname(__file__), "docutils_template.txt")
no_report_level = docutils.utils.Reporter.SEVERE_LEVEL + 1
settings_overrides = {
"embed_stylesheet": False,
"template": docutils_template_path,... | docutils_writer = docutils.writers.html4css1.Writer()
docutils_template_path = os.path.join(os.path.dirname(__file__), "docutils_template.txt")
no_report_level = docutils.utils.Reporter.SEVERE_LEVEL + 1
settings_overrides = {
"embed_stylesheet": False,
"template": docutils_template_path,... | 82 | 320 | 378 | 698 | import functools
import os
try:
import docutils.core
import docutils.io
import docutils.utils
import docutils.writers.html4css1
except ImportError:
docutils = None # type: ignore[assignment]
from .custom_logging import get_logger
class FakeStream:
def __init__(self, error):
self.__e... | import functools
import os
try:
import docutils.core
import docutils.io
import docutils.utils
import docutils.writers.html4css1
except ImportError:
docutils = None # type: ignore[assignment]
from .custom_logging import get_logger
class FakeStream:
def __init__(self, error):
self.__e... | |
46,408 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/rst_to_html.py | 21,22 | 15,28 | write | FakeStream | 22,28 | 22,28 | class FakeStream:
def __init__(self, error):
self.__error = error
log_ = get_logger("docutils")
def write(self, str):
FILL_FUNC_BODY | class FakeStream:
def __init__(self, error):
self.__error = error
log_ = get_logger("docutils")
def write(self, str):
FILL_FUNC_BODY | if len(str) > 0 and not str.isspace():
if self.__error:
raise Exception(str)
self.log_.warning(str)
| if len(str) > 0 and not str.isspace():
if self.__error:
raise Exception(str)
self.log_.warning(str)
| 12 | 56 | 48 | 104 | import functools
import os
try:
import docutils.core
import docutils.io
import docutils.utils
import docutils.writers.html4css1
except ImportError:
docutils = None # type: ignore[assignment]
from .custom_logging import get_logger
class FakeStream:
def __init__(self, error):
self.__e... | import functools
import os
try:
import docutils.core
import docutils.io
import docutils.utils
import docutils.writers.html4css1
except ImportError:
docutils = None # type: ignore[assignment]
from .custom_logging import get_logger
class FakeStream:
def __init__(self, error):
self.__e... |
46,409 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/sanitize_html.py | 253,254 | 1,258 | sanitize_html | 254,258 | 254,258 | """
HTML Sanitizer (lists of acceptable_* ripped from feedparser)
"""
import bleach
from galaxy.util import unicodify
_acceptable_elements = [
"a",
"abbr",
"acronym",
"address",
"area",
"article",
"aside",
"audio",
"b",
"big",
"blockquote",
"br",
"button",
"can... | """
HTML Sanitizer (lists of acceptable_* ripped from feedparser)
"""
import bleach
from galaxy.util import unicodify
_acceptable_elements = [
"a",
"abbr",
"acronym",
"address",
"area",
"article",
"aside",
"audio",
"b",
"big",
"blockquote",
"br",
"button",
"can... | kwd = dict(tags=_acceptable_elements, attributes=_acceptable_attributes, strip=True)
if allow_data_urls:
kwd["protocols"] = list(bleach.ALLOWED_PROTOCOLS) + ["data"]
return bleach.clean(unicodify(htmlSource), **kwd)
| kwd = dict(tags=_acceptable_elements, attributes=_acceptable_attributes, strip=True)
if allow_data_urls:
kwd["protocols"] = list(bleach.ALLOWED_PROTOCOLS) + ["data"]
return bleach.clean(unicodify(htmlSource), **kwd)
| 15 | 1,402 | 88 | 1,490 | """
HTML Sanitizer (lists of acceptable_* ripped from feedparser)
"""
import bleach
from galaxy.util import unicodify
_acceptable_elements = [
"a",
"abbr",
"acronym",
"address",
"area",
"article",
"aside",
"audio",
"b",
"big",
"blockquote",
"br",
"button",
"can... | """
HTML Sanitizer (lists of acceptable_* ripped from feedparser)
"""
import bleach
from galaxy.util import unicodify
_acceptable_elements = [
"a",
"abbr",
"acronym",
"address",
"area",
"article",
"aside",
"audio",
"b",
"big",
"blockquote",
"br",
"button",
"can... | |
46,410 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/script.py | 66,67 | 1,106 | populate_config_args | 67,82 | 67,82 | """Utilities for Galaxy scripts
"""
import argparse
import logging
import os
import sys
from galaxy.util.properties import (
find_config_file,
load_app_properties,
)
DESCRIPTION = None
ACTIONS = None
ARGUMENTS = None
DEFAULT_ACTION = None
ARG_HELP_CONFIG_FILE = """
Galaxy config file (defaults to $GALAXY_RO... | """Utilities for Galaxy scripts
"""
import argparse
import logging
import os
import sys
from galaxy.util.properties import (
find_config_file,
load_app_properties,
)
DESCRIPTION = None
ACTIONS = None
ARGUMENTS = None
DEFAULT_ACTION = None
ARG_HELP_CONFIG_FILE = """
Galaxy config file (defaults to $GALAXY_RO... | # config and config-file respected because we have used different arguments at different
# time for scripts.
# Options (e.g. option_name) not found in this file can have their defaults overridden
# set setting GALAXY_CONFIG_OPTION_NAME where OPTION_NAME is option_name converted to upper case.
# Opt... | # config and config-file respected because we have used different arguments at different
# time for scripts.
# Options (e.g. option_name) not found in this file can have their defaults overridden
# set setting GALAXY_CONFIG_OPTION_NAME where OPTION_NAME is option_name converted to upper case.
# Opt... | 85 | 902 | 266 | 1,168 | """Utilities for Galaxy scripts
"""
import argparse
import logging
import os
import sys
from galaxy.util.properties import (
find_config_file,
load_app_properties,
)
DESCRIPTION = None
ACTIONS = None
ARGUMENTS = None
DEFAULT_ACTION = None
ARG_HELP_CONFIG_FILE = """
Galaxy config file (defaults to $GALAXY_RO... | """Utilities for Galaxy scripts
"""
import argparse
import logging
import os
import sys
from galaxy.util.properties import (
find_config_file,
load_app_properties,
)
DESCRIPTION = None
ACTIONS = None
ARGUMENTS = None
DEFAULT_ACTION = None
ARG_HELP_CONFIG_FILE = """
Galaxy config file (defaults to $GALAXY_RO... | |
46,411 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/search.py | 31,36 | 1,117 | parse_filters_structured | 36,67 | 36,67 | import re
from typing import (
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
KeyedQueryT = Tuple[str, str]
ParseFilterResultT = Tuple[Optional[List["FilteredTerm"]], Optional[str]]
QUOTE_PATTERN = re.compile(r"\'(.*?)\'")
def parse_filters(search_term: str, filters: Optional[Dict[str, str... | import re
from typing import (
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
KeyedQueryT = Tuple[str, str]
ParseFilterResultT = Tuple[Optional[List["FilteredTerm"]], Optional[str]]
QUOTE_PATTERN = re.compile(r"\'(.*?)\'")
def parse_filters(search_term: str, filters: Optional[Dict[str, str... | search_space = search_term.replace('"', "'")
filters = filters or {}
filter_keys = "|".join(list(filters.keys()))
pattern = rf"({filter_keys}):(?:\s+)?([\w-]+|'.*?')(:\w+)?"
reserved = re.compile(pattern)
parsed_search = ParsedSearch()
while True:
match = reserved.search(search_space... | search_space = search_term.replace('"', "'")
filters = filters or {}
filter_keys = "|".join(list(filters.keys()))
pattern = rf"({filter_keys}):(?:\s+)?([\w-]+|'.*?')(:\w+)?"
reserved = re.compile(pattern)
parsed_search = ParsedSearch()
while True:
match = reserved.search(search_space... | 98 | 740 | 466 | 1,206 | import re
from typing import (
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
KeyedQueryT = Tuple[str, str]
ParseFilterResultT = Tuple[Optional[List["FilteredTerm"]], Optional[str]]
QUOTE_PATTERN = re.compile(r"\'(.*?)\'")
def parse_filters(search_term: str, filters: Optional[Dict[str, str... | import re
from typing import (
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
KeyedQueryT = Tuple[str, str]
ParseFilterResultT = Tuple[Optional[List["FilteredTerm"]], Optional[str]]
QUOTE_PATTERN = re.compile(r"\'(.*?)\'")
def parse_filters(search_term: str, filters: Optional[Dict[str, str... | |
46,412 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/search.py | 108,110 | 81,113 | simple_result | ParsedSearch | 110,113 | 110,113 | class ParsedSearch:
terms: List[TermT]
text_terms: List[RawTextTerm]
filter_terms: List[FilteredTerm]
def __init__(self):
self.terms = []
self.text_terms = []
self.filter_terms = []
def add_unfiltered_text_terms(self, text: str):
for part in text.split():
... | class ParsedSearch:
terms: List[TermT]
text_terms: List[RawTextTerm]
filter_terms: List[FilteredTerm]
def __init__(self):
self.terms = []
self.text_terms = []
self.filter_terms = []
def add_unfiltered_text_terms(self, text: str):
for part in text.split():
... | return None if len(self.filter_terms) == 0 else self.filter_terms, " ".join([t.text for t in self.text_terms])
| return None if len(self.filter_terms) == 0 else self.filter_terms, " ".join([t.text for t in self.text_terms])
| 14 | 289 | 43 | 332 | import re
from typing import (
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
KeyedQueryT = Tuple[str, str]
ParseFilterResultT = Tuple[Optional[List["FilteredTerm"]], Optional[str]]
QUOTE_PATTERN = re.compile(r"\'(.*?)\'")
def parse_filters(search_term: str, filters: Optional[Dict[str, str... | import re
from typing import (
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
KeyedQueryT = Tuple[str, str]
ParseFilterResultT = Tuple[Optional[List["FilteredTerm"]], Optional[str]]
QUOTE_PATTERN = re.compile(r"\'(.*?)\'")
def parse_filters(search_term: str, filters: Optional[Dict[str, str... |
46,413 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/simplegraph.py | 79,80 | 44,132 | add_edge | SimpleGraph | 94,104 | 80,104 | class SimpleGraph:
"""
Each node is unique (by id) and stores its own index in the node list/odict.
Each edge is represented as two indeces into the node list/odict.
Both nodes and edges allow storing extra information if needed.
Allows:
multiple edges between two nodes
self referen... | class SimpleGraph:
"""
Each node is unique (by id) and stores its own index in the node list/odict.
Each edge is represented as two indeces into the node list/odict.
Both nodes and edges allow storing extra information if needed.
Allows:
multiple edges between two nodes
self referen... | # adds target_id to source_id's edge list
# adding source_id and/or target_id to nodes if not there already
if source_id not in self.nodes:
self.add_node(source_id)
if target_id not in self.nodes:
self.add_node(target_id)
new_edge = SimpleGraphEdge(self.... | """
Adds a new node only if it doesn't already exist.
:param source_id: the id of the source node
:type source_id: (hashable)
:param target_id: the id of the target node
:type target_id: (hashable)
:param data: any extra data that needs to be saved for the edge
... | 38 | 850 | 146 | 996 | """
Fencepost-simple graph structure implementation.
"""
# Currently (2013.7.12) only used in easing the parsing of graph datatype data.
class SimpleGraphNode:
"""
Node representation.
"""
def __init__(self, index, **data):
"""
:param index: index of this node in some parent list
... | """
Fencepost-simple graph structure implementation.
"""
# Currently (2013.7.12) only used in easing the parsing of graph datatype data.
class SimpleGraphNode:
"""
Node representation.
"""
def __init__(self, index, **data):
"""
:param index: index of this node in some parent list
... |
46,414 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/sleeper.py | 19,20 | 4,24 | wake | Sleeper | 20,24 | 20,24 | class Sleeper:
"""
Provides a 'sleep' method that sleeps for a number of seconds *unless*
the notify method is called (from a different thread).
"""
def __init__(self):
self.condition = threading.Condition()
def sleep(self, seconds):
# Should this be in a try/finally block? -Jo... | class Sleeper:
"""
Provides a 'sleep' method that sleeps for a number of seconds *unless*
the notify method is called (from a different thread).
"""
def __init__(self):
self.condition = threading.Condition()
def sleep(self, seconds):
# Should this be in a try/finally block? -Jo... | # Should this be in a try/finally block? -John
self.condition.acquire()
self.condition.notify()
self.condition.release()
| # Should this be in a try/finally block? -John
self.condition.acquire()
self.condition.notify()
self.condition.release()
| 12 | 136 | 45 | 181 | import threading
class Sleeper:
"""
Provides a 'sleep' method that sleeps for a number of seconds *unless*
the notify method is called (from a different thread).
"""
def __init__(self):
self.condition = threading.Condition()
def sleep(self, seconds):
# Should this be in a try... | import threading
class Sleeper:
"""
Provides a 'sleep' method that sleeps for a number of seconds *unless*
the notify method is called (from a different thread).
"""
def __init__(self):
self.condition = threading.Condition()
def sleep(self, seconds):
# Should this be in a try... |
46,415 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/sockets.py | 41,42 | 1,62 | __unused_port_on_range | 42,62 | 42,62 | import random
import socket
import sys
from galaxy.util import commands
def get_ip() -> str:
if sys.platform == "darwin":
# If we're on OSX it is likely that the docker host is localhost.
return socket.gethostbyname(socket.gethostname())
# This method assumes that the ip with default route is... | import random
import socket
import sys
from galaxy.util import commands
def get_ip() -> str:
if sys.platform == "darwin":
# If we're on OSX it is likely that the docker host is localhost.
return socket.gethostbyname(socket.gethostname())
# This method assumes that the ip with default route is... | assert range[0] and range[1]
# Find all ports that are already occupied
cmd_netstat = ["netstat", "tuln"]
stdout = commands.execute(cmd_netstat)
occupied_ports = set()
for line in stdout.split("\n"):
if line.startswith("tcp") or line.startswith("tcp6"):
col = line.split()
... | assert range[0] and range[1]
# Find all ports that are already occupied
cmd_netstat = ["netstat", "tuln"]
stdout = commands.execute(cmd_netstat)
occupied_ports = set()
for line in stdout.split("\n"):
if line.startswith("tcp") or line.startswith("tcp6"):
col = line.split()
... | 60 | 361 | 216 | 577 | import random
import socket
import sys
from galaxy.util import commands
def get_ip() -> str:
if sys.platform == "darwin":
# If we're on OSX it is likely that the docker host is localhost.
return socket.gethostbyname(socket.gethostname())
# This method assumes that the ip with default route is... | import random
import socket
import sys
from galaxy.util import commands
def get_ip() -> str:
if sys.platform == "darwin":
# If we're on OSX it is likely that the docker host is localhost.
return socket.gethostbyname(socket.gethostname())
# This method assumes that the ip with default route is... | |
46,416 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/specs.py | 23,24 | 1,33 | to_float_or_none | 24,31 | 24,31 | import functools
import operator
from galaxy import util
# Utility methods for specifing maps.
def to_str_or_none(value):
if value is None:
return None
else:
return str(value)
def to_bool_or_none(value):
return util.string_as_bool_or_none(value)
def to_bool(value):
return util.asb... | import functools
import operator
from galaxy import util
# Utility methods for specifing maps.
def to_str_or_none(value):
if value is None:
return None
else:
return str(value)
def to_bool_or_none(value):
return util.string_as_bool_or_none(value)
def to_bool(value):
return util.asb... | if value is None:
return None
else:
return float(value)
# Utility methods for specifing valid...
| if value is None:
return None
else:
return float(value)
# Utility methods for specifing valid...
| 15 | 158 | 41 | 199 | import functools
import operator
from galaxy import util
# Utility methods for specifing maps.
def to_str_or_none(value):
if value is None:
return None
else:
return str(value)
def to_bool_or_none(value):
return util.string_as_bool_or_none(value)
def to_bool(value):
return util.asb... | import functools
import operator
from galaxy import util
# Utility methods for specifing maps.
def to_str_or_none(value):
if value is None:
return None
else:
return str(value)
def to_bool_or_none(value):
return util.string_as_bool_or_none(value)
def to_bool(value):
return util.asb... | |
46,417 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/sqlite.py | 25,26 | 1,29 | connect | 26,29 | 26,29 | import re
import sqlite3
try:
import sqlparse
def is_read_only_query(query):
statements = sqlparse.parse(query)
for statement in statements:
if statement.get_type() != "SELECT":
return False
return True
except ImportError:
# Without sqlparse we use a ve... | import re
import sqlite3
try:
import sqlparse
def is_read_only_query(query):
statements = sqlparse.parse(query)
for statement in statements:
if statement.get_type() != "SELECT":
return False
return True
except ImportError:
# Without sqlparse we use a ve... | connection = sqlite3.connect(path)
connection.row_factory = sqlite3.Row
return connection
| connection = sqlite3.connect(path)
connection.row_factory = sqlite3.Row
return connection
| 8 | 202 | 32 | 234 | import re
import sqlite3
try:
import sqlparse
def is_read_only_query(query):
statements = sqlparse.parse(query)
for statement in statements:
if statement.get_type() != "SELECT":
return False
return True
except ImportError:
# Without sqlparse we use a ve... | import re
import sqlite3
try:
import sqlparse
def is_read_only_query(query):
statements = sqlparse.parse(query)
for statement in statements:
if statement.get_type() != "SELECT":
return False
return True
except ImportError:
# Without sqlparse we use a ve... | |
46,418 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/task.py | 39,40 | 12,51 | run | IntervalTask | 40,47 | 40,47 | class IntervalTask:
def __init__(self, func, name="Periodic task", interval=3600, immediate_start=False, time_execution=False):
"""
Run an arbitrary function `func` every `interval` seconds.
Set `immediate_start` to True to run `func` when task is started.
"""
self.func = fu... | class IntervalTask:
def __init__(self, func, name="Periodic task", interval=3600, immediate_start=False, time_execution=False):
"""
Run an arbitrary function `func` every `interval` seconds.
Set `immediate_start` to True to run `func` when task is started.
"""
self.func = fu... | if self.immediate_start:
self._exec()
while not self.event.is_set():
self.event.wait(self.interval)
if self.running:
self._exec()
| if self.immediate_start:
self._exec()
while not self.event.is_set():
self.event.wait(self.interval)
if self.running:
self._exec()
| 10 | 304 | 61 | 365 | import logging
from threading import (
Event,
Thread,
)
from galaxy.util import ExecutionTimer
log = logging.getLogger(__name__)
class IntervalTask:
def __init__(self, func, name="Periodic task", interval=3600, immediate_start=False, time_execution=False):
"""
Run an arbitrary function `... | import logging
from threading import (
Event,
Thread,
)
from galaxy.util import ExecutionTimer
log = logging.getLogger(__name__)
class IntervalTask:
def __init__(self, func, name="Periodic task", interval=3600, immediate_start=False, time_execution=False):
"""
Run an arbitrary function `... |
46,419 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/template.py | 42,52 | 1,151 | fill_template | 58,146 | 52,146 | """Entry point for the usage of Cheetah templating within Galaxy."""
import traceback
from lib2to3.refactor import RefactoringTool
from Cheetah.Compiler import Compiler
from Cheetah.NameMapper import NotFound
from Cheetah.Parser import ParseError
from Cheetah.Template import Template
from packaging.version import Ver... | """Entry point for the usage of Cheetah templating within Galaxy."""
import traceback
from lib2to3.refactor import RefactoringTool
from Cheetah.Compiler import Compiler
from Cheetah.NameMapper import NotFound
from Cheetah.Parser import ParseError
from Cheetah.Template import Template
from packaging.version import Ver... | if template_text is None:
raise TypeError("Template text specified as None to fill_template.")
if not context:
context = kwargs
if isinstance(python_template_version, str):
python_template_version = Version(python_template_version)
try:
klass = Template.compile(source=tem... | """Fill a cheetah template out for specified context.
If template_text is None, an exception will be thrown, if context
is None (the default) - keyword arguments to this function will be used
as the context.
"""
if template_text is None:
raise TypeError("Template text specified as None ... | 333 | 554 | 1,167 | 1,721 | """Entry point for the usage of Cheetah templating within Galaxy."""
import traceback
from lib2to3.refactor import RefactoringTool
from Cheetah.Compiler import Compiler
from Cheetah.NameMapper import NotFound
from Cheetah.Parser import ParseError
from Cheetah.Template import Template
from packaging.version import Ver... | """Entry point for the usage of Cheetah templating within Galaxy."""
import traceback
from lib2to3.refactor import RefactoringTool
from Cheetah.Compiler import Compiler
from Cheetah.NameMapper import NotFound
from Cheetah.Parser import ParseError
from Cheetah.Template import Template
from packaging.version import Ver... | |
46,420 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/template.py | 29,30 | 26,34 | getModuleCode | FixedModuleCodeCompiler | 30,34 | 30,34 | class FixedModuleCodeCompiler(Compiler):
module_code = None
def getModuleCode(self):
FILL_FUNC_BODY | class FixedModuleCodeCompiler(Compiler):
module_code = None
def getModuleCode(self):
FILL_FUNC_BODY | self._moduleDef = self.module_code
return self._moduleDef
| self._moduleDef = self.module_code
return self._moduleDef
| 5 | 36 | 25 | 61 | """Entry point for the usage of Cheetah templating within Galaxy."""
import traceback
from lib2to3.refactor import RefactoringTool
from Cheetah.Compiler import Compiler
from Cheetah.NameMapper import NotFound
from Cheetah.Parser import ParseError
from Cheetah.Template import Template
from packaging.version import Ver... | """Entry point for the usage of Cheetah templating within Galaxy."""
import traceback
from lib2to3.refactor import RefactoringTool
from Cheetah.Compiler import Compiler
from Cheetah.NameMapper import NotFound
from Cheetah.Parser import ParseError
from Cheetah.Template import Template
from packaging.version import Ver... |
46,421 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/themes.py | 9,10 | 1,21 | flatten_theme | 12,21 | 10,21 | from typing import (
Dict,
Union,
)
Theme = Dict[str, Union["Theme", str]]
def flatten_theme(theme: Theme, prefix: str = "-") -> Dict[str, str]:
FILL_FUNC_BODY | from typing import (
Dict,
Union,
)
Theme = Dict[str, Union["Theme", str]]
def flatten_theme(theme: Theme, prefix: str = "-") -> Dict[str, str]:
"""Transforms a nested theme dictionary into a flat dictionary,
containing keys compatible with css variables. e.g. '--masthead-background-color'"""
FILL_FU... | flat_attributes: Dict[str, str] = {}
for key, val in theme.items():
if isinstance(val, str):
flat_attributes[f"{prefix}-{key}"] = val
elif isinstance(val, Dict):
flat_attributes.update(flatten_theme(val, f"{prefix}-{key}"))
return flat_attributes
| """Transforms a nested theme dictionary into a flat dictionary,
containing keys compatible with css variables. e.g. '--masthead-background-color'"""
flat_attributes: Dict[str, str] = {}
for key, val in theme.items():
if isinstance(val, str):
flat_attributes[f"{prefix}-{key}"] = val
... | 23 | 108 | 105 | 213 | from typing import (
Dict,
Union,
)
Theme = Dict[str, Union["Theme", str]]
def flatten_theme(theme: Theme, prefix: str = "-") -> Dict[str, str]:
FILL_FUNC_BODY | from typing import (
Dict,
Union,
)
Theme = Dict[str, Union["Theme", str]]
def flatten_theme(theme: Theme, prefix: str = "-") -> Dict[str, str]:
"""Transforms a nested theme dictionary into a flat dictionary,
containing keys compatible with css variables. e.g. '--masthead-background-color'"""
FILL_FU... | |
46,422 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/tool_shed/encoding_util.py | 33,34 | 1,41 | tool_shed_encode | 34,41 | 34,41 | import binascii
import json
from galaxy.util import (
smart_str,
unicodify,
)
from galaxy.util.hash_util import hmac_new
encoding_sep = "__esep__"
encoding_sep2 = "__esepii__"
def tool_shed_decode(value):
# Extract and verify hash
value = unicodify(value)
a, b = value.split(":")
value = bina... | import binascii
import json
from galaxy.util import (
smart_str,
unicodify,
)
from galaxy.util.hash_util import hmac_new
encoding_sep = "__esep__"
encoding_sep2 = "__esepii__"
def tool_shed_decode(value):
# Extract and verify hash
value = unicodify(value)
a, b = value.split(":")
value = bina... | if isinstance(val, dict) or isinstance(val, list):
value = json.dumps(val)
else:
value = val
a = hmac_new(b"ToolShedAndGalaxyMustHaveThisSameKey", value)
b = unicodify(binascii.hexlify(smart_str(value)))
return f"{a}:{b}"
| if isinstance(val, dict) or isinstance(val, list):
value = json.dumps(val)
else:
value = val
a = hmac_new(b"ToolShedAndGalaxyMustHaveThisSameKey", value)
b = unicodify(binascii.hexlify(smart_str(value)))
return f"{a}:{b}"
| 22 | 247 | 105 | 352 | import binascii
import json
from galaxy.util import (
smart_str,
unicodify,
)
from galaxy.util.hash_util import hmac_new
encoding_sep = "__esep__"
encoding_sep2 = "__esepii__"
def tool_shed_decode(value):
# Extract and verify hash
value = unicodify(value)
a, b = value.split(":")
value = bina... | import binascii
import json
from galaxy.util import (
smart_str,
unicodify,
)
from galaxy.util.hash_util import hmac_new
encoding_sep = "__esep__"
encoding_sep2 = "__esepii__"
def tool_shed_decode(value):
# Extract and verify hash
value = unicodify(value)
a, b = value.split(":")
value = bina... | |
46,423 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/tool_shed/tool_shed_registry.py | 106,107 | 33,119 | get_tool_shed_url | Registry | 111,119 | 107,119 | class Registry:
tool_sheds: Dict[str, str]
tool_shed_api_versions: Dict[str, API_VERSION]
tool_sheds_auth: Dict[str, Optional[AUTH_TUPLE]]
def __init__(self, config: Optional[StrPath] = None):
self.tool_sheds = {}
self.tool_sheds_auth = {}
self.tool_shed_api_versions = {}
... | class Registry:
tool_sheds: Dict[str, str]
tool_shed_api_versions: Dict[str, API_VERSION]
tool_sheds_auth: Dict[str, Optional[AUTH_TUPLE]]
def __init__(self, config: Optional[StrPath] = None):
self.tool_sheds = {}
self.tool_sheds_auth = {}
self.tool_shed_api_versions = {}
... | cleaned_tool_shed = common_util.remove_protocol_from_tool_shed_url(tool_shed)
for shed_url in self.tool_sheds.values():
if shed_url.find(cleaned_tool_shed) >= 0:
if shed_url.endswith("/"):
shed_url = shed_url.rstrip("/")
return shed_url
... | """
The value of tool_shed is something like: toolshed.g2.bx.psu.edu. We need the URL to this tool shed, which is
something like: http://toolshed.g2.bx.psu.edu/
"""
cleaned_tool_shed = common_util.remove_protocol_from_tool_shed_url(tool_shed)
for shed_url in self.tool_sh... | 38 | 1,048 | 142 | 1,190 | import logging
from typing import (
Dict,
NamedTuple,
Optional,
)
from typing_extensions import Literal
from galaxy.util import parse_xml_string
from galaxy.util.path import StrPath
from galaxy.util.tool_shed import common_util
from galaxy.util.tool_shed.xml_util import parse_xml
log = logging.getLogger(... | import logging
from typing import (
Dict,
NamedTuple,
Optional,
)
from typing_extensions import Literal
from galaxy.util import parse_xml_string
from galaxy.util.path import StrPath
from galaxy.util.tool_shed import common_util
from galaxy.util.tool_shed.xml_util import parse_xml
log = logging.getLogger(... |
46,424 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/tool_shed/xml_util.py | 20,21 | 1,49 | create_and_write_tmp_file | 21,29 | 21,29 | import logging
import os
import tempfile
from typing import (
Optional,
Tuple,
)
from galaxy.util import (
Element,
ElementTree,
parse_xml as galaxy_parse_xml,
xml_to_string,
)
from galaxy.util.path import StrPath
log = logging.getLogger(__name__)
def create_and_write_tmp_file(elem: Element)... | import logging
import os
import tempfile
from typing import (
Optional,
Tuple,
)
from galaxy.util import (
Element,
ElementTree,
parse_xml as galaxy_parse_xml,
xml_to_string,
)
from galaxy.util.path import StrPath
log = logging.getLogger(__name__)
def create_and_write_tmp_file(elem: Element)... | tmp_str = xml_to_string(elem, pretty=True)
with tempfile.NamedTemporaryFile(prefix="tmp-toolshed-cawrf", delete=False) as fh:
tmp_filename = fh.name
with open(tmp_filename, mode="w", encoding="utf-8") as fh:
fh.write(tmp_str)
return tmp_filename
| tmp_str = xml_to_string(elem, pretty=True)
with tempfile.NamedTemporaryFile(prefix="tmp-toolshed-cawrf", delete=False) as fh:
tmp_filename = fh.name
with open(tmp_filename, mode="w", encoding="utf-8") as fh:
fh.write(tmp_str)
return tmp_filename
| 21 | 331 | 111 | 442 | import logging
import os
import tempfile
from typing import (
Optional,
Tuple,
)
from galaxy.util import (
Element,
ElementTree,
parse_xml as galaxy_parse_xml,
xml_to_string,
)
from galaxy.util.path import StrPath
log = logging.getLogger(__name__)
def create_and_write_tmp_file(elem: Element)... | import logging
import os
import tempfile
from typing import (
Optional,
Tuple,
)
from galaxy.util import (
Element,
ElementTree,
parse_xml as galaxy_parse_xml,
xml_to_string,
)
from galaxy.util.path import StrPath
log = logging.getLogger(__name__)
def create_and_write_tmp_file(elem: Element)... | |
46,425 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/tool_version.py | 1,2 | 1,9 | remove_version_from_guid | 5,9 | 2,9 | def remove_version_from_guid(guid):
FILL_FUNC_BODY | def remove_version_from_guid(guid):
"""
Removes version from toolshed-derived tool_id(=guid).
"""
FILL_FUNC_BODY | if "/" not in guid:
return None
last_slash = guid.rfind("/")
return guid[:last_slash]
| """
Removes version from toolshed-derived tool_id(=guid).
"""
if "/" not in guid:
return None
last_slash = guid.rfind("/")
return guid[:last_slash]
| 12 | 49 | 38 | 87 | def remove_version_from_guid(guid):
FILL_FUNC_BODY | def remove_version_from_guid(guid):
"""
Removes version from toolshed-derived tool_id(=guid).
"""
FILL_FUNC_BODY | |
46,426 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/tree_dict.py | 14,15 | 1,72 | enter | 15,21 | 15,21 | from collections import UserDict
from collections.abc import (
ItemsView,
MutableMapping,
)
from typing import (
Any,
Optional,
)
from boltons.iterutils import remap
def enter(path, key, value):
FILL_FUNC_BODYclass TreeDict(UserDict):
"""
Dictionary that inserts its own keys in a parent dicti... | from collections import UserDict
from collections.abc import (
ItemsView,
MutableMapping,
)
from typing import (
Any,
Optional,
)
from boltons.iterutils import remap
def enter(path, key, value):
FILL_FUNC_BODYclass TreeDict(UserDict):
"""
Dictionary that inserts its own keys in a parent dicti... | if isinstance(value, MutableMapping):
return value.__class__(), ItemsView(value)
else:
return value, False
| if isinstance(value, MutableMapping):
return value.__class__(), ItemsView(value)
else:
return value, False
| 10 | 570 | 44 | 614 | from collections import UserDict
from collections.abc import (
ItemsView,
MutableMapping,
)
from typing import (
Any,
Optional,
)
from boltons.iterutils import remap
def enter(path, key, value):
FILL_FUNC_BODYclass TreeDict(UserDict):
"""
Dictionary that inserts its own keys in a parent dicti... | from collections import UserDict
from collections.abc import (
ItemsView,
MutableMapping,
)
from typing import (
Any,
Optional,
)
from boltons.iterutils import remap
def enter(path, key, value):
FILL_FUNC_BODYclass TreeDict(UserDict):
"""
Dictionary that inserts its own keys in a parent dicti... | |
46,427 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/tree_dict.py | 31,32 | 21,72 | clean_copy | TreeDict | 35,43 | 32,43 | class TreeDict(UserDict):
"""
Dictionary that inserts its own keys in a parent dictionary.
"""
def __init__(self, dict=None, **kwargs):
self._parent_data: Optional[TreeDict] = None
self._injected_data = {}
super().__init__(dict, **kwargs)
def clean_copy(self):
FILL_FUNC_BOD... | class TreeDict(UserDict):
"""
Dictionary that inserts its own keys in a parent dictionary.
"""
def __init__(self, dict=None, **kwargs):
self._parent_data: Optional[TreeDict] = None
self._injected_data = {}
super().__init__(dict, **kwargs)
def clean_copy(self):
"""
... |
def strip_tree_dict(path, key, value):
if isinstance(value, TreeDict):
value = value.data
return key, value
return remap(self.data, strip_tree_dict, enter=enter)
| """
Copy without injected data.
"""
def strip_tree_dict(path, key, value):
if isinstance(value, TreeDict):
value = value.data
return key, value
return remap(self.data, strip_tree_dict, enter=enter)
| 17 | 441 | 71 | 512 | from collections import UserDict
from collections.abc import (
ItemsView,
MutableMapping,
)
from typing import (
Any,
Optional,
)
from boltons.iterutils import remap
def enter(path, key, value):
if isinstance(value, MutableMapping):
return value.__class__(), ItemsView(value)
else:
... | from collections import UserDict
from collections.abc import (
ItemsView,
MutableMapping,
)
from typing import (
Any,
Optional,
)
from boltons.iterutils import remap
def enter(path, key, value):
if isinstance(value, MutableMapping):
return value.__class__(), ItemsView(value)
else:
... |
46,428 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/ucsc.py | 38,39 | 10,40 | readline | UCSCOutWrapper | 39,40 | 39,40 | class UCSCOutWrapper:
"""File-like object that throws an exception if it encounters the UCSC limit error lines"""
def __init__(self, other):
self.other = iter(other)
# Need one line of lookahead to be sure we are hitting the limit message
self.lookahead = None
def __iter__(self):
... | class UCSCOutWrapper:
"""File-like object that throws an exception if it encounters the UCSC limit error lines"""
def __init__(self, other):
self.other = iter(other)
# Need one line of lookahead to be sure we are hitting the limit message
self.lookahead = None
def __iter__(self):
... | return next(self)
| return next(self)
| 2 | 255 | 8 | 263 | """
Utilities for dealing with UCSC data.
"""
class UCSCLimitException(Exception):
pass
class UCSCOutWrapper:
"""File-like object that throws an exception if it encounters the UCSC limit error lines"""
def __init__(self, other):
self.other = iter(other)
# Need one line of lookahead to b... | """
Utilities for dealing with UCSC data.
"""
class UCSCLimitException(Exception):
pass
class UCSCOutWrapper:
"""File-like object that throws an exception if it encounters the UCSC limit error lines"""
def __init__(self, other):
self.other = iter(other)
# Need one line of lookahead to b... |
46,429 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/validation.py | 16,17 | 1,35 | validate_and_sanitize_basestring_list | 17,24 | 17,24 | """ Module for validation of incoming inputs.
TODO: Refactor BaseController references to similar methods to use this module.
"""
from galaxy import exceptions
from galaxy.util.sanitize_html import sanitize_html
def validate_and_sanitize_basestring(key, val):
if not isinstance(val, str):
raise exception... | """ Module for validation of incoming inputs.
TODO: Refactor BaseController references to similar methods to use this module.
"""
from galaxy import exceptions
from galaxy.util.sanitize_html import sanitize_html
def validate_and_sanitize_basestring(key, val):
if not isinstance(val, str):
raise exception... | try:
assert isinstance(val, list)
return [sanitize_html(t) for t in val]
except (AssertionError, TypeError):
raise exceptions.RequestParameterInvalidException(f"{key} must be a list of strings: {type(val)}")
| try:
assert isinstance(val, list)
return [sanitize_html(t) for t in val]
except (AssertionError, TypeError):
raise exceptions.RequestParameterInvalidException(f"{key} must be a list of strings: {type(val)}")
| 22 | 282 | 80 | 362 | """ Module for validation of incoming inputs.
TODO: Refactor BaseController references to similar methods to use this module.
"""
from galaxy import exceptions
from galaxy.util.sanitize_html import sanitize_html
def validate_and_sanitize_basestring(key, val):
if not isinstance(val, str):
raise exception... | """ Module for validation of incoming inputs.
TODO: Refactor BaseController references to similar methods to use this module.
"""
from galaxy import exceptions
from galaxy.util.sanitize_html import sanitize_html
def validate_and_sanitize_basestring(key, val):
if not isinstance(val, str):
raise exception... | |
46,431 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/watcher.py | 79,80 | 66,95 | monitor | BaseWatcher | 80,84 | 80,84 | class BaseWatcher:
def __init__(self, observer_class, event_handler_class, **kwargs):
self.observer = None
self.observer_class = observer_class
self.event_handler = event_handler_class(self)
self.monitored_dirs = {}
def start(self):
if self.observer is None:
... | class BaseWatcher:
def __init__(self, observer_class, event_handler_class, **kwargs):
self.observer = None
self.observer_class = observer_class
self.event_handler = event_handler_class(self)
self.monitored_dirs = {}
def start(self):
if self.observer is None:
... | self.monitored_dirs[dir_path] = recursive
if self.observer is not None:
self.observer.schedule(self.event_handler, dir_path, recursive=recursive)
| self.monitored_dirs[dir_path] = recursive
if self.observer is not None:
self.observer.schedule(self.event_handler, dir_path, recursive=recursive)
| 11 | 245 | 61 | 306 | # TODO: this is largely copied from galaxy.tool_util.toolbox.galaxy and generalized, the tool-oriented watchers in that
# module should probably be updated to use this where possible
import logging
import os.path
import time
try:
from watchdog.events import FileSystemEventHandler
from watchdog.observers impo... | # TODO: this is largely copied from galaxy.tool_util.toolbox.galaxy and generalized, the tool-oriented watchers in that
# module should probably be updated to use this where possible
import logging
import os.path
import time
try:
from watchdog.events import FileSystemEventHandler
from watchdog.observers impo... |
46,432 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/watcher.py | 146,147 | 129,185 | _extension_check | EventHandler | 147,152 | 147,152 | class EventHandler(FileSystemEventHandler):
def __init__(self, watcher):
self.watcher = watcher
# this effectively excludes on_opened and on_closed
def on_moved(self, event):
self._handle(event)
def on_created(self, event):
self._handle(event)
def on_deleted(self, event):
... | class EventHandler(FileSystemEventHandler):
def __init__(self, watcher):
self.watcher = watcher
# this effectively excludes on_opened and on_closed
def on_moved(self, event):
self._handle(event)
def on_created(self, event):
self._handle(event)
def on_deleted(self, event):
... | required_extensions = self.watcher.require_extensions.get(key)
if required_extensions:
return any(filter(path.endswith, required_extensions))
return not any(filter(path.endswith, self.watcher.ignore_extensions.get(key, [])))
| required_extensions = self.watcher.require_extensions.get(key)
if required_extensions:
return any(filter(path.endswith, required_extensions))
return not any(filter(path.endswith, self.watcher.ignore_extensions.get(key, [])))
| 13 | 537 | 78 | 615 | # TODO: this is largely copied from galaxy.tool_util.toolbox.galaxy and generalized, the tool-oriented watchers in that
# module should probably be updated to use this where possible
import logging
import os.path
import time
try:
from watchdog.events import FileSystemEventHandler
from watchdog.observers impo... | # TODO: this is largely copied from galaxy.tool_util.toolbox.galaxy and generalized, the tool-oriented watchers in that
# module should probably be updated to use this where possible
import logging
import os.path
import time
try:
from watchdog.events import FileSystemEventHandler
from watchdog.observers impo... |
46,433 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/watcher.py | 114,117 | 95,129 | watch_directory | Watcher | 117,129 | 117,129 | class Watcher(BaseWatcher):
def __init__(self, observer_class, event_handler_class, **kwargs):
super().__init__(observer_class, event_handler_class, **kwargs)
self.path_hash = {}
self.file_callbacks = {}
self.dir_callbacks = {}
self.ignore_extensions = {}
self.require... | class Watcher(BaseWatcher):
def __init__(self, observer_class, event_handler_class, **kwargs):
super().__init__(observer_class, event_handler_class, **kwargs)
self.path_hash = {}
self.file_callbacks = {}
self.dir_callbacks = {}
self.ignore_extensions = {}
self.require... | dir_path = os.path.abspath(dir_path)
if dir_path not in self.monitored_dirs:
if callback is not None:
self.dir_callbacks[dir_path] = callback
if ignore_extensions:
self.ignore_extensions[dir_path] = ignore_extensions
if require_extensio... | dir_path = os.path.abspath(dir_path)
if dir_path not in self.monitored_dirs:
if callback is not None:
self.dir_callbacks[dir_path] = callback
if ignore_extensions:
self.ignore_extensions[dir_path] = ignore_extensions
if require_extensio... | 41 | 288 | 168 | 456 | # TODO: this is largely copied from galaxy.tool_util.toolbox.galaxy and generalized, the tool-oriented watchers in that
# module should probably be updated to use this where possible
import logging
import os.path
import time
try:
from watchdog.events import FileSystemEventHandler
from watchdog.observers impo... | # TODO: this is largely copied from galaxy.tool_util.toolbox.galaxy and generalized, the tool-oriented watchers in that
# module should probably be updated to use this where possible
import logging
import os.path
import time
try:
from watchdog.events import FileSystemEventHandler
from watchdog.observers impo... |
46,435 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/xml_macros.py | 339,340 | 302,356 | macro_tokens | XmlMacroDef | 346,356 | 340,356 | class XmlMacroDef:
"""
representation of a (Galaxy) XML macro
stores the root element of the macro and the parameters.
each parameter is represented as pair containing
- the quote character, default '@'
- parameter name
parameter names can be given as comma separated list using the
`to... | class XmlMacroDef:
"""
representation of a (Galaxy) XML macro
stores the root element of the macro and the parameters.
each parameter is represented as pair containing
- the quote character, default '@'
- parameter name
parameter names can be given as comma separated list using the
`to... | tokens = {}
for key, (wrap_char, default_val) in self.parameters.items():
token_value = expand_el.attrib.get(key, default_val)
if token_value is REQUIRED_PARAMETER:
raise ValueError(f"Failed to expand macro - missing required parameter [{key}].")
token... | """
get a dictionary mapping token names to values. The names are the
parameter names surrounded by the quote character. Values are taken
from the expand_el if absent default values of optional parameters are
used.
"""
tokens = {}
for key, (wrap_char, defa... | 35 | 419 | 133 | 552 | import os
from copy import deepcopy
from typing import (
Dict,
List,
Optional,
Tuple,
)
from galaxy.util import (
Element,
ElementTree,
parse_xml,
)
from galaxy.util.path import StrPath
REQUIRED_PARAMETER = object()
def load_with_references(path: StrPath) -> Tuple[ElementTree, Optional[L... | import os
from copy import deepcopy
from typing import (
Dict,
List,
Optional,
Tuple,
)
from galaxy.util import (
Element,
ElementTree,
parse_xml,
)
from galaxy.util.path import StrPath
REQUIRED_PARAMETER = object()
def load_with_references(path: StrPath) -> Tuple[ElementTree, Optional[L... |
46,436 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/yaml_util.py | 30,31 | 1,81 | ordered_load | 40,72 | 31,72 | import logging
import os
from collections import OrderedDict
import yaml
from yaml.constructor import ConstructorError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader # type: ignore[assignment]
log = logging.getLogger(__name__)
class OrderedLoader(SafeLoade... | import logging
import os
from collections import OrderedDict
import yaml
from yaml.constructor import ConstructorError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader # type: ignore[assignment]
log = logging.getLogger(__name__)
class OrderedLoader(SafeLoade... |
def construct_mapping(loader, node, deep=False):
loader.flatten_mapping(node)
mapping = {}
merged_duplicate = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=deep)
... | """
Parse the first YAML document in a stream and produce the corresponding
Python object.
If merge_duplicate_keys is True, merge the values of duplicate mapping keys
into a list, as the uWSGI "dumb" YAML parser would do.
Otherwise, following YAML 1.2 specification which says that "each key is
... | 78 | 479 | 348 | 827 | import logging
import os
from collections import OrderedDict
import yaml
from yaml.constructor import ConstructorError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader # type: ignore[assignment]
log = logging.getLogger(__name__)
class OrderedLoader(SafeLoade... | import logging
import os
from collections import OrderedDict
import yaml
from yaml.constructor import ConstructorError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader # type: ignore[assignment]
log = logging.getLogger(__name__)
class OrderedLoader(SafeLoade... | |
46,437 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/yaml_util.py | 24,25 | 17,30 | include | OrderedLoader | 25,30 | 25,30 | class OrderedLoader(SafeLoader):
# This class was pulled out of ordered_load() for the sake of
# mocking __init__ in a unit test.
def __init__(self, stream):
self._root = os.path.split(stream.name)[0]
super().__init__(stream)
def include(self, node):
FILL_FUNC_BODY | class OrderedLoader(SafeLoader):
# This class was pulled out of ordered_load() for the sake of
# mocking __init__ in a unit test.
def __init__(self, stream):
self._root = os.path.split(stream.name)[0]
super().__init__(stream)
def include(self, node):
FILL_FUNC_BODY | filename = os.path.join(self._root, self.construct_scalar(node))
with open(filename) as f:
return yaml.load(f, OrderedLoader)
| filename = os.path.join(self._root, self.construct_scalar(node))
with open(filename) as f:
return yaml.load(f, OrderedLoader)
| 11 | 96 | 54 | 150 | import logging
import os
from collections import OrderedDict
import yaml
from yaml.constructor import ConstructorError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader # type: ignore[assignment]
log = logging.getLogger(__name__)
class OrderedLoader(SafeLoade... | import logging
import os
from collections import OrderedDict
import yaml
from yaml.constructor import ConstructorError
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader # type: ignore[assignment]
log = logging.getLogger(__name__)
class OrderedLoader(SafeLoade... |
46,438 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/util/zipstream.py | 71,72 | 20,83 | write | ZipstreamWrapper | 72,83 | 72,83 | class ZipstreamWrapper:
def __init__(
self, archive_name: Optional[str] = None, upstream_mod_zip: bool = False, upstream_gzip: bool = False
) -> None:
self.upstream_mod_zip = upstream_mod_zip
self.archive_name = archive_name
if not self.upstream_mod_zip:
self.archive ... | class ZipstreamWrapper:
def __init__(
self, archive_name: Optional[str] = None, upstream_mod_zip: bool = False, upstream_gzip: bool = False
) -> None:
self.upstream_mod_zip = upstream_mod_zip
self.archive_name = archive_name
if not self.upstream_mod_zip:
self.archive ... | if os.path.isdir(path):
pardir = os.path.join(path, os.pardir)
for root, directories, files in safe_walk(path):
for directory in directories:
dir_path = os.path.join(root, directory)
self.add_path(dir_path, os.path.relpath(dir_path,... | if os.path.isdir(path):
pardir = os.path.join(path, os.pardir)
for root, directories, files in safe_walk(path):
for directory in directories:
dir_path = os.path.join(root, directory)
self.add_path(dir_path, os.path.relpath(dir_path,... | 39 | 797 | 185 | 982 | import os
import zlib
from typing import (
Dict,
Iterator,
List,
Optional,
Set,
)
from urllib.parse import quote
import zipstream
from .path import safe_walk
CRC32_MIN = 1444
CRC32_MAX = 1459
class ZipstreamWrapper:
def __init__(
self, archive_name: Optional[str] = None, upstream_mo... | import os
import zlib
from typing import (
Dict,
Iterator,
List,
Optional,
Set,
)
from urllib.parse import quote
import zipstream
from .path import safe_walk
CRC32_MIN = 1444
CRC32_MAX = 1459
class ZipstreamWrapper:
def __init__(
self, archive_name: Optional[str] = None, upstream_mo... |
46,439 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/data_providers/cigar.py | 8,9 | 1,105 | get_ref_based_read_seq_and_cigar | 17,78 | 9,78 | """
Functions for working with SAM/BAM CIGAR representation.
"""
import operator
def get_ref_based_read_seq_and_cigar(read_seq, read_start, ref_seq, ref_seq_start, cigar):
FILL_FUNC_BODYdef _match_mismatch_counter(s1, p1, s2, p2):
"""
Count consecutive matches/mismatches between strings s1 and s2
startin... | """
Functions for working with SAM/BAM CIGAR representation.
"""
import operator
def get_ref_based_read_seq_and_cigar(read_seq, read_start, ref_seq, ref_seq_start, cigar):
"""
Returns a ( new_read_seq, new_cigar ) that can be used with reference
sequence to reconstruct the read. The new read sequence inc... |
if not ref_seq:
return read_seq, cigar
# Set up position for reference, read.
ref_seq_pos = read_start - ref_seq_start
read_pos = 0
# Create new read sequence, cigar.
new_read_seq = ""
new_cigar = ""
cigar_ops = "MIDNSHP=X"
for op_tuple in cigar:
op, op_len = op_tu... | """
Returns a ( new_read_seq, new_cigar ) that can be used with reference
sequence to reconstruct the read. The new read sequence includes only
bases that cannot be recovered from the reference: mismatches and
insertions (soft clipped bases are not included). The new cigar replaces
Ms with =s an... | 288 | 410 | 842 | 1,252 | """
Functions for working with SAM/BAM CIGAR representation.
"""
import operator
def get_ref_based_read_seq_and_cigar(read_seq, read_start, ref_seq, ref_seq_start, cigar):
FILL_FUNC_BODYdef _match_mismatch_counter(s1, p1, s2, p2):
"""
Count consecutive matches/mismatches between strings s1 and s2
startin... | """
Functions for working with SAM/BAM CIGAR representation.
"""
import operator
def get_ref_based_read_seq_and_cigar(read_seq, read_start, ref_seq, ref_seq_start, cigar):
"""
Returns a ( new_read_seq, new_cigar ) that can be used with reference
sequence to reconstruct the read. The new read sequence inc... | |
46,440 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/data_providers/phyloviz/baseparser.py | 119,120 | 104,124 | _writeJsonToFile | Base_Parser | 121,124 | 120,124 | class Base_Parser:
"""Base parsers contain all the methods to handle phylogeny tree creation and
converting the data to json that all parsers should have"""
def __init__(self):
self.phyloTrees = []
def parseFile(self, filePath):
"""Base method that all phylogeny file parser should have... | class Base_Parser:
"""Base parsers contain all the methods to handle phylogeny tree creation and
converting the data to json that all parsers should have"""
def __init__(self):
self.phyloTrees = []
def parseFile(self, filePath):
"""Base method that all phylogeny file parser should have... | f = open(filepath, "w")
f.writelines(json)
f.close()
| """Writes the file out to the system"""
f = open(filepath, "w")
f.writelines(json)
f.close()
| 6 | 190 | 30 | 220 | import json
from typing import (
Any,
Dict,
)
class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)... | import json
from typing import (
Any,
Dict,
)
class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)... |
46,441 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/data_providers/phyloviz/baseparser.py | 52,53 | 8,61 | addMiscToJson | Node | 54,61 | 53,61 | class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)
self.depth = kwargs.get("depth", 0)
sel... | class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)
self.depth = kwargs.get("depth", 0)
sel... | if not self.events == "":
jsonDict["events"] = self.events
if self.bootstrap is not None:
jsonDict["bootstrap"] = self.bootstrap
return jsonDict
| """Adds other misc attributes to json if they are present"""
if not self.events == "":
jsonDict["events"] = self.events
if self.bootstrap is not None:
jsonDict["bootstrap"] = self.bootstrap
return jsonDict
| 18 | 561 | 59 | 620 | import json
from typing import (
Any,
Dict,
)
class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)... | import json
from typing import (
Any,
Dict,
)
class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)... |
46,442 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/data_providers/phyloviz/baseparser.py | 89,90 | 61,104 | generateJsonableDict | PhyloTree | 92,104 | 90,104 | class PhyloTree:
"""Standardized python based class to represent the phylogenetic tree parsed from different
phylogenetic file formats."""
def __init__(self):
self.root, self.rootAttr = None, {}
self.nodes = {}
self.title = None
self.id = 1
def addAttributesToRoot(self,... | class PhyloTree:
"""Standardized python based class to represent the phylogenetic tree parsed from different
phylogenetic file formats."""
def __init__(self):
self.root, self.rootAttr = None, {}
self.nodes = {}
self.title = None
self.id = 1
def addAttributesToRoot(self,... | jsonTree: Dict[str, Any]
if self.root:
assert isinstance(self.root, Node)
jsonTree = self.root.toJson()
for key, value in self.rootAttr.items():
# transfer temporary stored attr to root
jsonTree[key] = value
else:
ra... | """Changes itself into a dictonary by recurssively calling the tojson on all its nodes. Think of it
as a dict in an array of dict in an array of dict and so on..."""
jsonTree: Dict[str, Any]
if self.root:
assert isinstance(self.root, Node)
jsonTree = self.root.toJ... | 34 | 355 | 109 | 464 | import json
from typing import (
Any,
Dict,
)
class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)... | import json
from typing import (
Any,
Dict,
)
class Node:
"""Node class of PhyloTree, which represents a CLAUDE in a phylogenetic tree"""
def __init__(self, nodeName, **kwargs):
"""Creates a node and adds in the typical annotations"""
self.name, self.id = nodeName, kwargs.get("id", 0)... |
46,444 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/data_providers/phyloviz/nexusparser.py | 16,17 | 8,105 | parseNexus | Nexus_Parser | 22,85 | 17,85 | class Nexus_Parser(Newick_Parser):
def __init__(self):
super().__init__()
def parseFile(self, filePath):
"""passes a file and extracts its Nexus content."""
return self.parseNexus(filePath)
def parseNexus(self, filename):
FILL_FUNC_BODY def splitLinebyWhitespaces(self, line):
... | class Nexus_Parser(Newick_Parser):
def __init__(self):
super().__init__()
def parseFile(self, filePath):
"""passes a file and extracts its Nexus content."""
return self.parseNexus(filePath)
def parseNexus(self, filename):
"""Nexus data is stored in blocks between a line sta... |
with open(filename) as nex_file:
nexlines = nex_file.readlines()
rowCount = 0
inTreeBlock = False # sentinel to check if we are in a tree block
intranslateBlock = (
False # sentinel to check if we are in the translate region of the tree. Stores synonyms of the... | """Nexus data is stored in blocks between a line starting with begin and another line starting with end;
Commends inside square brackets are to be ignored,
For more information: http://wiki.christophchamp.com/index.php/NEXUS_file_format
Nexus can store multiple trees
"""
... | 227 | 394 | 665 | 1,059 | import re
from .newickparser import Newick_Parser
MAX_READLINES = 200000
class Nexus_Parser(Newick_Parser):
def __init__(self):
super().__init__()
def parseFile(self, filePath):
"""passes a file and extracts its Nexus content."""
return self.parseNexus(filePath)
def parseNexus(... | import re
from .newickparser import Newick_Parser
MAX_READLINES = 200000
class Nexus_Parser(Newick_Parser):
def __init__(self):
super().__init__()
def parseFile(self, filePath):
"""passes a file and extracts its Nexus content."""
return self.parseNexus(filePath)
def parseNexus(... |
46,445 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/data_providers/phyloviz/phyloxmlparser.py | 108,109 | 9,129 | _makeInternalNode | Phyloxml_Parser | 112,127 | 109,127 | class Phyloxml_Parser(Base_Parser):
"""Parses a phyloxml file into a json file that will be passed to PhyloViz for display"""
def __init__(self):
super().__init__()
self.phyloTree = PhyloTree()
self.tagsOfInterest = {
"clade": "",
"name": "name",
"bra... | class Phyloxml_Parser(Base_Parser):
"""Parses a phyloxml file into a json file that will be passed to PhyloViz for display"""
def __init__(self):
super().__init__()
self.phyloTree = PhyloTree()
self.tagsOfInterest = {
"clade": "",
"name": "name",
"bra... | node = {}
for child in internalNode:
childTag = self.cleanTag(child.tag)
if childTag == "clade":
continue
elif childTag in self.tagsOfInterest:
if childTag == "events": # events is nested 1 more level deeper than others
... | """Makes an internal node from an element object that is guranteed to be a parent node.
Gets the value of interests like events and appends it to a custom node object that will be passed to PhyloTree to make nodes
"""
node = {}
for child in internalNode:
childTag = se... | 52 | 1,105 | 168 | 1,273 | from galaxy.util import parse_xml
from .baseparser import (
Base_Parser,
Node,
PhyloTree,
)
class Phyloxml_Parser(Base_Parser):
"""Parses a phyloxml file into a json file that will be passed to PhyloViz for display"""
def __init__(self):
super().__init__()
self.phyloTree = PhyloTr... | from galaxy.util import parse_xml
from .baseparser import (
Base_Parser,
Node,
PhyloTree,
)
class Phyloxml_Parser(Base_Parser):
"""Parses a phyloxml file into a json file that will be passed to PhyloViz for display"""
def __init__(self):
super().__init__()
self.phyloTree = PhyloTr... |
46,446 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/data_providers/registry.py | 68,69 | 41,150 | get_data_provider | DataProviderRegistry | 73,150 | 69,150 | class DataProviderRegistry:
"""
Registry for data providers that enables listing and lookup.
"""
def __init__(self):
# Mapping from dataset type name to a class that can fetch data from a file of that
# type. First key is converted dataset type; if result is another dict, second key
... | class DataProviderRegistry:
"""
Registry for data providers that enables listing and lookup.
"""
def __init__(self):
# Mapping from dataset type name to a class that can fetch data from a file of that
# type. First key is converted dataset type; if result is another dict, second key
... |
data_provider: Optional[BaseDataProvider]
data_provider_class: Type[BaseDataProvider]
# any datatype class that is a subclass of another needs to be
# checked before the parent in this conditional.
if raw:
# Working with raw data.
if isinstance(original_... | """
Returns data provider matching parameter values. For standalone data
sources, source parameter is ignored.
"""
data_provider: Optional[BaseDataProvider]
data_provider_class: Type[BaseDataProvider]
# any datatype class that is a subclass of another needs to b... | 257 | 396 | 924 | 1,320 | from typing import (
Dict,
Optional,
Type,
Union,
)
from typing_extensions import Literal
from galaxy.datatypes.data import (
Data,
Newick,
Nexus,
)
from galaxy.datatypes.interval import (
Bed,
ChromatinInteractions,
ENCODEPeak,
Gff,
Gtf,
Interval,
)
from galaxy.dat... | from typing import (
Dict,
Optional,
Type,
Union,
)
from typing_extensions import Literal
from galaxy.datatypes.data import (
Data,
Newick,
Nexus,
)
from galaxy.datatypes.interval import (
Bed,
ChromatinInteractions,
ENCODEPeak,
Gff,
Gtf,
Interval,
)
from galaxy.dat... |
46,447 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/plugins/plugin.py | 253,254 | 236,266 | _render | ScriptVisualizationPlugin | 258,266 | 254,266 | class ScriptVisualizationPlugin(VisualizationPlugin):
"""
A visualization plugin that starts by loading a single (js) script.
The script is loaded into a pre-defined mako template:
`config/plugins/visualizations/common/templates/script_entry_point.mako`
"""
MAKO_TEMPLATE = "script_entry_po... | class ScriptVisualizationPlugin(VisualizationPlugin):
"""
A visualization plugin that starts by loading a single (js) script.
The script is loaded into a pre-defined mako template:
`config/plugins/visualizations/common/templates/script_entry_point.mako`
"""
MAKO_TEMPLATE = "script_entry_po... | render_vars["embedded"] = self._parse_embedded(embedded)
render_vars["static_url"] = url_for(f"/{self.static_path}/")
render_vars.update(vars={})
render_vars.update({"script_attributes": self.config["entry_point"]["attr"]})
template_filename = os.path.join(self.MAKO_TEMPLATE)
... | """
Override to add script attributes and point mako at the script entry point
template.
"""
render_vars["embedded"] = self._parse_embedded(embedded)
render_vars["static_url"] = url_for(f"/{self.static_path}/")
render_vars.update(vars={})
render_vars.updat... | 16 | 206 | 145 | 351 | """
Visualization plugins: instantiate/deserialize data and models
from a query string and render a webpage based on those data.
"""
import copy
import logging
import os
from typing import (
Any,
Dict,
)
import mako.lookup
from galaxy.visualization.plugins import (
resource_parser,
utils,
)
from gala... | """
Visualization plugins: instantiate/deserialize data and models
from a query string and render a webpage based on those data.
"""
import copy
import logging
import os
from typing import (
Any,
Dict,
)
import mako.lookup
from galaxy.visualization.plugins import (
resource_parser,
utils,
)
from gala... |
46,448 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/plugins/plugin.py | 51,52 | 25,68 | _build_template_path | ServesTemplatesPluginMixin | 52,54 | 52,54 | class ServesTemplatesPluginMixin:
"""
An object that renders (mako) template files from the server.
"""
path: str
#: default number of templates to search for plugin template lookup
DEFAULT_TEMPLATE_COLLECTION_SIZE = 10
def _set_up_template_plugin(self, template_cache_dir, additional_temp... | class ServesTemplatesPluginMixin:
"""
An object that renders (mako) template files from the server.
"""
path: str
#: default number of templates to search for plugin template lookup
DEFAULT_TEMPLATE_COLLECTION_SIZE = 10
def _set_up_template_plugin(self, template_cache_dir, additional_temp... | return os.path.join(self.path, "templates")
| return os.path.join(self.path, "templates")
| 3 | 438 | 20 | 458 | """
Visualization plugins: instantiate/deserialize data and models
from a query string and render a webpage based on those data.
"""
import copy
import logging
import os
from typing import (
Any,
Dict,
)
import mako.lookup
from galaxy.visualization.plugins import (
resource_parser,
utils,
)
from gala... | """
Visualization plugins: instantiate/deserialize data and models
from a query string and render a webpage based on those data.
"""
import copy
import logging
import os
from typing import (
Any,
Dict,
)
import mako.lookup
from galaxy.visualization.plugins import (
resource_parser,
utils,
)
from gala... |
46,449 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/visualization/plugins/plugin.py | 279,280 | 270,290 | _render | StaticFileVisualizationPlugin | 283,290 | 280,290 | class StaticFileVisualizationPlugin(VisualizationPlugin):
"""
A visualization plugin that starts by loading a static html file defined in
the visualization's config file.
"""
# TODO: these are not embeddable by their nature - update config
# TODO: should do render/render_saved here since most o... | class StaticFileVisualizationPlugin(VisualizationPlugin):
"""
A visualization plugin that starts by loading a static html file defined in
the visualization's config file.
"""
# TODO: these are not embeddable by their nature - update config
# TODO: should do render/render_saved here since most o... | render_vars["embedded"] = self._parse_embedded(embedded)
render_vars.update(vars={})
static_file_path = self.config["entry_point"]["file"]
static_file_path = os.path.join(self.path, static_file_path)
with open(static_file_path) as outfile:
return outfile.read()
| """
Render the static file simply by reading and returning it.
"""
render_vars["embedded"] = self._parse_embedded(embedded)
render_vars.update(vars={})
static_file_path = self.config["entry_point"]["file"]
static_file_path = os.path.join(self.path, static_file_pa... | 17 | 145 | 106 | 251 | """
Visualization plugins: instantiate/deserialize data and models
from a query string and render a webpage based on those data.
"""
import copy
import logging
import os
from typing import (
Any,
Dict,
)
import mako.lookup
from galaxy.visualization.plugins import (
resource_parser,
utils,
)
from gala... | """
Visualization plugins: instantiate/deserialize data and models
from a query string and render a webpage based on those data.
"""
import copy
import logging
import os
from typing import (
Any,
Dict,
)
import mako.lookup
from galaxy.visualization.plugins import (
resource_parser,
utils,
)
from gala... |
46,452 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/web/framework/helpers/tags.py | 10,11 | 1,89 | format_attrs | 25,29 | 11,29 | """
Code derived from WebHelpers: https://bitbucket.org/bbangert/webhelpers
Licensed under the MIT license: https://bitbucket.org/bbangert/webhelpers/src/tip/LICENSE
"""
from markupsafe import escape_silent
def format_attrs(**attrs):
FILL_FUNC_BODYdef javascript_link(*urls, **attrs):
"""Return script include ta... | """
Code derived from WebHelpers: https://bitbucket.org/bbangert/webhelpers
Licensed under the MIT license: https://bitbucket.org/bbangert/webhelpers/src/tip/LICENSE
"""
from markupsafe import escape_silent
def format_attrs(**attrs):
"""Format HTML attributes into a string of ' key="value"' pairs which
can ... | strings = [f' {attr}="{escape_silent(value)}"' for attr, value in sorted(attrs.items()) if value is not None]
return "".join(strings)
| """Format HTML attributes into a string of ' key="value"' pairs which
can be inserted into an HTML tag.
The attributes are sorted alphabetically. If any value is None, the entire
attribute is suppressed.
Usage:
>>> format_attrs(p=2, q=3) == u' p="2" q="3"'
True
>>> format_attrs(p=2, q... | 16 | 925 | 54 | 979 | """
Code derived from WebHelpers: https://bitbucket.org/bbangert/webhelpers
Licensed under the MIT license: https://bitbucket.org/bbangert/webhelpers/src/tip/LICENSE
"""
from markupsafe import escape_silent
def format_attrs(**attrs):
FILL_FUNC_BODYdef javascript_link(*urls, **attrs):
"""Return script include ta... | """
Code derived from WebHelpers: https://bitbucket.org/bbangert/webhelpers
Licensed under the MIT license: https://bitbucket.org/bbangert/webhelpers/src/tip/LICENSE
"""
from markupsafe import escape_silent
def format_attrs(**attrs):
"""Format HTML attributes into a string of ' key="value"' pairs which
can ... | |
46,454 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/web/framework/middleware/error.py | 268,269 | 224,286 | close | CatchingIter | 269,274 | 269,274 | class CatchingIter:
"""
A wrapper around the application iterator that will catch
exceptions raised by the a generator, or by the close method, and
display or report as necessary.
"""
def __init__(self, app_iter, environ, start_checker, error_middleware):
self.app_iterable = app_iter
... | class CatchingIter:
"""
A wrapper around the application iterator that will catch
exceptions raised by the a generator, or by the close method, and
display or report as necessary.
"""
def __init__(self, app_iter, environ, start_checker, error_middleware):
self.app_iterable = app_iter
... | # This should at least print something to stderr if the
# close method fails at this point
if not self.closed:
self._close()
| # This should at least print something to stderr if the
# close method fails at this point
if not self.closed:
self._close()
| 22 | 534 | 43 | 577 | # Like many things, this started life as part of Paste
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Error handler middleware
When an exception is thrown from the wrapper application, this l... | # Like many things, this started life as part of Paste
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Error handler middleware
When an exception is thrown from the wrapper application, this l... |
46,455 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/web/framework/middleware/error.py | 180,181 | 39,212 | make_catching_iter | ErrorMiddleware | 181,186 | 181,186 | class ErrorMiddleware:
"""
Error handling middleware
Usage::
error_catching_wsgi_app = ErrorMiddleware(wsgi_app)
Settings:
``debug``:
If true, then tracebacks will be shown in the browser.
``error_email``:
an email address (or list of addresses) to send excep... | class ErrorMiddleware:
"""
Error handling middleware
Usage::
error_catching_wsgi_app = ErrorMiddleware(wsgi_app)
Settings:
``debug``:
If true, then tracebacks will be shown in the browser.
``error_email``:
an email address (or list of addresses) to send excep... | if isinstance(app_iter, (list, tuple)):
# These don't raise
return app_iter
return CatchingIter(app_iter, environ, sr_checker, self)
| if isinstance(app_iter, (list, tuple)):
# These don't raise
return app_iter
return CatchingIter(app_iter, environ, sr_checker, self)
| 15 | 1,900 | 59 | 1,959 | # Like many things, this started life as part of Paste
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Error handler middleware
When an exception is thrown from the wrapper application, this l... | # Like many things, this started life as part of Paste
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Error handler middleware
When an exception is thrown from the wrapper application, this l... |
46,456 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/web/framework/middleware/error.py | 297,298 | 286,341 | extraData | Supplement | 298,328 | 298,328 | class Supplement:
"""
This is a supplement used to display standard WSGI information in
the traceback.
"""
def __init__(self, middleware, environ):
self.middleware = middleware
self.environ = environ
self.source_url = request.construct_url(environ)
def extraData(self):
... | class Supplement:
"""
This is a supplement used to display standard WSGI information in
the traceback.
"""
def __init__(self, middleware, environ):
self.middleware = middleware
self.environ = environ
self.source_url = request.construct_url(environ)
def extraData(self):
... | data = {}
cgi_vars = data[("extra", "CGI Variables")] = {}
wsgi_vars = data[("extra", "WSGI Variables")] = {}
hide_vars = [
"paste.config",
"wsgi.errors",
"wsgi.input",
"wsgi.multithread",
"wsgi.multiprocess",
"wsgi.... | data = {}
cgi_vars = data[("extra", "CGI Variables")] = {}
wsgi_vars = data[("extra", "WSGI Variables")] = {}
hide_vars = [
"paste.config",
"wsgi.errors",
"wsgi.input",
"wsgi.multithread",
"wsgi.multiprocess",
"wsgi.... | 87 | 275 | 415 | 690 | # Like many things, this started life as part of Paste
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Error handler middleware
When an exception is thrown from the wrapper application, this l... | # Like many things, this started life as part of Paste
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Error handler middleware
When an exception is thrown from the wrapper application, this l... |
46,458 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/web_stack/gunicorn_config.py | 10,11 | 1,79 | is_preload_app | 11,14 | 11,14 | """
Gunicorn config file based on https://gist.github.com/hynek/ba655c8756924a5febc5285c712a7946
"""
import gc
import os
import sys
def is_preload_app():
FILL_FUNC_BODYdef on_starting(server):
"""
Attach a set of IDs that can be temporarily re-used.
Used on reloads when each worker exists twice.
"""... | """
Gunicorn config file based on https://gist.github.com/hynek/ba655c8756924a5febc5285c712a7946
"""
import gc
import os
import sys
def is_preload_app():
FILL_FUNC_BODYdef on_starting(server):
"""
Attach a set of IDs that can be temporarily re-used.
Used on reloads when each worker exists twice.
"""... | return "--preload" in os.environ.get("GUNICORN_CMD_ARGS", "") or "--preload" in sys.argv
| return "--preload" in os.environ.get("GUNICORN_CMD_ARGS", "") or "--preload" in sys.argv
| 9 | 715 | 46 | 761 | """
Gunicorn config file based on https://gist.github.com/hynek/ba655c8756924a5febc5285c712a7946
"""
import gc
import os
import sys
def is_preload_app():
FILL_FUNC_BODYdef on_starting(server):
"""
Attach a set of IDs that can be temporarily re-used.
Used on reloads when each worker exists twice.
"""... | """
Gunicorn config file based on https://gist.github.com/hynek/ba655c8756924a5febc5285c712a7946
"""
import gc
import os
import sys
def is_preload_app():
FILL_FUNC_BODYdef on_starting(server):
"""
Attach a set of IDs that can be temporarily re-used.
Used on reloads when each worker exists twice.
"""... | |
46,459 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/web_stack/transport.py | 28,29 | 10,71 | start_if_needed | ApplicationStackTransport | 29,44 | 29,44 | class ApplicationStackTransport:
SHUTDOWN_MSG = "__SHUTDOWN__"
def __init__(self, app, stack, dispatcher=None):
"""Pre-fork initialization."""
self.app = app
self.stack = stack
self.can_run = False
self.running = False
self.dispatcher = dispatcher
self.di... | class ApplicationStackTransport:
SHUTDOWN_MSG = "__SHUTDOWN__"
def __init__(self, app, stack, dispatcher=None):
"""Pre-fork initialization."""
self.app = app
self.stack = stack
self.can_run = False
self.running = False
self.dispatcher = dispatcher
self.di... | # Don't unnecessarily start a thread that we don't need.
if (
self.can_run
and not self.running
and not self.dispatcher_thread
and self.dispatcher
and self.dispatcher.handler_count
):
self.running = True
self.dis... | # Don't unnecessarily start a thread that we don't need.
if (
self.can_run
and not self.running
and not self.dispatcher_thread
and self.dispatcher
and self.dispatcher.handler_count
):
self.running = True
self.dis... | 38 | 376 | 165 | 541 | """Web application stack operations
"""
import logging
import threading
log = logging.getLogger(__name__)
class ApplicationStackTransport:
SHUTDOWN_MSG = "__SHUTDOWN__"
def __init__(self, app, stack, dispatcher=None):
"""Pre-fork initialization."""
self.app = app
self.stack = stack
... | """Web application stack operations
"""
import logging
import threading
log = logging.getLogger(__name__)
class ApplicationStackTransport:
SHUTDOWN_MSG = "__SHUTDOWN__"
def __init__(self, app, stack, dispatcher=None):
"""Pre-fork initialization."""
self.app = app
self.stack = stack
... |
46,460 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/cbv.py | 72,73 | 1,122 | _init_cbv | 78,108 | 73,108 | """
Original implementation by David Montague (@dmontagu)
https://github.com/dmontagu/fastapi-utils
"""
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import (
Any,
ClassVar,
get_origin,
get_type_hints,
TypeVar,
)
from fastapi import (
APIRo... | """
Original implementation by David Montague (@dmontagu)
https://github.com/dmontagu/fastapi-utils
"""
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import (
Any,
ClassVar,
get_origin,
get_type_hints,
TypeVar,
)
from fastapi import (
APIRo... | if getattr(cls, CBV_CLASS_KEY, False): # pragma: no cover
return # Already initialized
old_init: Callable[..., Any] = cls.__init__
old_signature = inspect.signature(old_init)
old_parameters = list(old_signature.parameters.values())[1:] # drop `self` parameter
new_parameters = [
x ... | """
Idempotently modifies the provided `cls`, performing the following modifications:
* The `__init__` function is updated to set any class-annotated dependencies as instance attributes
* The `__signature__` attribute is updated to indicate to FastAPI what arguments should be passed to the initializer
... | 109 | 956 | 461 | 1,417 | """
Original implementation by David Montague (@dmontagu)
https://github.com/dmontagu/fastapi-utils
"""
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import (
Any,
ClassVar,
get_origin,
get_type_hints,
TypeVar,
)
from fastapi import (
APIRo... | """
Original implementation by David Montague (@dmontagu)
https://github.com/dmontagu/fastapi-utils
"""
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import (
Any,
ClassVar,
get_origin,
get_type_hints,
TypeVar,
)
from fastapi import (
APIRo... | |
46,463 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/container_resolution.py | 110,113 | 20,128 | resolve_with_install | ContainerResolutionAPIController | 125,128 | 113,128 | class ContainerResolutionAPIController(BaseGalaxyAPIController):
def __init__(self, app: StructuredApp):
super().__init__(app)
self._view = views.ContainerResolutionView(app)
@expose_api
@require_admin
def index(self, trans, **kwd):
"""
GET /api/container_resolvers
... | class ContainerResolutionAPIController(BaseGalaxyAPIController):
def __init__(self, app: StructuredApp):
super().__init__(app)
self._view = views.ContainerResolutionView(app)
@expose_api
@require_admin
def index(self, trans, **kwd):
"""
GET /api/container_resolvers
... | kwds.update(payload)
kwds["install"] = True
return self._view.resolve(**kwds)
| """
POST /api/container_resolvers/resolve/install
POST /api/container_resolvers/{index}/resolve/install
Do the resolution of dependencies like resolve(), but allow building
and installing new containers during installation. payload of POST body maybe
contain same paramet... | 6 | 1,085 | 37 | 1,122 | """
API operations allowing clients to manage container resolution.
"""
import logging
import requests
from galaxy.structured_app import StructuredApp
from galaxy.tool_util.deps import views
from galaxy.web import (
expose_api,
require_admin,
)
from . import BaseGalaxyAPIController
log = logging.getLogger(_... | """
API operations allowing clients to manage container resolution.
"""
import logging
import requests
from galaxy.structured_app import StructuredApp
from galaxy.tool_util.deps import views
from galaxy.web import (
expose_api,
require_admin,
)
from . import BaseGalaxyAPIController
log = logging.getLogger(_... |
46,464 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/datatypes.py | 86,97 | 58,168 | types_and_mapping | FastAPIDatatypes | 100,105 | 97,105 | @router.cbv
class FastAPIDatatypes:
datatypes_registry: Registry = depends(Registry)
@router.get(
"/api/datatypes",
public=True,
summary="Lists all available data types",
response_description="List of data types",
)
async def index(
self,
extension_only: ... | @router.cbv
class FastAPIDatatypes:
datatypes_registry: Registry = depends(Registry)
@router.get(
"/api/datatypes",
public=True,
summary="Lists all available data types",
response_description="List of data types",
)
async def index(
self,
extension_only: ... | return DatatypesCombinedMap(
datatypes=view_index(self.datatypes_registry, extension_only, upload_only),
datatypes_mapping=view_mapping(self.datatypes_registry),
)
| """Combines the datatype information from (/api/datatypes) and the
mapping information from (/api/datatypes/mapping) into a single
response."""
return DatatypesCombinedMap(
datatypes=view_index(self.datatypes_registry, extension_only, upload_only),
datatypes_mappi... | 7 | 1,274 | 67 | 1,341 | """
API operations allowing clients to determine datatype supported by Galaxy.
"""
import logging
from typing import (
cast,
Dict,
List,
Optional,
Union,
)
from fastapi import Query
from galaxy.datatypes.registry import Registry
from galaxy.managers.datatypes import (
DatatypeConverterList,
... | """
API operations allowing clients to determine datatype supported by Galaxy.
"""
import logging
from typing import (
cast,
Dict,
List,
Optional,
Union,
)
from fastapi import Query
from galaxy.datatypes.registry import Registry
from galaxy.managers.datatypes import (
DatatypeConverterList,
... |
46,465 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/dynamic_tools.py | 25,27 | 17,87 | index | DynamicToolsController | 35,38 | 27,38 | class DynamicToolsController(BaseAPIController):
"""
RESTful controller for interactions with dynamic tools.
Dynamic tools are tools defined in the database. Use the tools controller
to run these tools and view functional information.
"""
@expose_api_anonymous_and_sessionless
def index(sel... | class DynamicToolsController(BaseAPIController):
"""
RESTful controller for interactions with dynamic tools.
Dynamic tools are tools defined in the database. Use the tools controller
to run these tools and view functional information.
"""
@expose_api_anonymous_and_sessionless
def index(sel... | manager = self.app.dynamic_tools_manager
return [t.to_dict() for t in manager.list_tools()]
| """
GET /api/dynamic_tools
This returns meta-information about the dynamic tool, such as
tool_uuid. To use the tool or view funtional information such as
inputs and outputs, use the standard tools API indexed by the
ID (and optionally version) returned from this endpoint... | 9 | 696 | 37 | 733 | import logging
from galaxy import (
util,
web,
)
from galaxy.exceptions import ObjectNotFound
from galaxy.web import (
expose_api,
expose_api_anonymous_and_sessionless,
)
from galaxy.webapps.base.controller import BaseAPIController
log = logging.getLogger(__name__)
class DynamicToolsController(BaseA... | import logging
from galaxy import (
util,
web,
)
from galaxy.exceptions import ObjectNotFound
from galaxy.web import (
expose_api,
expose_api_anonymous_and_sessionless,
)
from galaxy.webapps.base.controller import BaseAPIController
log = logging.getLogger(__name__)
class DynamicToolsController(BaseA... |
46,467 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/job_lock.py | 15,17 | 1,25 | job_lock_status | 18,21 | 17,21 | from fastapi import Body
from galaxy.managers.jobs import (
JobLock,
JobManager,
)
from . import (
depends,
Router,
)
router = Router(tags=["job_lock"])
@router.get("/api/job_lock", require_admin=True)
def job_lock_status(job_manager: JobManager = depends(JobManager)) -> JobLock:
FILL_FUNC_BODY@rout... | from fastapi import Body
from galaxy.managers.jobs import (
JobLock,
JobManager,
)
from . import (
depends,
Router,
)
router = Router(tags=["job_lock"])
@router.get("/api/job_lock", require_admin=True)
def job_lock_status(job_manager: JobManager = depends(JobManager)) -> JobLock:
"""Get job lock... | return job_manager.job_lock()
| """Get job lock status."""
return job_manager.job_lock()
| 2 | 203 | 16 | 219 | from fastapi import Body
from galaxy.managers.jobs import (
JobLock,
JobManager,
)
from . import (
depends,
Router,
)
router = Router(tags=["job_lock"])
@router.get("/api/job_lock", require_admin=True)
def job_lock_status(job_manager: JobManager = depends(JobManager)) -> JobLock:
FILL_FUNC_BODY@rout... | from fastapi import Body
from galaxy.managers.jobs import (
JobLock,
JobManager,
)
from . import (
depends,
Router,
)
router = Router(tags=["job_lock"])
@router.get("/api/job_lock", require_admin=True)
def job_lock_status(job_manager: JobManager = depends(JobManager)) -> JobLock:
"""Get job lock... | |
46,468 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/job_ports.py | 24,26 | 11,47 | create | JobPortsAPIController | 45,47 | 26,47 | class JobPortsAPIController(BaseGalaxyAPIController):
"""This job files controller allows remote job running mechanisms to
modify the current state of ports for queued and running jobs.
It is certainly not meant to represent part of Galaxy's stable, user
facing API.
See the JobFiles API for informa... | class JobPortsAPIController(BaseGalaxyAPIController):
"""This job files controller allows remote job running mechanisms to
modify the current state of ports for queued and running jobs.
It is certainly not meant to represent part of Galaxy's stable, user
facing API.
See the JobFiles API for informa... | payload.update(kwargs)
return self._job_ports_view.register_container_information(job_id, **payload)
| """
create( self, trans, job_id, payload, **kwargs )
* POST /api/jobs/{job_id}/ports
Populate port information for interactive tools.
:type job_id: str
:param job_id: encoded id string of the job
:type payload: dict
:param payload: diction... | 4 | 335 | 35 | 370 | """ API for asynchronous job running mechanisms can use to fetch or put files
related to running and queued jobs.
"""
from galaxy.job_execution.ports import JobPortsView
from galaxy.structured_app import StructuredApp
from galaxy.web import expose_api_anonymous_and_sessionless
from . import BaseGalaxyAPIController
c... | """ API for asynchronous job running mechanisms can use to fetch or put files
related to running and queued jobs.
"""
from galaxy.job_execution.ports import JobPortsView
from galaxy.structured_app import StructuredApp
from galaxy.web import expose_api_anonymous_and_sessionless
from . import BaseGalaxyAPIController
c... |
46,469 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/job_tokens.py | 55,56 | 26,71 | __authorize_job_access | FastAPIJobTokens | 56,71 | 56,71 | @router.cbv
class FastAPIJobTokens:
@router.get(
"/api/jobs/{job_id}/oidc-tokens",
summary="Get a fresh OIDC token",
description="Allows remote job running mechanisms to get a fresh OIDC token that "
"can be used on remote side to authorize user. "
"It is not meant to represe... | @router.cbv
class FastAPIJobTokens:
@router.get(
"/api/jobs/{job_id}/oidc-tokens",
summary="Get a fresh OIDC token",
description="Allows remote job running mechanisms to get a fresh OIDC token that "
"can be used on remote side to authorize user. "
"It is not meant to represe... | session = trans.sa_session
job_id = trans.security.decode_id(encoded_job_id)
job = session.get(Job, job_id)
secret = job.destination_params.get("job_secret_base", "jobs_token")
job_key_internal = trans.security.encode_id(job_id, kind=secret)
if not util.safe_str_cmp(job_... | session = trans.sa_session
job_id = trans.security.decode_id(encoded_job_id)
job = session.get(Job, job_id)
secret = job.destination_params.get("job_secret_base", "jobs_token")
job_key_internal = trans.security.encode_id(job_id, kind=secret)
if not util.safe_str_cmp(job_... | 55 | 376 | 218 | 594 | """ API asynchronous job running mechanisms can use to get a fresh OIDC token.
"""
import logging
from fastapi import Query
from fastapi.responses import PlainTextResponse
from galaxy import (
exceptions,
util,
)
from galaxy.authnz.util import provider_name_to_backend
from galaxy.managers.context import Prov... | """ API asynchronous job running mechanisms can use to get a fresh OIDC token.
"""
import logging
from fastapi import Query
from fastapi.responses import PlainTextResponse
from galaxy import (
exceptions,
util,
)
from galaxy.authnz.util import provider_name_to_backend
from galaxy.managers.context import Prov... |
46,470 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/sanitize_allow.py | 57,58 | 17,106 | _generate_allowlist | SanitizeAllowController | 58,106 | 58,106 | class SanitizeAllowController(BaseAPIController):
@web.require_admin
@web.expose_api
def index(self, trans, **kwd):
"""
GET /api/sanitize_allow
Return an object showing the current state of the toolbox and allow list.
"""
return self._generate_allowlist(trans)
@w... | class SanitizeAllowController(BaseAPIController):
@web.require_admin
@web.expose_api
def index(self, trans, **kwd):
"""
GET /api/sanitize_allow
Return an object showing the current state of the toolbox and allow list.
"""
return self._generate_allowlist(trans)
@w... | sanitize_dict: Dict[str, Any] = dict(
blocked_toolshed=[], allowed_toolshed=[], blocked_local=[], allowed_local=[]
)
ids = None
for tool_id in trans.app.config.sanitize_allowlist:
installed_name = ""
installed_ids = {"full": "", "allowed": tool_id, "ow... | sanitize_dict: Dict[str, Any] = dict(
blocked_toolshed=[], allowed_toolshed=[], blocked_local=[], allowed_local=[]
)
ids = None
for tool_id in trans.app.config.sanitize_allowlist:
installed_name = ""
installed_ids = {"full": "", "allowed": tool_id, "ow... | 122 | 508 | 702 | 1,210 | """
API operations allowing clients to retrieve and modify the HTML sanitization allow list.
"""
import logging
from typing import (
Any,
Dict,
)
from galaxy import web
from galaxy.webapps.base.controller import BaseAPIController
log = logging.getLogger(__name__)
class SanitizeAllowController(BaseAPIContro... | """
API operations allowing clients to retrieve and modify the HTML sanitization allow list.
"""
import logging
from typing import (
Any,
Dict,
)
from galaxy import web
from galaxy.webapps.base.controller import BaseAPIController
log = logging.getLogger(__name__)
class SanitizeAllowController(BaseAPIContro... |
46,472 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/toolshed.py | 30,33 | 16,55 | request | ToolShedController | 36,55 | 33,55 | class ToolShedController(BaseGalaxyAPIController):
"""RESTful controller for interactions with Toolsheds."""
@expose_api
def index(self, trans, **kwd):
"""
GET /api/tool_shed
Interact with the Toolshed registry of this instance.
"""
tool_sheds = []
for name, ... | class ToolShedController(BaseGalaxyAPIController):
"""RESTful controller for interactions with Toolsheds."""
@expose_api
def index(self, trans, **kwd):
"""
GET /api/tool_shed
Interact with the Toolshed registry of this instance.
"""
tool_sheds = []
for name, ... | tool_shed_url = params.pop("tool_shed_url")
controller = params.pop("controller")
if controller is None:
raise MessageException("Please provide a toolshed controller name.")
tool_shed_registry = trans.app.tool_shed_registry
if tool_shed_registry is None:
r... | """
GET /api/tool_shed/request
"""
tool_shed_url = params.pop("tool_shed_url")
controller = params.pop("controller")
if controller is None:
raise MessageException("Please provide a toolshed controller name.")
tool_shed_registry = trans.app.tool_shed_re... | 66 | 200 | 271 | 471 | import json
import logging
from urllib.parse import quote
from galaxy.exceptions import MessageException
from galaxy.util import url_get
from galaxy.web import (
expose_api,
require_admin,
)
from . import BaseGalaxyAPIController
log = logging.getLogger(__name__)
class ToolShedController(BaseGalaxyAPIControl... | import json
import logging
from urllib.parse import quote
from galaxy.exceptions import MessageException
from galaxy.util import url_get
from galaxy.web import (
expose_api,
require_admin,
)
from . import BaseGalaxyAPIController
log = logging.getLogger(__name__)
class ToolShedController(BaseGalaxyAPIControl... |
46,473 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/uploads.py | 16,18 | 13,23 | hooks | UploadsAPIController | 21,23 | 18,23 | class UploadsAPIController(BaseGalaxyAPIController):
READ_CHUNK_SIZE = 2**16
@expose_api_anonymous
def hooks(self, trans, **kwds):
FILL_FUNC_BODY | class UploadsAPIController(BaseGalaxyAPIController):
READ_CHUNK_SIZE = 2**16
@expose_api_anonymous
def hooks(self, trans, **kwds):
"""
Exposed as POST /api/upload/hooks and /api/upload/resumable_upload
"""
FILL_FUNC_BODY | # Internal endpoint, only purpose is to authenticate user, but may grow additional functionality in the future
return None
| """
Exposed as POST /api/upload/hooks and /api/upload/resumable_upload
"""
# Internal endpoint, only purpose is to authenticate user, but may grow additional functionality in the future
return None
| 19 | 93 | 28 | 121 | """
API operations for uploaded files in storage.
"""
import logging
from galaxy.web.framework.decorators import expose_api_anonymous
from . import BaseGalaxyAPIController
log = logging.getLogger(__name__)
class UploadsAPIController(BaseGalaxyAPIController):
READ_CHUNK_SIZE = 2**16
@expose_api_anonymous
... | """
API operations for uploaded files in storage.
"""
import logging
from galaxy.web.framework.decorators import expose_api_anonymous
from . import BaseGalaxyAPIController
log = logging.getLogger(__name__)
class UploadsAPIController(BaseGalaxyAPIController):
READ_CHUNK_SIZE = 2**16
@expose_api_anonymous
... |
46,474 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/api/webhooks.py | 26,28 | 16,53 | webhook_data | WebhooksController | 33,53 | 28,53 | class WebhooksController(BaseGalaxyAPIController):
@expose_api_anonymous_and_sessionless
def all_webhooks(self, trans: GalaxyWebTransaction, **kwd):
"""
GET /api/webhooks/
Return all webhooks.
"""
return [webhook.to_dict() for webhook in self.app.webhooks_registry.webhoo... | class WebhooksController(BaseGalaxyAPIController):
@expose_api_anonymous_and_sessionless
def all_webhooks(self, trans: GalaxyWebTransaction, **kwd):
"""
GET /api/webhooks/
Return all webhooks.
"""
return [webhook.to_dict() for webhook in self.app.webhooks_registry.webhoo... | params = {}
for key, value in kwd.items():
params[key] = value
webhook = next(webhook for webhook in self.app.webhooks_registry.webhooks if webhook.id == webhook_id)
if webhook and webhook.helper != "":
spec = importlib.util.spec_from_file_location(webhook.path... | """
GET /api/webhooks/{webhook_id}/data/{params}
Return the result of executing helper function.
"""
params = {}
for key, value in kwd.items():
params[key] = value
webhook = next(webhook for webhook in self.app.webhooks_registry.webhooks if webhook.... | 49 | 189 | 197 | 386 | """
API Controller providing Galaxy Webhooks
"""
import importlib.util
import logging
from typing import Any
from galaxy.web import expose_api_anonymous_and_sessionless
from galaxy.webapps.base.webapp import GalaxyWebTransaction
from . import BaseGalaxyAPIController
log = logging.getLogger(__name__)
class Webhooks... | """
API Controller providing Galaxy Webhooks
"""
import importlib.util
import logging
from typing import Any
from galaxy.web import expose_api_anonymous_and_sessionless
from galaxy.webapps.base.webapp import GalaxyWebTransaction
from . import BaseGalaxyAPIController
log = logging.getLogger(__name__)
class Webhooks... |
46,476 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/controllers/admin_toolshed.py | 54,58 | 36,157 | restore_repository | AdminToolshed | 58,65 | 58,65 | class AdminToolshed(AdminGalaxy):
@web.json
@web.require_admin
@legacy_tool_shed_endpoint
def activate_repository(self, trans, **kwd):
"""Activate a repository that was deactivated but not uninstalled."""
return self._activate_repository(trans, **kwd)
def _activate_repository(self, ... | class AdminToolshed(AdminGalaxy):
@web.json
@web.require_admin
@legacy_tool_shed_endpoint
def activate_repository(self, trans, **kwd):
"""Activate a repository that was deactivated but not uninstalled."""
return self._activate_repository(trans, **kwd)
def _activate_repository(self, ... | repository_id = kwd["id"]
repository = get_installed_tool_shed_repository(trans.app, repository_id)
if repository.uninstalled:
raise Exception("Cannot restore uninstalled repositories, just re-install.")
else:
return self._activate_repository(trans, **kwd)
| repository_id = kwd["id"]
repository = get_installed_tool_shed_repository(trans.app, repository_id)
if repository.uninstalled:
raise Exception("Cannot restore uninstalled repositories, just re-install.")
else:
return self._activate_repository(trans, **kwd)
| 20 | 1,744 | 87 | 1,831 | import json
import logging
import os
from functools import wraps
from galaxy import (
util,
web,
)
from galaxy.exceptions import ConfigDoesNotAllowException
from galaxy.model.base import transaction
from galaxy.tool_shed.util import dependency_display
from galaxy.tool_shed.util.repository_util import (
get... | import json
import logging
import os
from functools import wraps
from galaxy import (
util,
web,
)
from galaxy.exceptions import ConfigDoesNotAllowException
from galaxy.model.base import transaction
from galaxy.tool_shed.util import dependency_display
from galaxy.tool_shed.util.repository_util import (
get... |
46,478 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/controllers/error.py | 8,10 | 7,11 | index | Error | 10,11 | 10,11 | class Error(BaseUIController):
@web.expose
def index(self, trans):
FILL_FUNC_BODY | class Error(BaseUIController):
@web.expose
def index(self, trans):
FILL_FUNC_BODY | raise Exception("Fake error")
| raise Exception("Fake error")
| 3 | 34 | 10 | 44 | from galaxy.webapps.base.controller import (
BaseUIController,
web,
)
class Error(BaseUIController):
@web.expose
def index(self, trans):
FILL_FUNC_BODY | from galaxy.webapps.base.controller import (
BaseUIController,
web,
)
class Error(BaseUIController):
@web.expose
def index(self, trans):
FILL_FUNC_BODY |
46,479 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/controllers/shed_tool_static.py | 15,16 | 1,59 | _asset_exists_and_is_safe | 16,21 | 16,21 | import logging
import os
from galaxy import web
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.util.path import (
join,
safe_contains,
)
from galaxy.webapps.base.controller import BaseUIController
log = logging.getLogger(__name__)
def _asset_exists_and_is_safe(repo_path, asset_pa... | import logging
import os
from galaxy import web
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.util.path import (
join,
safe_contains,
)
from galaxy.webapps.base.controller import BaseUIController
log = logging.getLogger(__name__)
def _asset_exists_and_is_safe(repo_path, asset_pa... | if not safe_contains(repo_path, asset_path):
raise RequestParameterInvalidException()
return os.path.exists(asset_path)
| if not safe_contains(repo_path, asset_path):
raise RequestParameterInvalidException()
return os.path.exists(asset_path)
| 8 | 646 | 45 | 691 | import logging
import os
from galaxy import web
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.util.path import (
join,
safe_contains,
)
from galaxy.webapps.base.controller import BaseUIController
log = logging.getLogger(__name__)
def _asset_exists_and_is_safe(repo_path, asset_pa... | import logging
import os
from galaxy import web
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.util.path import (
join,
safe_contains,
)
from galaxy.webapps.base.controller import BaseUIController
log = logging.getLogger(__name__)
def _asset_exists_and_is_safe(repo_path, asset_pa... | |
46,480 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/controllers/shed_tool_static.py | 22,24 | 21,59 | index | ShedToolStatic | 35,59 | 24,59 | class ShedToolStatic(BaseUIController):
@web.expose
def index(self, trans, shed, owner, repo, tool, version, image_file, **kwargs):
FILL_FUNC_BODY | class ShedToolStatic(BaseUIController):
@web.expose
def index(self, trans, shed, owner, repo, tool, version, image_file, **kwargs):
"""
Open an image file that is contained in an installed tool shed repository or that is referenced by a URL for display. The
image can be defined in eithe... | guid = "/".join((shed, "repos", owner, repo, tool, version))
tool = trans.app.toolbox.get_tool(guid)
repo_path = os.path.abspath(tool._repository_dir)
found_path = None
if "static/images" not in image_file:
asset_path = os.path.abspath(join(repo_path, "static", "imag... | """
Open an image file that is contained in an installed tool shed repository or that is referenced by a URL for display. The
image can be defined in either a README.rst file contained in the repository or the help section of a Galaxy tool config that
is contained in the repository. Th... | 66 | 234 | 343 | 577 | import logging
import os
from galaxy import web
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.util.path import (
join,
safe_contains,
)
from galaxy.webapps.base.controller import BaseUIController
log = logging.getLogger(__name__)
def _asset_exists_and_is_safe(repo_path, asset_pa... | import logging
import os
from galaxy import web
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.util.path import (
join,
safe_contains,
)
from galaxy.webapps.base.controller import BaseUIController
log = logging.getLogger(__name__)
def _asset_exists_and_is_safe(repo_path, asset_pa... |
46,483 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/fast_factory.py | 53,54 | 1,67 | factory | 54,67 | 54,67 | """Module containing factory class for building uvicorn app for Galaxy.
Information on uvicorn, its various settings, and how to invoke it can
be found at https://www.uvicorn.org/.
Galaxy can be launched with uvicorn using the following invocation:
::
uvicorn --app-dir lib --factory galaxy.webapps.galaxy.fast_f... | """Module containing factory class for building uvicorn app for Galaxy.
Information on uvicorn, its various settings, and how to invoke it can
be found at https://www.uvicorn.org/.
Galaxy can be launched with uvicorn using the following invocation:
::
uvicorn --app-dir lib --factory galaxy.webapps.galaxy.fast_f... | props = WebappSetupProps(
app_name="galaxy",
default_section_name=DEFAULT_CONFIG_SECTION,
env_config_file="GALAXY_CONFIG_FILE",
env_config_section="GALAXY_CONFIG_SECTION",
check_galaxy_root=True,
)
config_provider = WebappConfigResolver(props)
config = config_prov... | props = WebappSetupProps(
app_name="galaxy",
default_section_name=DEFAULT_CONFIG_SECTION,
env_config_file="GALAXY_CONFIG_FILE",
env_config_section="GALAXY_CONFIG_SECTION",
check_galaxy_root=True,
)
config_provider = WebappConfigResolver(props)
config = config_prov... | 26 | 524 | 214 | 738 | """Module containing factory class for building uvicorn app for Galaxy.
Information on uvicorn, its various settings, and how to invoke it can
be found at https://www.uvicorn.org/.
Galaxy can be launched with uvicorn using the following invocation:
::
uvicorn --app-dir lib --factory galaxy.webapps.galaxy.fast_f... | """Module containing factory class for building uvicorn app for Galaxy.
Information on uvicorn, its various settings, and how to invoke it can
be found at https://www.uvicorn.org/.
Galaxy can be launched with uvicorn using the following invocation:
::
uvicorn --app-dir lib --factory galaxy.webapps.galaxy.fast_f... | |
46,485 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/authenticate.py | 51,52 | 31,98 | _decode_baseauth | AuthenticationService | 67,98 | 52,98 | class AuthenticationService:
def __init__(self, user_manager: UserManager, auth_manager: AuthManager, api_keys_manager: ApiKeyManager):
self._user_manager = user_manager
self._auth_manager = auth_manager
self._api_keys_manager = api_keys_manager
def get_api_key(self, environ: Dict[str, ... | class AuthenticationService:
def __init__(self, user_manager: UserManager, auth_manager: AuthManager, api_keys_manager: ApiKeyManager):
self._user_manager = user_manager
self._auth_manager = auth_manager
self._api_keys_manager = api_keys_manager
def get_api_key(self, environ: Dict[str, ... | if encoded_str is None:
raise exceptions.RequestParameterInvalidException("Authentication is missing")
split = str(encoded_str).strip().split(" ")
# If split is only one element, try to decode the email and password
# directly.
if len(split) == 1:
try:
... | """
Decode an encrypted HTTP basic authentication string. Returns a tuple of
the form (email, password), and raises a HTTPBadRequest exception if
nothing could be decoded.
:param encoded_str: BaseAuth string encoded base64
:type encoded_str: string
:returns: ... | 127 | 438 | 362 | 800 | from base64 import b64decode
from typing import (
Any,
Dict,
Optional,
Tuple,
Union,
)
from urllib.parse import unquote
from pydantic import BaseModel
from starlette.requests import Request as StartletteRequest
from galaxy import exceptions
from galaxy.auth import AuthManager
from galaxy.managers.... | from base64 import b64decode
from typing import (
Any,
Dict,
Optional,
Tuple,
Union,
)
from urllib.parse import unquote
from pydantic import BaseModel
from starlette.requests import Request as StartletteRequest
from galaxy import exceptions
from galaxy.auth import AuthManager
from galaxy.managers.... |
46,486 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/base.py | 176,177 | 1,196 | async_task_summary | 177,196 | 177,196 | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... | name = None
try:
name = async_result.name
except AttributeError:
# if backend is disabled, we won't have this
pass
queue = None
try:
queue = async_result.queue
except AttributeError:
# if backend is disabled, we won't have this
pass
return Asy... | name = None
try:
name = async_result.name
except AttributeError:
# if backend is disabled, we won't have this
pass
queue = None
try:
queue = async_result.queue
except AttributeError:
# if backend is disabled, we won't have this
pass
return Asy... | 45 | 1,755 | 151 | 1,906 | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... | |
46,487 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/base.py | 157,164 | 156,176 | create_objects_from_store | ConsumesModelStores | 164,176 | 164,176 | class ConsumesModelStores:
def create_objects_from_store(
self,
trans,
payload,
history=None,
for_library=False,
):
FILL_FUNC_BODY | class ConsumesModelStores:
def create_objects_from_store(
self,
trans,
payload,
history=None,
for_library=False,
):
FILL_FUNC_BODY | galaxy_user = None
if isinstance(trans.user, User):
galaxy_user = trans.user
return create_objects_from_store(
app=trans.app,
galaxy_user=galaxy_user,
payload=payload,
history=history,
for_library=for_library,
)
| galaxy_user = None
if isinstance(trans.user, User):
galaxy_user = trans.user
return create_objects_from_store(
app=trans.app,
galaxy_user=galaxy_user,
payload=payload,
history=history,
for_library=for_library,
)
| 17 | 60 | 98 | 158 | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... |
46,488 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/base.py | 150,151 | 149,156 | serve_export_store | ServesExportStores | 151,156 | 151,156 | class ServesExportStores:
def serve_export_store(self, app, download_format: str):
FILL_FUNC_BODY | class ServesExportStores:
def serve_export_store(self, app, download_format: str):
FILL_FUNC_BODY | export_target = NamedTemporaryFile("wb")
export_store = get_export_store_factory(app, download_format)(export_target.name)
return ServedExportStore(export_store, export_target)
| export_target = NamedTemporaryFile("wb")
export_store = get_export_store_factory(app, download_format)(export_target.name)
return ServedExportStore(export_store, export_target)
| 10 | 38 | 64 | 102 | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... |
46,489 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/base.py | 112,113 | 52,131 | get_object | ServiceBase | 116,120 | 113,120 | class ServiceBase:
"""Base class with common logic and utils reused by other services.
A service class:
- Provides top level operations (`Index`, `Show`, `Delete`...) that are usually
consumed directly by the API controllers or other services.
- Uses a combination of managers to perform the op... | class ServiceBase:
"""Base class with common logic and utils reused by other services.
A service class:
- Provides top level operations (`Index`, `Show`, `Delete`...) that are usually
consumed directly by the API controllers or other services.
- Uses a combination of managers to perform the op... | return get_object(
trans, id, class_name, check_ownership=check_ownership, check_accessible=check_accessible, deleted=deleted
)
| """
Convenience method to get a model object with the specified checks.
"""
return get_object(
trans, id, class_name, check_ownership=check_ownership, check_accessible=check_accessible, deleted=deleted
)
| 9 | 915 | 49 | 964 | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... | import mimetypes
from tempfile import NamedTemporaryFile
from typing import (
Any,
cast,
List,
NamedTuple,
Optional,
)
from celery.result import AsyncResult
from galaxy.exceptions import (
AuthenticationRequired,
ConfigDoesNotAllowException,
)
from galaxy.managers.base import (
decode_... |
46,491 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/help.py | 29,30 | 14,45 | search_forum | HelpService | 31,45 | 30,45 | class HelpService(ServiceBase):
"""Common interface/service logic for interactions with Galaxy Help API.
Provides the logic of the actions invoked by API controllers and uses type definitions
and pydantic models to declare its parameters and return types.
"""
def __init__(
self,
se... | class HelpService(ServiceBase):
"""Common interface/service logic for interactions with Galaxy Help API.
Provides the logic of the actions invoked by API controllers and uses type definitions
and pydantic models to declare its parameters and return types.
"""
def __init__(
self,
se... | if not self.config.enable_help_forum_tool_panel_integration:
raise ServerNotConfiguredForRequest(
"Integration with the Galaxy Help Forum is not enabled in the configuration."
)
if not self.config.help_forum_api_url:
raise ServerNotConfiguredForRequest... | """Search the Galaxy Help forum using the Discourse API."""
if not self.config.enable_help_forum_tool_panel_integration:
raise ServerNotConfiguredForRequest(
"Integration with the Galaxy Help Forum is not enabled in the configuration."
)
if not self.config... | 43 | 155 | 182 | 337 | import logging
import requests
from galaxy.config import GalaxyAppConfiguration
from galaxy.exceptions import ServerNotConfiguredForRequest
from galaxy.schema.help import HelpForumSearchResponse
from galaxy.security.idencoding import IdEncodingHelper
from galaxy.webapps.galaxy.services.base import ServiceBase
log = ... | import logging
import requests
from galaxy.config import GalaxyAppConfiguration
from galaxy.exceptions import ServerNotConfiguredForRequest
from galaxy.schema.help import HelpForumSearchResponse
from galaxy.security.idencoding import IdEncodingHelper
from galaxy.webapps.galaxy.services.base import ServiceBase
log = ... |
46,496 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/quotas.py | 164,165 | 1,168 | get_quotas | 165,168 | 165,168 | import logging
from typing import Optional
from sqlalchemy import (
false,
select,
true,
)
from galaxy import util
from galaxy.managers.context import ProvidesUserContext
from galaxy.managers.groups import get_group_by_name
from galaxy.managers.quotas import QuotaManager
from galaxy.managers.users import ... | import logging
from typing import Optional
from sqlalchemy import (
false,
select,
true,
)
from galaxy import util
from galaxy.managers.context import ProvidesUserContext
from galaxy.managers.groups import get_group_by_name
from galaxy.managers.quotas import QuotaManager
from galaxy.managers.users import ... | is_deleted = true() if deleted else false()
stmt = select(Quota).where(Quota.deleted == is_deleted)
return session.scalars(stmt)
| is_deleted = true() if deleted else false()
stmt = select(Quota).where(Quota.deleted == is_deleted)
return session.scalars(stmt)
| 14 | 1,892 | 50 | 1,942 | import logging
from typing import Optional
from sqlalchemy import (
false,
select,
true,
)
from galaxy import util
from galaxy.managers.context import ProvidesUserContext
from galaxy.managers.groups import get_group_by_name
from galaxy.managers.quotas import QuotaManager
from galaxy.managers.users import ... | import logging
from typing import Optional
from sqlalchemy import (
false,
select,
true,
)
from galaxy import util
from galaxy.managers.context import ProvidesUserContext
from galaxy.managers.groups import get_group_by_name
from galaxy.managers.quotas import QuotaManager
from galaxy.managers.users import ... | |
46,497 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/quotas.py | 129,130 | 37,164 | get_user_id | QuotasService | 130,135 | 130,135 | class QuotasService(ServiceBase):
"""Interface/service object shared by controllers for interacting with quotas."""
def __init__(self, security: IdEncodingHelper, quota_manager: QuotaManager):
super().__init__(security)
self.quota_manager = quota_manager
def index(self, trans: ProvidesUser... | class QuotasService(ServiceBase):
"""Interface/service object shared by controllers for interacting with quotas."""
def __init__(self, security: IdEncodingHelper, quota_manager: QuotaManager):
super().__init__(security)
self.quota_manager = quota_manager
def index(self, trans: ProvidesUser... | try:
return trans.security.decode_id(item)
except Exception:
return get_user_by_email(trans.sa_session, item).id
| try:
return trans.security.decode_id(item)
except Exception:
return get_user_by_email(trans.sa_session, item).id
| 8 | 1,573 | 48 | 1,621 | import logging
from typing import Optional
from sqlalchemy import (
false,
select,
true,
)
from galaxy import util
from galaxy.managers.context import ProvidesUserContext
from galaxy.managers.groups import get_group_by_name
from galaxy.managers.quotas import QuotaManager
from galaxy.managers.users import ... | import logging
from typing import Optional
from sqlalchemy import (
false,
select,
true,
)
from galaxy import util
from galaxy.managers.context import ProvidesUserContext
from galaxy.managers.groups import get_group_by_name
from galaxy.managers.quotas import QuotaManager
from galaxy.managers.users import ... |
46,498 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/storage_cleaner.py | 39,40 | 22,72 | get_discarded_summary | StorageCleanerService | 40,43 | 40,43 | class StorageCleanerService(ServiceBase):
"""Service providing actions to monitor and recover storage space used by the user."""
def __init__(
self,
user_manager: UserManager,
history_cleaner: HistoryStorageCleanerManager,
hda_cleaner: HDAStorageCleanerManager,
):
se... | class StorageCleanerService(ServiceBase):
"""Service providing actions to monitor and recover storage space used by the user."""
def __init__(
self,
user_manager: UserManager,
history_cleaner: HistoryStorageCleanerManager,
hda_cleaner: HDAStorageCleanerManager,
):
se... | user = self.get_authenticated_user(trans)
return self.storage_cleaner_map[stored_item_type].get_discarded_summary(user)
| user = self.get_authenticated_user(trans)
return self.storage_cleaner_map[stored_item_type].get_discarded_summary(user)
| 5 | 620 | 49 | 669 | import logging
from typing import (
Dict,
Optional,
Set,
)
from galaxy.managers.base import StorageCleanerManager
from galaxy.managers.context import ProvidesHistoryContext
from galaxy.managers.hdas import HDAStorageCleanerManager
from galaxy.managers.histories import HistoryStorageCleanerManager
from gala... | import logging
from typing import (
Dict,
Optional,
Set,
)
from galaxy.managers.base import StorageCleanerManager
from galaxy.managers.context import ProvidesHistoryContext
from galaxy.managers.hdas import HDAStorageCleanerManager
from galaxy.managers.histories import HistoryStorageCleanerManager
from gala... |
46,499 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/galaxy/services/visualizations.py | 42,48 | 21,63 | index | VisualizationsService | 53,63 | 48,63 | class VisualizationsService(ServiceBase):
"""Common interface/service logic for interactions with visualizations in the context of the API.
Provides the logic of the actions invoked by API controllers and uses type definitions
and pydantic models to declare its parameters and return types.
"""
def... | class VisualizationsService(ServiceBase):
"""Common interface/service logic for interactions with visualizations in the context of the API.
Provides the logic of the actions invoked by API controllers and uses type definitions
and pydantic models to declare its parameters and return types.
"""
def... | if not trans.user_is_admin:
user_id = trans.user and trans.user.id
if payload.user_id and payload.user_id != user_id:
raise exceptions.AdminRequiredException("Only admins can index the visualizations of others")
entries, total_matches = self.manager.index_query(t... | """Return a list of Visualizations viewable by the user
:rtype: list
:returns: dictionaries containing Visualization details
"""
if not trans.user_is_admin:
user_id = trans.user and trans.user.id
if payload.user_id and payload.user_id != user_id:
... | 38 | 290 | 141 | 431 | import logging
from typing import Tuple
from galaxy import exceptions
from galaxy.managers.visualizations import (
VisualizationManager,
VisualizationSerializer,
)
from galaxy.schema.visualization import (
VisualizationIndexQueryPayload,
VisualizationSummaryList,
)
from galaxy.security.idencoding impor... | import logging
from typing import Tuple
from galaxy import exceptions
from galaxy.managers.visualizations import (
VisualizationManager,
VisualizationSerializer,
)
from galaxy.schema.visualization import (
VisualizationIndexQueryPayload,
VisualizationSummaryList,
)
from galaxy.security.idencoding impor... |
46,501 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/openapi/utils.py | 31,48 | 1,121 | get_openapi | 48,121 | 48,121 | """
Copy of https://github.com/tiangolo/fastapi/blob/master/fastapi/openapi/utils.py with changes from https://github.com/tiangolo/fastapi/pull/10903
"""
from typing import (
Any,
Dict,
List,
Optional,
Sequence,
Set,
Union,
)
from fastapi import routing
from fastapi._compat import (
Ge... | """
Copy of https://github.com/tiangolo/fastapi/blob/master/fastapi/openapi/utils.py with changes from https://github.com/tiangolo/fastapi/pull/10903
"""
from typing import (
Any,
Dict,
List,
Optional,
Sequence,
Set,
Union,
)
from fastapi import routing
from fastapi._compat import (
Ge... | info: Dict[str, Any] = {"title": title, "version": version}
if summary:
info["summary"] = summary
if description:
info["description"] = description
if terms_of_service:
info["termsOfService"] = terms_of_service
if contact:
info["contact"] = contact
if license_info... | info: Dict[str, Any] = {"title": title, "version": version}
if summary:
info["summary"] = summary
if description:
info["description"] = description
if terms_of_service:
info["termsOfService"] = terms_of_service
if contact:
info["contact"] = contact
if license_info... | 200 | 465 | 941 | 1,406 | """
Copy of https://github.com/tiangolo/fastapi/blob/master/fastapi/openapi/utils.py with changes from https://github.com/tiangolo/fastapi/pull/10903
"""
from typing import (
Any,
Dict,
List,
Optional,
Sequence,
Set,
Union,
)
from fastapi import routing
from fastapi._compat import (
Ge... | """
Copy of https://github.com/tiangolo/fastapi/blob/master/fastapi/openapi/utils.py with changes from https://github.com/tiangolo/fastapi/pull/10903
"""
from typing import (
Any,
Dict,
List,
Optional,
Sequence,
Set,
Union,
)
from fastapi import routing
from fastapi._compat import (
Ge... | |
46,502 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/reports/buildapp.py | 53,54 | 1,103 | app_factory | 55,80 | 54,80 | """
Provides factory methods to assemble the Galaxy web application
"""
import atexit
import logging
import os
from inspect import isclass
from paste import httpexceptions
import galaxy.model
import galaxy.model.mapping
import galaxy.webapps.base.webapp
from galaxy.util import asbool
from galaxy.util.properties impo... | """
Provides factory methods to assemble the Galaxy web application
"""
import atexit
import logging
import os
from inspect import isclass
from paste import httpexceptions
import galaxy.model
import galaxy.model.mapping
import galaxy.webapps.base.webapp
from galaxy.util import asbool
from galaxy.util.properties impo... | # Create the Galaxy application unless passed in
load_app_kwds = load_app_kwds or {}
kwargs = load_app_properties(kwds=kwargs, **load_app_kwds)
if "app" in kwargs:
app = kwargs.pop("app")
else:
from galaxy.webapps.reports.app import UniverseApplication
app = UniverseApplicat... | """Return a wsgi application serving the root object"""
# Create the Galaxy application unless passed in
load_app_kwds = load_app_kwds or {}
kwargs = load_app_properties(kwds=kwargs, **load_app_kwds)
if "app" in kwargs:
app = kwargs.pop("app")
else:
from galaxy.webapps.reports.ap... | 94 | 863 | 396 | 1,259 | """
Provides factory methods to assemble the Galaxy web application
"""
import atexit
import logging
import os
from inspect import isclass
from paste import httpexceptions
import galaxy.model
import galaxy.model.mapping
import galaxy.webapps.base.webapp
from galaxy.util import asbool
from galaxy.util.properties impo... | """
Provides factory methods to assemble the Galaxy web application
"""
import atexit
import logging
import os
from inspect import isclass
from paste import httpexceptions
import galaxy.model
import galaxy.model.mapping
import galaxy.webapps.base.webapp
from galaxy.util import asbool
from galaxy.util.properties impo... | |
46,503 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/reports/config.py | 87,88 | 1,112 | get_database_engine_options | 92,112 | 88,112 | """Universe configuration builder."""
import logging
import os
import re
from galaxy.util import string_as_bool
log = logging.getLogger(__name__)
def resolve_path(path, root):
"""If 'path' is relative make absolute by prepending 'root'"""
if not (os.path.isabs(path)):
path = os.path.join(root, path... | """Universe configuration builder."""
import logging
import os
import re
from galaxy.util import string_as_bool
log = logging.getLogger(__name__)
def resolve_path(path, root):
"""If 'path' is relative make absolute by prepending 'root'"""
if not (os.path.isabs(path)):
path = os.path.join(root, path... | conversions = {
"convert_unicode": string_as_bool,
"pool_timeout": int,
"echo": string_as_bool,
"echo_pool": string_as_bool,
"pool_recycle": int,
"pool_size": int,
"max_overflow": int,
"pool_threadlocal": string_as_bool,
}
prefix = "database_en... | """
Allow options for the SQLAlchemy database engine to be passed by using
the prefix "database_engine_option".
"""
conversions = {
"convert_unicode": string_as_bool,
"pool_timeout": int,
"echo": string_as_bool,
"echo_pool": string_as_bool,
"pool_recycle": int... | 51 | 1,183 | 212 | 1,395 | """Universe configuration builder."""
import logging
import os
import re
from galaxy.util import string_as_bool
log = logging.getLogger(__name__)
def resolve_path(path, root):
"""If 'path' is relative make absolute by prepending 'root'"""
if not (os.path.isabs(path)):
path = os.path.join(root, path... | """Universe configuration builder."""
import logging
import os
import re
from galaxy.util import string_as_bool
log = logging.getLogger(__name__)
def resolve_path(path, root):
"""If 'path' is relative make absolute by prepending 'root'"""
if not (os.path.isabs(path)):
path = os.path.join(root, path... | |
46,504 | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy | /home/hieuvd/dung_repo/raw/stars_03/galaxyproject_galaxy/galaxy/lib/galaxy/webapps/reports/config.py | 69,70 | 23,87 | check | Configuration | 70,75 | 70,75 | class Configuration:
def __init__(self, **kwargs):
self.config_dict = kwargs
self.root = kwargs.get("root_dir", ".")
# Database related configuration
self.database = resolve_path(kwargs.get("database_file", "database/universe.sqlite"), self.root)
self.database_connection = kw... | class Configuration:
def __init__(self, **kwargs):
self.config_dict = kwargs
self.root = kwargs.get("root_dir", ".")
# Database related configuration
self.database = resolve_path(kwargs.get("database_file", "database/universe.sqlite"), self.root)
self.database_connection = kw... | # Check that required directories exist
for path in (self.root,):
if not os.path.isdir(path):
raise ConfigurationError(f"Directory does not exist: {path}")
| # Check that required directories exist
for path in (self.root,):
if not os.path.isdir(path):
raise ConfigurationError(f"Directory does not exist: {path}")
| 19 | 970 | 55 | 1,025 | """Universe configuration builder."""
import logging
import os
import re
from galaxy.util import string_as_bool
log = logging.getLogger(__name__)
def resolve_path(path, root):
"""If 'path' is relative make absolute by prepending 'root'"""
if not (os.path.isabs(path)):
path = os.path.join(root, path... | """Universe configuration builder."""
import logging
import os
import re
from galaxy.util import string_as_bool
log = logging.getLogger(__name__)
def resolve_path(path, root):
"""If 'path' is relative make absolute by prepending 'root'"""
if not (os.path.isabs(path)):
path = os.path.join(root, path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.