Search is not available for this dataset
text stringlengths 75 104k |
|---|
def load(cls, instruction):
"""
Loads a new GuacamoleInstruction from encoded instruction string.
:param instruction: Instruction string.
:return: GuacamoleInstruction()
"""
if not instruction.endswith(INST_TERM):
raise InvalidInstruction('Instruction termin... |
def decode_instruction(instruction):
"""
Decode whole instruction and return list of args.
Usually, returned arg[0] is the instruction opcode.
example:
>> args = decode_instruction('4.size,4.1024;')
>> args == ['size', '1024']
>> True
:param instruction:... |
def encode_arg(arg):
"""
Encode argument to be sent in a valid GuacamoleInstruction.
example:
>> arg = encode_arg('size')
>> arg == '4.size'
>> True
:param arg: arg string.
:return: str
"""
arg_utf8 = utf8(arg)
return ELEM_SEP.j... |
def encode(self):
"""
Prepare the instruction to be sent over the wire.
:return: str
"""
instruction_iter = itertools.chain([self.opcode], self.args)
elems = ARG_SEP.join(self.encode_arg(arg) for arg in instruction_iter)
return elems + INST_TERM |
def class_url(cls):
"""Returns a versioned URI string for this class"""
base = 'v{0}'.format(getattr(cls, 'RESOURCE_VERSION', '1'))
return "/{0}/{1}".format(base, class_to_api_name(cls.class_name())) |
def instance_url(self):
"""Get instance URL by ID"""
id_ = self.get(self.ID_ATTR)
base = self.class_url()
if id_:
return '/'.join([base, six.text_type(id_)])
else:
raise Exception(
'Could not determine which URL to request: %s instance '
... |
def class_url(cls):
"""
Returns a versioned URI string for this class,
and don't pluralize the class name.
"""
base = 'v{0}'.format(getattr(cls, 'RESOURCE_VERSION', '1'))
return "/{0}/{1}".format(base, class_to_api_name(
cls.class_name(), pluralize=False)) |
def download(self, path=None, **kwargs):
"""
Download the file to the specified directory or file path.
Downloads to a temporary directory if no path is specified.
Returns the absolute path to the file.
"""
download_url = self.download_url(**kwargs)
try:
... |
def parent_object(self):
""" Get the commit objects parent Import or Migration """
from . import types
parent_klass = types.get(self.parent_job_model.split('.')[1])
return parent_klass.retrieve(self.parent_job_id, client=self._client) |
def _ask_for_credentials():
"""
Asks the user for their email and password.
"""
_print_msg('Please enter your SolveBio credentials')
domain = raw_input('Domain (e.g. <domain>.solvebio.com): ')
# Check to see if this domain supports password authentication
try:
account = client.reques... |
def login(*args, **kwargs):
"""
Prompt user for login information (domain/email/password).
Domain, email and password are used to get the user's API key.
Always updates the stored credentials file.
"""
if args and args[0].api_key:
# Handle command-line arguments if provided.
sol... |
def interactive_login():
"""
Force an interactive login via the command line.
Sets the global API key and updates the client auth.
"""
solvebio.access_token = None
solvebio.api_key = None
client.set_token()
domain, email, password = _ask_for_credentials()
if not all([domain, email, ... |
def whoami(*args, **kwargs):
"""
Prints information about the current user.
Assumes the user is already logged-in.
"""
user = client.whoami()
if user:
print_user(user)
else:
print('You are not logged-in.') |
def print_user(user):
"""
Prints information about the current user.
"""
email = user['email']
domain = user['account']['domain']
role = user['role']
print('You are logged-in to the "{0}" domain '
'as {1} with role {2}.'
.format(domain, email, role)) |
def from_string(cls, string, exact=False):
"""
Handles UCSC-style range queries (chr1:100-200)
"""
try:
chromosome, pos = string.split(':')
except ValueError:
raise ValueError('Please use UCSC-style format: "chr2:1000-2000"')
if '-' in pos:
... |
def filter(self, *filters, **kwargs):
"""
Returns this Query instance with the query args combined with
existing set with AND.
kwargs are simply passed to a new Filter object and combined to any
other filters with AND.
By default, everything is combined using AND. If yo... |
def range(self, chromosome, start, stop, exact=False):
"""
Shortcut to do range filters on genomic datasets.
"""
return self._clone(
filters=[GenomicFilter(chromosome, start, stop, exact)]) |
def position(self, chromosome, position, exact=False):
"""
Shortcut to do a single position filter on genomic datasets.
"""
return self._clone(
filters=[GenomicFilter(chromosome, position, exact=exact)]) |
def facets(self, *args, **kwargs):
"""
Returns a dictionary with the requested facets.
The facets function supports string args, and keyword
args.
q.facets('field_1', 'field_2') will return facets for
field_1 and field_2.
q.facets(field_1={'limit': 0}, field_2={... |
def _process_filters(cls, filters):
"""Takes a list of filters and returns JSON
:Parameters:
- `filters`: List of Filters, (key, val) tuples, or dicts
Returns: List of JSON API filters
"""
data = []
# Filters should always be a list
for f in filters:
... |
def next(self):
"""
Allows the Query object to be an iterable.
This method will iterate through a cached result set
and fetch successive pages as required.
A `StopIteration` exception will be raised when there aren't
any more results available or when the requested resu... |
def execute(self, offset=0, **query):
"""
Executes a query. Additional query parameters can be passed
as keyword arguments.
Returns: The request parameters and the raw query response.
"""
_params = self._build_query(**query)
self._page_offset = offset
_p... |
def migrate(self, target, follow=True, **kwargs):
"""
Migrate the data from the Query to a target dataset.
Valid optional kwargs include:
* target_fields
* include_errors
* validation_params
* metadata
* commit_mode
"""
from solvebio imp... |
def login(**kwargs):
"""
Sets up the auth credentials using the provided key/token,
or checks the credentials file (if no token provided).
Lookup order:
1. access_token
2. api_key
3. local credentials
No errors are raised if no key is found.
"""
from .cli.auth impor... |
def main(argv=sys.argv[1:]):
""" Main entry point for SolveBio CLI """
parser = SolveArgumentParser()
args = parser.parse_solvebio_args(argv)
if args.api_host:
solvebio.api_host = args.api_host
if args.api_key:
solvebio.api_key = args.api_key
if not solvebio.api_key:
#... |
def _add_subcommands(self):
"""
The _add_subcommands method must be separate from the __init__
method, as infinite recursion will occur otherwise, due to the fact
that the __init__ method itself will be called when instantiating
a subparser, as we do below
... |
def parse_solvebio_args(self, args=None, namespace=None):
"""
Try to parse the args first, and then add the subparsers. We want
to do this so that we can check to see if there are any unknown
args. We can assume that if, by this point, there are no unknown
args, w... |
def download_vault_folder(remote_path, local_path, dry_run=False, force=False):
"""Recursively downloads a folder in a vault to a local directory.
Only downloads files, not datasets."""
local_path = os.path.normpath(os.path.expanduser(local_path))
if not os.access(local_path, os.W_OK):
raise Ex... |
def construct_from(cls, values, **kwargs):
"""Used to create a new object from an HTTP response"""
instance = cls(values.get(cls.ID_ATTR), **kwargs)
instance.refresh_from(values)
return instance |
def logout(self):
"""Revoke the token and remove the cookie."""
if self._oauth_client_secret:
try:
oauth_token = flask.request.cookies[self.TOKEN_COOKIE_NAME]
# Revoke the token
requests.post(
urljoin(self._api_host, self.OA... |
def launch_ipython_shell(args): # pylint: disable=unused-argument
"""Open the SolveBio shell (IPython wrapper)"""
try:
import IPython # noqa
except ImportError:
_print("The SolveBio Python shell requires IPython.\n"
"To install, type: 'pip install ipython'")
return F... |
def launch_ipython_5_shell(args):
"""Open the SolveBio shell (IPython wrapper) with IPython 5+"""
import IPython # noqa
from traitlets.config import Config
c = Config()
path = os.path.dirname(os.path.abspath(__file__))
try:
# see if we're already inside IPython
get_ipython # ... |
def launch_ipython_legacy_shell(args): # pylint: disable=unused-argument
"""Open the SolveBio shell (IPython wrapper) for older IPython versions"""
try:
from IPython.config.loader import Config
except ImportError:
_print("The SolveBio Python shell requires IPython.\n"
"To ins... |
def get(self, url, params, **kwargs):
"""Issues an HTTP GET across the wire via the Python requests
library. See *request()* for information on keyword args."""
kwargs['params'] = params
return self.request('GET', url, **kwargs) |
def delete(self, url, data, **kwargs):
"""Issues an HTTP DELETE across the wire via the Python requests
library. See *request* for information on keyword args."""
kwargs['data'] = data
return self.request('DELETE', url, **kwargs) |
def request(self, method, url, **kwargs):
"""
Issues an HTTP Request across the wire via the Python requests
library.
Parameters
----------
method : str
an HTTP method: GET, PUT, POST, DELETE, ...
url : str
the place to connect to. If the ... |
def child_object(self):
""" Get Task child object class """
from . import types
child_klass = types.get(self.task_type.split('.')[1])
return child_klass.retrieve(self.task_id, client=self._client) |
def cancel(self):
""" Cancel a task """
_status = self.status
self.status = "canceled"
try:
self.save()
except:
# Reset status to what it was before
# status update failure
self.status = _status
raise |
def _parse_info_snpeff(self, info):
"""
Specialized INFO field parser for SnpEff ANN fields.
Requires self._snpeff_ann_fields to be set.
"""
ann = info.pop('ANN', []) or []
# Overwrite the existing ANN with something parsed
# Split on '|', merge with the ANN keys ... |
def next(self):
"""
Expands multiple alleles into one record each
using an internal buffer (_next).
"""
def _alt(alt):
"""Parses the VCF row ALT object."""
# If alt is '.' in VCF, PyVCF returns None, convert back to '.'
if not alt:
... |
def row_to_dict(self, row, allele, alternate_alleles):
"""Return a parsed dictionary for JSON."""
def _variant_sbid(**kwargs):
"""Generates a SolveBio variant ID (SBID)."""
return '{build}-{chromosome}-{start}-{stop}-{allele}'\
.format(**kwargs).upper()
... |
def get_credentials():
"""
Returns the user's stored API key if a valid credentials file is found.
Raises CredentialsError if no valid credentials file is found.
"""
try:
netrc_path = netrc.path()
auths = netrc(netrc_path).authenticators(
urlparse(solvebio.api_host).netlo... |
def save(self, path):
"""Dump the class data in the format of a .netrc file."""
rep = ""
for host in self.hosts.keys():
attrs = self.hosts[host]
rep = rep + "machine " + host + "\n\tlogin " \
+ six.text_type(attrs[0]) + "\n"
if attrs[1]:
... |
def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or
isinstance(string, string_types)) and \
_isconvertible(int, string) |
def _align_column(strings, alignment, minwidth=0, has_invisible=True):
"""
[string] -> [padded_string]
>>> list(map(str,_align_column( \
["12.345", "-1234.5", "1.23", "1234.5", \
"1e+234", "1.0e234"], "decimal")))
[' 12.345 ', '-1234.5 ', ' 1.23 ', \
' 1234.5 ', ' ... |
def _format(val, valtype, floatfmt, missingval=""):
"""
Format a value accoding to its type.
Unicode is supported:
>>> hrow = ['\u0431\u0443\u043a\u0432\u0430', \
'\u0446\u0438\u0444\u0440\u0430'] ; \
tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \
good... |
def _normalize_tabular_data(tabular_data, headers, sort=True):
"""
Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* 2D NumPy arrays
* dict of iterables (usually used with headers="keys"... |
def _build_row(cells, padding, begin, sep, end):
"Return a string which represents a row of data cells."
pad = " " * padding
padded_cells = [pad + cell + pad for cell in cells]
# SolveBio: we're only displaying Key-Value tuples (dimension of 2).
# enforce that we don't wrap lines by setting a max... |
def _build_line(colwidths, padding, begin, fill, sep, end):
"Return a string which represents a horizontal line."
cells = [fill * (w + 2 * padding) for w in colwidths]
return _build_row(cells, 0, begin, sep, end) |
def _mediawiki_cell_attrs(row, colaligns):
"Prefix every cell in a row with an HTML alignment attribute."
alignment = {"left": '',
"right": 'align="right"| ',
"center": 'align="center"| ',
"decimal": 'align="right"| '}
row2 = [alignment[a] + c for c, a in z... |
def _line_segment_with_colons(linefmt, align, colwidth):
"""Return a segment of a horizontal line with optional colons which
indicate column's alignment (as in `pipe` output format)."""
fill = linefmt.hline
w = colwidth
if align in ["right", "decimal"]:
return (fill[0] * (w - 1)) + ":"
e... |
def _format_table(fmt, headers, rows, colwidths, colaligns):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if headers else fmt.without_header_hide
pad = fmt.padding
headerrow = fmt.headerrow if fmt.headerrow else fmt.datarow
if fmt.lineabove an... |
def import_file(self, path, **kwargs):
"""
This is a shortcut to creating a DatasetImport. Can't use "import()"
because of Python.
"""
from . import Manifest
from . import DatasetImport
if 'id' not in self or not self['id']:
raise Exception(
... |
def migrate(self, target, follow=True, **kwargs):
"""
Migrate the data from this dataset to a target dataset.
Valid optional kwargs include:
* source_params
* target_fields
* include_errors
* commit_mode
"""
if 'id' not in self or not self['id']... |
def validate_full_path(cls, full_path, **kwargs):
"""Helper method to parse a full or partial path and
return a full path as well as a dict containing path parts.
Uses the following rules when processing the path:
* If no domain, uses the current user's account domain
*... |
def create_dataset(args):
"""
Attempt to create a new dataset given the following params:
* template_id
* template_file
* capacity
* create_vault
* [argument] dataset name or full path
NOTE: genome_build has been deprecated and is no longer used.
"""
# For ... |
def upload(args):
"""
Given a folder or file, upload all the folders and files contained
within it, skipping ones that already exist on the remote.
"""
base_remote_path, path_dict = Object.validate_full_path(
args.full_path, vault=args.vault, path=args.path)
# Assert the vault exists an... |
def import_file(args):
"""
Given a dataset and a local path, upload and import the file(s).
Command arguments (args):
* create_dataset
* template_id
* full_path
* vault (optional, overrides the vault in full_path)
* path (optional, overrides the path in full_path)
... |
def validate_full_path(cls, full_path, **kwargs):
"""Helper method to return a full path from a full or partial path.
If no domain, assumes user's account domain
If the vault is "~", assumes personal vault.
Valid vault paths include:
domain:vault
domain... |
def validate_api_host_url(url):
"""
Validate SolveBio API host url.
Valid urls must not be empty and
must contain either HTTP or HTTPS scheme.
"""
if not url:
raise SolveError('No SolveBio API host is set')
parsed = urlparse(url)
if parsed.scheme not in ['http', 'https']:
... |
def add(self, *args):
"""
Add one or more files or URLs to the manifest.
If files contains a glob, it is expanded.
All files are uploaded to SolveBio. The Upload
object is used to fill the manifest.
"""
def _is_url(path):
p = urlparse(path)
... |
def annotate(self, records, **kwargs):
"""Annotate a set of records with stored fields.
Args:
records: A list or iterator (can be a Query object)
chunk_size: The number of records to annotate at once (max 500).
Returns:
A generator that yields one annotated ... |
def evaluate(self, data=None, data_type='string', is_list=False):
"""Evaluates the expression with the provided context and format."""
payload = {
'data': data,
'expression': self.expr,
'data_type': data_type,
'is_list': is_list
}
res = sel... |
def format_output(data, headers, format_name, **kwargs):
"""Format output using *format_name*.
This is a wrapper around the :class:`TabularOutputFormatter` class.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The column headers.
:param str format_name: The... |
def format_name(self, format_name):
"""Set the default format name.
:param str format_name: The display format name.
:raises ValueError: if the format is not recognized.
"""
if format_name in self.supported_formats:
self._format_name = format_name
else:
... |
def register_new_formatter(cls, format_name, handler, preprocessors=(),
kwargs=None):
"""Register a new output formatter.
:param str format_name: The name of the format.
:param callable handler: The function that formats the data.
:param tuple preprocessor... |
def format_output(self, data, headers, format_name=None,
preprocessors=(), column_types=None, **kwargs):
"""Format the headers and data using a specific formatter.
*format_name* must be a supported formatter (see
:attr:`supported_formats`).
:param iterable data: A... |
def _get_column_types(self, data):
"""Get a list of the data types for each column in *data*."""
columns = list(zip_longest(*data))
return [self._get_column_type(column) for column in columns] |
def _get_column_type(self, column):
"""Get the most generic data type for iterable *column*."""
type_values = [TYPES[self._get_type(v)] for v in column]
inverse_types = {v: k for k, v in TYPES.items()}
return inverse_types[max(type_values)] |
def _get_type(self, value):
"""Get the data type for *value*."""
if value is None:
return type(None)
elif type(value) in int_types:
return int
elif type(value) in float_types:
return float
elif isinstance(value, binary_type):
return... |
def adapter(data, headers, table_format=None, preserve_whitespace=False,
**kwargs):
"""Wrap tabulate inside a function for TabularOutputFormatter."""
keys = ('floatfmt', 'numalign', 'stralign', 'showindex', 'disable_numparse')
tkwargs = {'tablefmt': table_format}
tkwargs.update(filter_dict_b... |
def get_user_config_dir(app_name, app_author, roaming=True, force_xdg=True):
"""Returns the config folder for the application. The default behavior
is to return whatever is most appropriate for the operating system.
For an example application called ``"My App"`` by ``"Acme"``,
something like the follo... |
def get_system_config_dirs(app_name, app_author, force_xdg=True):
r"""Returns a list of system-wide config folders for the application.
For an example application called ``"My App"`` by ``"Acme"``,
something like the following folders could be returned:
macOS (non-XDG):
``['/Library/Application ... |
def read_default_config(self):
"""Read the default config file.
:raises DefaultConfigValidationError: There was a validation error with
the *default* file.
"""
if self.validate:
self.default_config = ConfigObj(configspec=self.def... |
def read(self):
"""Read the default, additional, system, and user config files.
:raises DefaultConfigValidationError: There was a validation error with
the *default* file.
"""
if self.default_file:
self.read_default_config()
... |
def user_config_file(self):
"""Get the absolute path to the user config file."""
return os.path.join(
get_user_config_dir(self.app_name, self.app_author),
self.filename) |
def system_config_files(self):
"""Get a list of absolute paths to the system config files."""
return [os.path.join(f, self.filename) for f in get_system_config_dirs(
self.app_name, self.app_author)] |
def additional_files(self):
"""Get a list of absolute paths to the additional config files."""
return [os.path.join(f, self.filename) for f in self.additional_dirs] |
def write_default_config(self, overwrite=False):
"""Write the default config to the user's config file.
:param bool overwrite: Write over an existing config if it exists.
"""
destination = self.user_config_file()
if not overwrite and os.path.exists(destination):
retu... |
def write(self, outfile=None, section=None):
"""Write the current config to a file (defaults to user config).
:param str outfile: The path to the file to write to.
:param None/str section: The config section to write, or :data:`None`
to write the entire config.
... |
def read_config_file(self, f):
"""Read a config file *f*.
:param str f: The path to a file to read.
"""
configspec = self.default_file if self.validate else None
try:
config = ConfigObj(infile=f, configspec=configspec,
interpolation=Fal... |
def read_config_files(self, files):
"""Read a list of config files.
:param iterable files: An iterable (e.g. list) of files to read.
"""
errors = {}
for _file in files:
config, valid = self.read_config_file(_file)
self.update(config)
if valid ... |
def bytes_to_string(b):
"""Convert bytes *b* to a string.
Hexlify bytes that can't be decoded.
"""
if isinstance(b, binary_type):
try:
return b.decode('utf8')
except UnicodeDecodeError:
return '0x' + binascii.hexlify(b).decode('ascii')
return b |
def truncate_string(value, max_width=None):
"""Truncate string values."""
if isinstance(value, text_type) and max_width is not None and len(value) > max_width:
return value[:max_width]
return value |
def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys} |
def unique_items(seq):
"""Return the unique items from iterable *seq* (in order)."""
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))] |
def replace(s, replace):
"""Replace multiple values in a string"""
for r in replace:
s = s.replace(*r)
return s |
def adapter(data, headers, **kwargs):
"""Wrap the formatting inside a function for TabularOutputFormatter."""
for row in chain((headers,), data):
yield "\t".join((replace(r, (('\n', r'\n'), ('\t', r'\t'))) for r in row)) |
def call_and_exit(self, cmd, shell=True):
"""Run the *cmd* and exit with the proper exit code."""
sys.exit(subprocess.call(cmd, shell=shell)) |
def call_in_sequence(self, cmds, shell=True):
"""Run multiple commmands in a row, exiting if one fails."""
for cmd in cmds:
if subprocess.call(cmd, shell=shell) == 1:
sys.exit(1) |
def apply_options(self, cmd, options=()):
"""Apply command-line options."""
for option in (self.default_cmd_options + options):
cmd = self.apply_option(cmd, option,
active=getattr(self, option, False))
return cmd |
def apply_option(self, cmd, option, active=True):
"""Apply a command-line option."""
return re.sub(r'{{{}\:(?P<option>[^}}]*)}}'.format(option),
'\g<option>' if active else '', cmd) |
def initialize_options(self):
"""Set the default options."""
self.branch = 'master'
self.fix = False
super(lint, self).initialize_options() |
def run(self):
"""Run the linter."""
cmd = 'pep8radius {branch} {{fix: --in-place}}{{verbose: -vv}}'
cmd = cmd.format(branch=self.branch)
self.call_and_exit(self.apply_options(cmd, ('fix', ))) |
def run(self):
"""Generate and view the documentation."""
cmds = (self.clean_docs_cmd, self.html_docs_cmd, self.view_docs_cmd)
self.call_in_sequence(cmds) |
def truncate_string(data, headers, max_field_width=None, **_):
"""Truncate very long strings. Only needed for tabular
representation, because trying to tabulate very long data
is problematic in terms of performance, and does not make any
sense visually.
:param iterable data: An :term:`iterable` (e.... |
def convert_to_string(data, headers, **_):
"""Convert all *data* and *headers* to strings.
Binary data that cannot be decoded is converted to a hexadecimal
representation via :func:`binascii.hexlify`.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The colum... |
def override_missing_value(data, headers, missing_value='', **_):
"""Override missing values in the *data* with *missing_value*.
A missing value is any value that is :data:`None`.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The column headers.
:param mis... |
def override_tab_value(data, headers, new_value=' ', **_):
"""Override tab values in the *data* with *new_value*.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The column headers.
:param new_value: The new value to use for tab.
:return: The processed dat... |
def bytes_to_string(data, headers, **_):
"""Convert all *data* and *headers* bytes to strings.
Binary data that cannot be decoded is converted to a hexadecimal
representation via :func:`binascii.hexlify`.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers: The c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.