repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
daler/gffutils | gffutils/interface.py | FeatureDB.bed12 | def bed12(self, feature, block_featuretype=['exon'],
thick_featuretype=['CDS'], thin_featuretype=None,
name_field='ID', color=None):
"""
Converts `feature` into a BED12 format.
GFF and GTF files do not necessarily define genes consistently, so this
method pro... | python | def bed12(self, feature, block_featuretype=['exon'],
thick_featuretype=['CDS'], thin_featuretype=None,
name_field='ID', color=None):
"""
Converts `feature` into a BED12 format.
GFF and GTF files do not necessarily define genes consistently, so this
method pro... | Converts `feature` into a BED12 format.
GFF and GTF files do not necessarily define genes consistently, so this
method provides flexiblity in specifying what to call a "transcript".
Parameters
----------
feature : str or Feature instance
In most cases, this feature ... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L1154-L1299 |
daler/gffutils | gffutils/iterators.py | DataIterator | def DataIterator(data, checklines=10, transform=None,
force_dialect_check=False, from_string=False, **kwargs):
"""
Iterate over features, no matter how they are provided.
Parameters
----------
data : str, iterable of Feature objs, FeatureDB
`data` can be a string (filename,... | python | def DataIterator(data, checklines=10, transform=None,
force_dialect_check=False, from_string=False, **kwargs):
"""
Iterate over features, no matter how they are provided.
Parameters
----------
data : str, iterable of Feature objs, FeatureDB
`data` can be a string (filename,... | Iterate over features, no matter how they are provided.
Parameters
----------
data : str, iterable of Feature objs, FeatureDB
`data` can be a string (filename, URL, or contents of a file, if
from_string=True), any arbitrary iterable of features, or a FeatureDB
(in which case its all... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/iterators.py#L229-L279 |
tisimst/pyDOE | pyDOE/doe_box_behnken.py | bbdesign | def bbdesign(n, center=None):
"""
Create a Box-Behnken design
Parameters
----------
n : int
The number of factors in the design
Optional
--------
center : int
The number of center points to include (default = 1).
Returns
-------
... | python | def bbdesign(n, center=None):
"""
Create a Box-Behnken design
Parameters
----------
n : int
The number of factors in the design
Optional
--------
center : int
The number of center points to include (default = 1).
Returns
-------
... | Create a Box-Behnken design
Parameters
----------
n : int
The number of factors in the design
Optional
--------
center : int
The number of center points to include (default = 1).
Returns
-------
mat : 2d-array
The design matrix
... | https://github.com/tisimst/pyDOE/blob/436143702507a5c8ff87b361223eee8171d6a1d7/pyDOE/doe_box_behnken.py#L22-L91 |
daler/gffutils | gffutils/inspect.py | inspect | def inspect(data, look_for=['featuretype', 'chrom', 'attribute_keys',
'feature_count'], limit=None, verbose=True):
"""
Inspect a GFF or GTF data source.
This function is useful for figuring out the different featuretypes found
in a file (for potential removal before creating... | python | def inspect(data, look_for=['featuretype', 'chrom', 'attribute_keys',
'feature_count'], limit=None, verbose=True):
"""
Inspect a GFF or GTF data source.
This function is useful for figuring out the different featuretypes found
in a file (for potential removal before creating... | Inspect a GFF or GTF data source.
This function is useful for figuring out the different featuretypes found
in a file (for potential removal before creating a FeatureDB).
Returns a dictionary with a key for each item in `look_for` and
a corresponding value that is a dictionary of how many of each uniq... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/inspect.py#L7-L105 |
tisimst/pyDOE | pyDOE/doe_factorial.py | fullfact | def fullfact(levels):
"""
Create a general full-factorial design
Parameters
----------
levels : array-like
An array of integers that indicate the number of levels of each input
design factor.
Returns
-------
mat : 2d-array
The design matrix ... | python | def fullfact(levels):
"""
Create a general full-factorial design
Parameters
----------
levels : array-like
An array of integers that indicate the number of levels of each input
design factor.
Returns
-------
mat : 2d-array
The design matrix ... | Create a general full-factorial design
Parameters
----------
levels : array-like
An array of integers that indicate the number of levels of each input
design factor.
Returns
-------
mat : 2d-array
The design matrix with coded levels 0 to k-1 for a k-l... | https://github.com/tisimst/pyDOE/blob/436143702507a5c8ff87b361223eee8171d6a1d7/pyDOE/doe_factorial.py#L21-L82 |
tisimst/pyDOE | pyDOE/doe_factorial.py | fracfact | def fracfact(gen):
"""
Create a 2-level fractional-factorial design with a generator string.
Parameters
----------
gen : str
A string, consisting of lowercase, uppercase letters or operators "-"
and "+", indicating the factors of the experiment
Returns
--... | python | def fracfact(gen):
"""
Create a 2-level fractional-factorial design with a generator string.
Parameters
----------
gen : str
A string, consisting of lowercase, uppercase letters or operators "-"
and "+", indicating the factors of the experiment
Returns
--... | Create a 2-level fractional-factorial design with a generator string.
Parameters
----------
gen : str
A string, consisting of lowercase, uppercase letters or operators "-"
and "+", indicating the factors of the experiment
Returns
-------
H : 2d-array
... | https://github.com/tisimst/pyDOE/blob/436143702507a5c8ff87b361223eee8171d6a1d7/pyDOE/doe_factorial.py#L119-L231 |
tisimst/pyDOE | pyDOE/doe_lhs.py | lhs | def lhs(n, samples=None, criterion=None, iterations=None):
"""
Generate a latin-hypercube design
Parameters
----------
n : int
The number of factors to generate samples for
Optional
--------
samples : int
The number of samples to generate for each fa... | python | def lhs(n, samples=None, criterion=None, iterations=None):
"""
Generate a latin-hypercube design
Parameters
----------
n : int
The number of factors to generate samples for
Optional
--------
samples : int
The number of samples to generate for each fa... | Generate a latin-hypercube design
Parameters
----------
n : int
The number of factors to generate samples for
Optional
--------
samples : int
The number of samples to generate for each factor (Default: n)
criterion : str
Allowable values are "cen... | https://github.com/tisimst/pyDOE/blob/436143702507a5c8ff87b361223eee8171d6a1d7/pyDOE/doe_lhs.py#L21-L119 |
tisimst/pyDOE | pyDOE/doe_lhs.py | _pdist | def _pdist(x):
"""
Calculate the pair-wise point distances of a matrix
Parameters
----------
x : 2d-array
An m-by-n array of scalars, where there are m points in n dimensions.
Returns
-------
d : array
A 1-by-b array of scalars, where b = m*(m - 1)/2... | python | def _pdist(x):
"""
Calculate the pair-wise point distances of a matrix
Parameters
----------
x : 2d-array
An m-by-n array of scalars, where there are m points in n dimensions.
Returns
-------
d : array
A 1-by-b array of scalars, where b = m*(m - 1)/2... | Calculate the pair-wise point distances of a matrix
Parameters
----------
x : 2d-array
An m-by-n array of scalars, where there are m points in n dimensions.
Returns
-------
d : array
A 1-by-b array of scalars, where b = m*(m - 1)/2. This array contains
... | https://github.com/tisimst/pyDOE/blob/436143702507a5c8ff87b361223eee8171d6a1d7/pyDOE/doe_lhs.py#L200-L243 |
daler/gffutils | gffutils/scripts/gffutils-flybase-convert.py | clean_gff | def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None,
featuretypes_to_ignore=None):
"""
Cleans a GFF file by removing features on unwanted chromosomes and of
unwanted featuretypes. Optionally adds "chr" to chrom names.
"""
logger.info("Cleaning GFF")
chroms_to_ignore =... | python | def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None,
featuretypes_to_ignore=None):
"""
Cleans a GFF file by removing features on unwanted chromosomes and of
unwanted featuretypes. Optionally adds "chr" to chrom names.
"""
logger.info("Cleaning GFF")
chroms_to_ignore =... | Cleans a GFF file by removing features on unwanted chromosomes and of
unwanted featuretypes. Optionally adds "chr" to chrom names. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/scripts/gffutils-flybase-convert.py#L25-L45 |
tisimst/pyDOE | pyDOE/doe_composite.py | ccdesign | def ccdesign(n, center=(4, 4), alpha='orthogonal', face='circumscribed'):
"""
Central composite design
Parameters
----------
n : int
The number of factors in the design.
Optional
--------
center : int array
A 1-by-2 array of integers, the number of c... | python | def ccdesign(n, center=(4, 4), alpha='orthogonal', face='circumscribed'):
"""
Central composite design
Parameters
----------
n : int
The number of factors in the design.
Optional
--------
center : int array
A 1-by-2 array of integers, the number of c... | Central composite design
Parameters
----------
n : int
The number of factors in the design.
Optional
--------
center : int array
A 1-by-2 array of integers, the number of center points in each block
of the design. (Default: (4, 4)).
alpha : str
... | https://github.com/tisimst/pyDOE/blob/436143702507a5c8ff87b361223eee8171d6a1d7/pyDOE/doe_composite.py#L24-L160 |
daler/gffutils | gffutils/feature.py | feature_from_line | def feature_from_line(line, dialect=None, strict=True, keep_order=False):
"""
Given a line from a GFF file, return a Feature object
Parameters
----------
line : string
strict : bool
If True (default), assume `line` is a single, tab-delimited string that
has at least 9 fields.
... | python | def feature_from_line(line, dialect=None, strict=True, keep_order=False):
"""
Given a line from a GFF file, return a Feature object
Parameters
----------
line : string
strict : bool
If True (default), assume `line` is a single, tab-delimited string that
has at least 9 fields.
... | Given a line from a GFF file, return a Feature object
Parameters
----------
line : string
strict : bool
If True (default), assume `line` is a single, tab-delimited string that
has at least 9 fields.
If False, then the input can have a more flexible format, useful for
c... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/feature.py#L356-L411 |
daler/gffutils | gffutils/feature.py | Feature.calc_bin | def calc_bin(self, _bin=None):
"""
Calculate the smallest UCSC genomic bin that will contain this feature.
"""
if _bin is None:
try:
_bin = bins.bins(self.start, self.end, one=True)
except TypeError:
_bin = None
return _bin | python | def calc_bin(self, _bin=None):
"""
Calculate the smallest UCSC genomic bin that will contain this feature.
"""
if _bin is None:
try:
_bin = bins.bins(self.start, self.end, one=True)
except TypeError:
_bin = None
return _bin | Calculate the smallest UCSC genomic bin that will contain this feature. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/feature.py#L182-L191 |
daler/gffutils | gffutils/feature.py | Feature.astuple | def astuple(self, encoding=None):
"""
Return a tuple suitable for import into a database.
Attributes field and extra field jsonified into strings. The order of
fields is such that they can be supplied as arguments for the query
defined in :attr:`gffutils.constants._INSERT`.
... | python | def astuple(self, encoding=None):
"""
Return a tuple suitable for import into a database.
Attributes field and extra field jsonified into strings. The order of
fields is such that they can be supplied as arguments for the query
defined in :attr:`gffutils.constants._INSERT`.
... | Return a tuple suitable for import into a database.
Attributes field and extra field jsonified into strings. The order of
fields is such that they can be supplied as arguments for the query
defined in :attr:`gffutils.constants._INSERT`.
If `encoding` is not None, then convert string fi... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/feature.py#L293-L322 |
daler/gffutils | gffutils/feature.py | Feature.sequence | def sequence(self, fasta, use_strand=True):
"""
Retrieves the sequence of this feature as a string.
Uses the pyfaidx package.
Parameters
----------
fasta : str
If str, then it's a FASTA-format filename; otherwise assume it's
a pyfaidx.Fasta obje... | python | def sequence(self, fasta, use_strand=True):
"""
Retrieves the sequence of this feature as a string.
Uses the pyfaidx package.
Parameters
----------
fasta : str
If str, then it's a FASTA-format filename; otherwise assume it's
a pyfaidx.Fasta obje... | Retrieves the sequence of this feature as a string.
Uses the pyfaidx package.
Parameters
----------
fasta : str
If str, then it's a FASTA-format filename; otherwise assume it's
a pyfaidx.Fasta object.
use_strand : bool
If True (default), th... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/feature.py#L324-L353 |
daler/gffutils | gffutils/convert.py | to_bed12 | def to_bed12(f, db, child_type='exon', name_field='ID'):
"""
Given a top-level feature (e.g., transcript), construct a BED12 entry
Parameters
----------
f : Feature object or string
This is the top-level feature represented by one BED12 line. For
a canonical GFF or GTF, this will ge... | python | def to_bed12(f, db, child_type='exon', name_field='ID'):
"""
Given a top-level feature (e.g., transcript), construct a BED12 entry
Parameters
----------
f : Feature object or string
This is the top-level feature represented by one BED12 line. For
a canonical GFF or GTF, this will ge... | Given a top-level feature (e.g., transcript), construct a BED12 entry
Parameters
----------
f : Feature object or string
This is the top-level feature represented by one BED12 line. For
a canonical GFF or GTF, this will generally be a transcript.
db : a FeatureDB object
This is ... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/convert.py#L7-L43 |
daler/gffutils | gffutils/helpers.py | infer_dialect | def infer_dialect(attributes):
"""
Infer the dialect based on the attributes.
Parameters
----------
attributes : str or iterable
A single attributes string from a GTF or GFF line, or an iterable of
such strings.
Returns
-------
Dictionary representing the inferred diale... | python | def infer_dialect(attributes):
"""
Infer the dialect based on the attributes.
Parameters
----------
attributes : str or iterable
A single attributes string from a GTF or GFF line, or an iterable of
such strings.
Returns
-------
Dictionary representing the inferred diale... | Infer the dialect based on the attributes.
Parameters
----------
attributes : str or iterable
A single attributes string from a GTF or GFF line, or an iterable of
such strings.
Returns
-------
Dictionary representing the inferred dialect | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L25-L42 |
daler/gffutils | gffutils/helpers.py | _choose_dialect | def _choose_dialect(dialects):
"""
Given a list of dialects, choose the one to use as the "canonical" version.
If `dialects` is an empty list, then use the default GFF3 dialect
Parameters
----------
dialects : iterable
iterable of dialect dictionaries
Returns
-------
dict
... | python | def _choose_dialect(dialects):
"""
Given a list of dialects, choose the one to use as the "canonical" version.
If `dialects` is an empty list, then use the default GFF3 dialect
Parameters
----------
dialects : iterable
iterable of dialect dictionaries
Returns
-------
dict
... | Given a list of dialects, choose the one to use as the "canonical" version.
If `dialects` is an empty list, then use the default GFF3 dialect
Parameters
----------
dialects : iterable
iterable of dialect dictionaries
Returns
-------
dict | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L45-L75 |
daler/gffutils | gffutils/helpers.py | make_query | def make_query(args, other=None, limit=None, strand=None, featuretype=None,
extra=None, order_by=None, reverse=False,
completely_within=False):
"""
Multi-purpose, bare-bones ORM function.
This function composes queries given some commonly-used kwargs that can be
passed to ... | python | def make_query(args, other=None, limit=None, strand=None, featuretype=None,
extra=None, order_by=None, reverse=False,
completely_within=False):
"""
Multi-purpose, bare-bones ORM function.
This function composes queries given some commonly-used kwargs that can be
passed to ... | Multi-purpose, bare-bones ORM function.
This function composes queries given some commonly-used kwargs that can be
passed to FeatureDB methods (like .parents(), .children(), .all_features(),
.features_of_type()). It handles, in one place, things like restricting to
featuretype, limiting to a genomic r... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L78-L239 |
daler/gffutils | gffutils/helpers.py | _bin_from_dict | def _bin_from_dict(d):
"""
Given a dictionary yielded by the parser, return the genomic "UCSC" bin
"""
try:
start = int(d['start'])
end = int(d['end'])
return bins.bins(start, end, one=True)
# e.g., if "."
except ValueError:
return None | python | def _bin_from_dict(d):
"""
Given a dictionary yielded by the parser, return the genomic "UCSC" bin
"""
try:
start = int(d['start'])
end = int(d['end'])
return bins.bins(start, end, one=True)
# e.g., if "."
except ValueError:
return None | Given a dictionary yielded by the parser, return the genomic "UCSC" bin | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L242-L253 |
daler/gffutils | gffutils/helpers.py | _jsonify | def _jsonify(x):
"""Use most compact form of JSON"""
if isinstance(x, dict_class):
return json.dumps(x._d, separators=(',', ':'))
return json.dumps(x, separators=(',', ':')) | python | def _jsonify(x):
"""Use most compact form of JSON"""
if isinstance(x, dict_class):
return json.dumps(x._d, separators=(',', ':'))
return json.dumps(x, separators=(',', ':')) | Use most compact form of JSON | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L256-L260 |
daler/gffutils | gffutils/helpers.py | _unjsonify | def _unjsonify(x, isattributes=False):
"""Convert JSON string to an ordered defaultdict."""
if isattributes:
obj = json.loads(x)
return dict_class(obj)
return json.loads(x) | python | def _unjsonify(x, isattributes=False):
"""Convert JSON string to an ordered defaultdict."""
if isattributes:
obj = json.loads(x)
return dict_class(obj)
return json.loads(x) | Convert JSON string to an ordered defaultdict. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L263-L268 |
daler/gffutils | gffutils/helpers.py | _feature_to_fields | def _feature_to_fields(f, jsonify=True):
"""
Convert feature to tuple, for faster sqlite3 import
"""
x = []
for k in constants._keys:
v = getattr(f, k)
if jsonify and (k in ('attributes', 'extra')):
x.append(_jsonify(v))
else:
x.append(v)
return tu... | python | def _feature_to_fields(f, jsonify=True):
"""
Convert feature to tuple, for faster sqlite3 import
"""
x = []
for k in constants._keys:
v = getattr(f, k)
if jsonify and (k in ('attributes', 'extra')):
x.append(_jsonify(v))
else:
x.append(v)
return tu... | Convert feature to tuple, for faster sqlite3 import | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L271-L282 |
daler/gffutils | gffutils/helpers.py | _dict_to_fields | def _dict_to_fields(d, jsonify=True):
"""
Convert dict to tuple, for faster sqlite3 import
"""
x = []
for k in constants._keys:
v = d[k]
if jsonify and (k in ('attributes', 'extra')):
x.append(_jsonify(v))
else:
x.append(v)
return tuple(x) | python | def _dict_to_fields(d, jsonify=True):
"""
Convert dict to tuple, for faster sqlite3 import
"""
x = []
for k in constants._keys:
v = d[k]
if jsonify and (k in ('attributes', 'extra')):
x.append(_jsonify(v))
else:
x.append(v)
return tuple(x) | Convert dict to tuple, for faster sqlite3 import | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L285-L296 |
daler/gffutils | gffutils/helpers.py | merge_attributes | def merge_attributes(attr1, attr2):
"""
Merges two attribute dictionaries into a single dictionary.
Parameters
----------
`attr1`, `attr2` : dict
Returns
-------
dict
"""
new_d = copy.deepcopy(attr1)
new_d.update(attr2)
#all of attr2 key : values just overwrote attr1,... | python | def merge_attributes(attr1, attr2):
"""
Merges two attribute dictionaries into a single dictionary.
Parameters
----------
`attr1`, `attr2` : dict
Returns
-------
dict
"""
new_d = copy.deepcopy(attr1)
new_d.update(attr2)
#all of attr2 key : values just overwrote attr1,... | Merges two attribute dictionaries into a single dictionary.
Parameters
----------
`attr1`, `attr2` : dict
Returns
-------
dict | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L307-L333 |
daler/gffutils | gffutils/helpers.py | dialect_compare | def dialect_compare(dialect1, dialect2):
"""
Compares two dialects.
"""
orig = set(dialect1.items())
new = set(dialect2.items())
return dict(
added=dict(list(new.difference(orig))),
removed=dict(list(orig.difference(new)))
) | python | def dialect_compare(dialect1, dialect2):
"""
Compares two dialects.
"""
orig = set(dialect1.items())
new = set(dialect2.items())
return dict(
added=dict(list(new.difference(orig))),
removed=dict(list(orig.difference(new)))
) | Compares two dialects. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L336-L345 |
daler/gffutils | gffutils/helpers.py | sanitize_gff_db | def sanitize_gff_db(db, gid_field="gid"):
"""
Sanitize given GFF db. Returns a sanitized GFF db.
Sanitizing means:
- Ensuring that start < stop for all features
- Standardizing gene units by adding a 'gid' attribute
that makes the file grep-able
TODO: Do something with negative coordina... | python | def sanitize_gff_db(db, gid_field="gid"):
"""
Sanitize given GFF db. Returns a sanitized GFF db.
Sanitizing means:
- Ensuring that start < stop for all features
- Standardizing gene units by adding a 'gid' attribute
that makes the file grep-able
TODO: Do something with negative coordina... | Sanitize given GFF db. Returns a sanitized GFF db.
Sanitizing means:
- Ensuring that start < stop for all features
- Standardizing gene units by adding a 'gid' attribute
that makes the file grep-able
TODO: Do something with negative coordinates? | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L348-L376 |
daler/gffutils | gffutils/helpers.py | sanitize_gff_file | def sanitize_gff_file(gff_fname,
in_memory=True,
in_place=False):
"""
Sanitize a GFF file.
"""
db = None
if is_gff_db(gff_fname):
# It's a database filename, so load it
db = gffutils.FeatureDB(gff_fname)
else:
# Need to create a... | python | def sanitize_gff_file(gff_fname,
in_memory=True,
in_place=False):
"""
Sanitize a GFF file.
"""
db = None
if is_gff_db(gff_fname):
# It's a database filename, so load it
db = gffutils.FeatureDB(gff_fname)
else:
# Need to create a... | Sanitize a GFF file. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L379-L404 |
daler/gffutils | gffutils/helpers.py | is_gff_db | def is_gff_db(db_fname):
"""
Return True if the given filename is a GFF database.
For now, rely on .db extension.
"""
if not os.path.isfile(db_fname):
return False
if db_fname.endswith(".db"):
return True
return False | python | def is_gff_db(db_fname):
"""
Return True if the given filename is a GFF database.
For now, rely on .db extension.
"""
if not os.path.isfile(db_fname):
return False
if db_fname.endswith(".db"):
return True
return False | Return True if the given filename is a GFF database.
For now, rely on .db extension. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L415-L425 |
daler/gffutils | gffutils/helpers.py | get_gff_db | def get_gff_db(gff_fname,
ext=".db"):
"""
Get db for GFF file. If the database has a .db file,
load that. Otherwise, create a named temporary file,
serialize the db to that, and return the loaded database.
"""
if not os.path.isfile(gff_fname):
# Not sure how we should deal... | python | def get_gff_db(gff_fname,
ext=".db"):
"""
Get db for GFF file. If the database has a .db file,
load that. Otherwise, create a named temporary file,
serialize the db to that, and return the loaded database.
"""
if not os.path.isfile(gff_fname):
# Not sure how we should deal... | Get db for GFF file. If the database has a .db file,
load that. Otherwise, create a named temporary file,
serialize the db to that, and return the loaded database. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/helpers.py#L475-L506 |
daler/gffutils | gffutils/bins.py | bins | def bins(start, stop, fmt='gff', one=True):
"""
Uses the definition of a "genomic bin" described in Fig 7 of
http://genome.cshlp.org/content/12/6/996.abstract.
Parameters
----------
one : boolean
If `one=True` (default), then only return the smallest bin that
completely contains... | python | def bins(start, stop, fmt='gff', one=True):
"""
Uses the definition of a "genomic bin" described in Fig 7 of
http://genome.cshlp.org/content/12/6/996.abstract.
Parameters
----------
one : boolean
If `one=True` (default), then only return the smallest bin that
completely contains... | Uses the definition of a "genomic bin" described in Fig 7 of
http://genome.cshlp.org/content/12/6/996.abstract.
Parameters
----------
one : boolean
If `one=True` (default), then only return the smallest bin that
completely contains these coordinates (useful for assigning a single
... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/bins.py#L58-L128 |
daler/gffutils | gffutils/bins.py | print_bin_sizes | def print_bin_sizes():
"""
Useful for debugging: how large is each bin, and what are the bin IDs?
"""
for i, offset in enumerate(OFFSETS):
binstart = offset
try:
binstop = OFFSETS[i + 1]
except IndexError:
binstop = binstart
bin_size = 2 ** (FIRST... | python | def print_bin_sizes():
"""
Useful for debugging: how large is each bin, and what are the bin IDs?
"""
for i, offset in enumerate(OFFSETS):
binstart = offset
try:
binstop = OFFSETS[i + 1]
except IndexError:
binstop = binstart
bin_size = 2 ** (FIRST... | Useful for debugging: how large is each bin, and what are the bin IDs? | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/bins.py#L131-L155 |
daler/gffutils | gffutils/parser.py | _reconstruct | def _reconstruct(keyvals, dialect, keep_order=False,
sort_attribute_values=False):
"""
Reconstructs the original attributes string according to the dialect.
Parameters
==========
keyvals : dict
Attributes from a GFF/GTF feature
dialect : dict
Dialect containing... | python | def _reconstruct(keyvals, dialect, keep_order=False,
sort_attribute_values=False):
"""
Reconstructs the original attributes string according to the dialect.
Parameters
==========
keyvals : dict
Attributes from a GFF/GTF feature
dialect : dict
Dialect containing... | Reconstructs the original attributes string according to the dialect.
Parameters
==========
keyvals : dict
Attributes from a GFF/GTF feature
dialect : dict
Dialect containing info on how to reconstruct a string version of the
attributes
keep_order : bool
If True, t... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/parser.py#L76-L169 |
daler/gffutils | gffutils/parser.py | _split_keyvals | def _split_keyvals(keyval_str, dialect=None):
"""
Given the string attributes field of a GFF-like line, split it into an
attributes dictionary and a "dialect" dictionary which contains information
needed to reconstruct the original string.
Lots of logic here to handle all the corner cases.
If ... | python | def _split_keyvals(keyval_str, dialect=None):
"""
Given the string attributes field of a GFF-like line, split it into an
attributes dictionary and a "dialect" dictionary which contains information
needed to reconstruct the original string.
Lots of logic here to handle all the corner cases.
If ... | Given the string attributes field of a GFF-like line, split it into an
attributes dictionary and a "dialect" dictionary which contains information
needed to reconstruct the original string.
Lots of logic here to handle all the corner cases.
If `dialect` is None, then do all the logic to infer a dialec... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/parser.py#L175-L360 |
daler/gffutils | gffutils/create.py | create_db | def create_db(data, dbfn, id_spec=None, force=False, verbose=False,
checklines=10, merge_strategy='error', transform=None,
gtf_transcript_key='transcript_id', gtf_gene_key='gene_id',
gtf_subfeature='exon', force_gff=False,
force_dialect_check=False, from_string=Fa... | python | def create_db(data, dbfn, id_spec=None, force=False, verbose=False,
checklines=10, merge_strategy='error', transform=None,
gtf_transcript_key='transcript_id', gtf_gene_key='gene_id',
gtf_subfeature='exon', force_gff=False,
force_dialect_check=False, from_string=Fa... | Create a database from a GFF or GTF file.
For more details on when and how to use the kwargs below, see the examples
in the online documentation (:ref:`examples`).
Parameters
----------
data : string or iterable
If a string (and `from_string` is False), then `data` is the path to
... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L1025-L1312 |
daler/gffutils | gffutils/create.py | _DBCreator._id_handler | def _id_handler(self, f):
"""
Given a Feature from self.iterator, figure out what the ID should be.
This uses `self.id_spec` identify the ID.
"""
# If id_spec is a string, convert to iterable for later
if isinstance(self.id_spec, six.string_types):
id_key = ... | python | def _id_handler(self, f):
"""
Given a Feature from self.iterator, figure out what the ID should be.
This uses `self.id_spec` identify the ID.
"""
# If id_spec is a string, convert to iterable for later
if isinstance(self.id_spec, six.string_types):
id_key = ... | Given a Feature from self.iterator, figure out what the ID should be.
This uses `self.id_spec` identify the ID. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L153-L205 |
daler/gffutils | gffutils/create.py | _DBCreator._do_merge | def _do_merge(self, f, merge_strategy, add_duplicate=False):
"""
Different merge strategies upon name conflicts.
"error":
Raise error
"warning"
Log a warning
"merge":
Combine old and new attributes -- but only if everything else
... | python | def _do_merge(self, f, merge_strategy, add_duplicate=False):
"""
Different merge strategies upon name conflicts.
"error":
Raise error
"warning"
Log a warning
"merge":
Combine old and new attributes -- but only if everything else
... | Different merge strategies upon name conflicts.
"error":
Raise error
"warning"
Log a warning
"merge":
Combine old and new attributes -- but only if everything else
matches; otherwise error. This can be slow, but is thorough.
"create_un... | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L213-L354 |
daler/gffutils | gffutils/create.py | _DBCreator._add_duplicate | def _add_duplicate(self, idspecid, newid):
"""
Adds a duplicate ID (as identified by id_spec) and its new ID to the
duplicates table so that they can be later searched for merging.
Parameters
----------
newid : str
The primary key used in the features table
... | python | def _add_duplicate(self, idspecid, newid):
"""
Adds a duplicate ID (as identified by id_spec) and its new ID to the
duplicates table so that they can be later searched for merging.
Parameters
----------
newid : str
The primary key used in the features table
... | Adds a duplicate ID (as identified by id_spec) and its new ID to the
duplicates table so that they can be later searched for merging.
Parameters
----------
newid : str
The primary key used in the features table
idspecid : str
The ID identified by id_spec | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L356-L388 |
daler/gffutils | gffutils/create.py | _DBCreator._candidate_merges | def _candidate_merges(self, f):
"""
Identifies those features that originally had the same ID as `f`
(according to the id_spec), but were modified because of duplicate
IDs.
"""
candidates = [self._get_feature(f.id)]
c = self.conn.cursor()
results = c.exec... | python | def _candidate_merges(self, f):
"""
Identifies those features that originally had the same ID as `f`
(according to the id_spec), but were modified because of duplicate
IDs.
"""
candidates = [self._get_feature(f.id)]
c = self.conn.cursor()
results = c.exec... | Identifies those features that originally had the same ID as `f`
(according to the id_spec), but were modified because of duplicate
IDs. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L390-L407 |
daler/gffutils | gffutils/create.py | _DBCreator._init_tables | def _init_tables(self):
"""
Table creation
"""
c = self.conn.cursor()
v = sqlite3.sqlite_version_info
self.set_pragmas(self.pragmas)
c.executescript(constants.SCHEMA)
self.conn.commit() | python | def _init_tables(self):
"""
Table creation
"""
c = self.conn.cursor()
v = sqlite3.sqlite_version_info
self.set_pragmas(self.pragmas)
c.executescript(constants.SCHEMA)
self.conn.commit() | Table creation | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L440-L448 |
daler/gffutils | gffutils/create.py | _DBCreator._finalize | def _finalize(self):
"""
Various last-minute stuff to perform after file has been parsed and
imported.
In general, if you'll be adding stuff to the meta table, do it here.
"""
c = self.conn.cursor()
directives = self.directives + self.iterator.directives
... | python | def _finalize(self):
"""
Various last-minute stuff to perform after file has been parsed and
imported.
In general, if you'll be adding stuff to the meta table, do it here.
"""
c = self.conn.cursor()
directives = self.directives + self.iterator.directives
... | Various last-minute stuff to perform after file has been parsed and
imported.
In general, if you'll be adding stuff to the meta table, do it here. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L450-L505 |
daler/gffutils | gffutils/create.py | _DBCreator.create | def create(self):
"""
Calls various methods sequentially in order to fully build the
database.
"""
# Calls each of these methods in order. _populate_from_lines and
# _update_relations must be implemented in subclasses.
self._init_tables()
self._populate_f... | python | def create(self):
"""
Calls various methods sequentially in order to fully build the
database.
"""
# Calls each of these methods in order. _populate_from_lines and
# _update_relations must be implemented in subclasses.
self._init_tables()
self._populate_f... | Calls various methods sequentially in order to fully build the
database. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L507-L517 |
daler/gffutils | gffutils/create.py | _DBCreator.execute | def execute(self, query):
"""
Execute a query directly on the database.
"""
c = self.conn.cursor()
result = c.execute(query)
for i in result:
yield i | python | def execute(self, query):
"""
Execute a query directly on the database.
"""
c = self.conn.cursor()
result = c.execute(query)
for i in result:
yield i | Execute a query directly on the database. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L523-L530 |
daler/gffutils | gffutils/create.py | _DBCreator._replace | def _replace(self, feature, cursor):
"""
Insert a feature into the database.
"""
try:
cursor.execute(
constants._UPDATE,
list(feature.astuple()) + [feature.id])
except sqlite3.ProgrammingError:
cursor.execute(
... | python | def _replace(self, feature, cursor):
"""
Insert a feature into the database.
"""
try:
cursor.execute(
constants._UPDATE,
list(feature.astuple()) + [feature.id])
except sqlite3.ProgrammingError:
cursor.execute(
... | Insert a feature into the database. | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/create.py#L542-L553 |
edx/bok-choy | bok_choy/javascript.py | wait_for_js | def wait_for_js(function):
"""
Method decorator that waits for JavaScript dependencies before executing `function`.
If the function is not a method, the decorator has no effect.
Args:
function (callable): Method to decorate.
Returns:
Decorated method
"""
@functools.wraps(f... | python | def wait_for_js(function):
"""
Method decorator that waits for JavaScript dependencies before executing `function`.
If the function is not a method, the decorator has no effect.
Args:
function (callable): Method to decorate.
Returns:
Decorated method
"""
@functools.wraps(f... | Method decorator that waits for JavaScript dependencies before executing `function`.
If the function is not a method, the decorator has no effect.
Args:
function (callable): Method to decorate.
Returns:
Decorated method | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/javascript.py#L45-L77 |
edx/bok-choy | bok_choy/javascript.py | _decorator | def _decorator(store_name, store_values):
"""
Return a class decorator that:
1) Defines a new class method, `wait_for_js`
2) Defines a new class list variable, `store_name` and adds
`store_values` to the list.
"""
def decorator(clz): # pylint: disable=missing-docstring
# Add a... | python | def _decorator(store_name, store_values):
"""
Return a class decorator that:
1) Defines a new class method, `wait_for_js`
2) Defines a new class list variable, `store_name` and adds
`store_values` to the list.
"""
def decorator(clz): # pylint: disable=missing-docstring
# Add a... | Return a class decorator that:
1) Defines a new class method, `wait_for_js`
2) Defines a new class list variable, `store_name` and adds
`store_values` to the list. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/javascript.py#L80-L101 |
edx/bok-choy | bok_choy/javascript.py | _wait_for_js | def _wait_for_js(self):
"""
Class method added by the decorators to allow
decorated classes to manually re-check JavaScript
dependencies.
Expect that `self` is a class that:
1) Has been decorated with either `js_defined` or `requirejs`
2) Has a `browser` property
If either (1) or (2) i... | python | def _wait_for_js(self):
"""
Class method added by the decorators to allow
decorated classes to manually re-check JavaScript
dependencies.
Expect that `self` is a class that:
1) Has been decorated with either `js_defined` or `requirejs`
2) Has a `browser` property
If either (1) or (2) i... | Class method added by the decorators to allow
decorated classes to manually re-check JavaScript
dependencies.
Expect that `self` is a class that:
1) Has been decorated with either `js_defined` or `requirejs`
2) Has a `browser` property
If either (1) or (2) is not satisfied, then do nothing. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/javascript.py#L104-L135 |
edx/bok-choy | bok_choy/javascript.py | _are_js_vars_defined | def _are_js_vars_defined(browser, js_vars):
"""
Return a boolean indicating whether all the JavaScript
variables `js_vars` are defined on the current page.
`browser` is a Selenium webdriver instance.
"""
# This script will evaluate to True iff all of
# the required vars are defined.
scr... | python | def _are_js_vars_defined(browser, js_vars):
"""
Return a boolean indicating whether all the JavaScript
variables `js_vars` are defined on the current page.
`browser` is a Selenium webdriver instance.
"""
# This script will evaluate to True iff all of
# the required vars are defined.
scr... | Return a boolean indicating whether all the JavaScript
variables `js_vars` are defined on the current page.
`browser` is a Selenium webdriver instance. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/javascript.py#L138-L158 |
edx/bok-choy | bok_choy/javascript.py | _are_requirejs_deps_loaded | def _are_requirejs_deps_loaded(browser, deps):
"""
Return a boolean indicating whether all the RequireJS
dependencies `deps` have loaded on the current page.
`browser` is a WebDriver instance.
"""
# This is a little complicated
#
# We're going to use `execute_async_script` to give cont... | python | def _are_requirejs_deps_loaded(browser, deps):
"""
Return a boolean indicating whether all the RequireJS
dependencies `deps` have loaded on the current page.
`browser` is a WebDriver instance.
"""
# This is a little complicated
#
# We're going to use `execute_async_script` to give cont... | Return a boolean indicating whether all the RequireJS
dependencies `deps` have loaded on the current page.
`browser` is a WebDriver instance. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/javascript.py#L161-L212 |
edx/bok-choy | bok_choy/page_object.py | no_selenium_errors | def no_selenium_errors(func):
"""
Decorator to create an `EmptyPromise` check function that is satisfied
only when `func` executes without a Selenium error.
This protects against many common test failures due to timing issues.
For example, accessing an element after it has been modified by JavaScri... | python | def no_selenium_errors(func):
"""
Decorator to create an `EmptyPromise` check function that is satisfied
only when `func` executes without a Selenium error.
This protects against many common test failures due to timing issues.
For example, accessing an element after it has been modified by JavaScri... | Decorator to create an `EmptyPromise` check function that is satisfied
only when `func` executes without a Selenium error.
This protects against many common test failures due to timing issues.
For example, accessing an element after it has been modified by JavaScript
ordinarily results in a `StaleEleme... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/page_object.py#L64-L90 |
edx/bok-choy | bok_choy/page_object.py | pre_verify | def pre_verify(method):
"""
Decorator that calls self._verify_page() before executing the decorated method
Args:
method (callable): The method to decorate.
Returns:
Decorated method
"""
@wraps(method)
def wrapper(self, *args, **kwargs): # pylint: disable=missing-docstring
... | python | def pre_verify(method):
"""
Decorator that calls self._verify_page() before executing the decorated method
Args:
method (callable): The method to decorate.
Returns:
Decorated method
"""
@wraps(method)
def wrapper(self, *args, **kwargs): # pylint: disable=missing-docstring
... | Decorator that calls self._verify_page() before executing the decorated method
Args:
method (callable): The method to decorate.
Returns:
Decorated method | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/page_object.py#L110-L124 |
edx/bok-choy | bok_choy/a11y/axs_ruleset.py | AxsAuditConfig.set_rules | def set_rules(self, rules):
"""
Sets the rules to be run or ignored for the audit.
Args:
rules: a dictionary of the format `{"ignore": [], "apply": []}`.
See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits
Passing `{"apply": []... | python | def set_rules(self, rules):
"""
Sets the rules to be run or ignored for the audit.
Args:
rules: a dictionary of the format `{"ignore": [], "apply": []}`.
See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits
Passing `{"apply": []... | Sets the rules to be run or ignored for the audit.
Args:
rules: a dictionary of the format `{"ignore": [], "apply": []}`.
See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits
Passing `{"apply": []}` or `{}` means to check for all available rule... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axs_ruleset.py#L36-L69 |
edx/bok-choy | bok_choy/a11y/axs_ruleset.py | AxsAuditConfig.set_scope | def set_scope(self, include=None, exclude=None):
"""
Sets `scope`, the "start point" for the audit.
Args:
include: A list of css selectors specifying the elements that
contain the portion of the page that should be audited.
Defaults to auditing the e... | python | def set_scope(self, include=None, exclude=None):
"""
Sets `scope`, the "start point" for the audit.
Args:
include: A list of css selectors specifying the elements that
contain the portion of the page that should be audited.
Defaults to auditing the e... | Sets `scope`, the "start point" for the audit.
Args:
include: A list of css selectors specifying the elements that
contain the portion of the page that should be audited.
Defaults to auditing the entire document.
exclude: This arg is not implemented in t... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axs_ruleset.py#L71-L103 |
edx/bok-choy | bok_choy/a11y/axs_ruleset.py | AxsAudit._check_rules | def _check_rules(browser, rules_js, config):
"""
Check the page for violations of the configured rules. By default,
all rules in the ruleset will be checked.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an A... | python | def _check_rules(browser, rules_js, config):
"""
Check the page for violations of the configured rules. By default,
all rules in the ruleset will be checked.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an A... | Check the page for violations of the configured rules. By default,
all rules in the ruleset will be checked.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an AxsAuditConfig instance.
Returns:
A namedtupl... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axs_ruleset.py#L134-L193 |
edx/bok-choy | bok_choy/a11y/axs_ruleset.py | AxsAudit.get_errors | def get_errors(audit_results):
"""
Args:
audit_results: results of `AxsAudit.do_audit()`.
Returns: a list of errors.
"""
errors = []
if audit_results:
if audit_results.errors:
errors.extend(audit_results.errors)
return err... | python | def get_errors(audit_results):
"""
Args:
audit_results: results of `AxsAudit.do_audit()`.
Returns: a list of errors.
"""
errors = []
if audit_results:
if audit_results.errors:
errors.extend(audit_results.errors)
return err... | Args:
audit_results: results of `AxsAudit.do_audit()`.
Returns: a list of errors. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axs_ruleset.py#L196-L208 |
edx/bok-choy | bok_choy/a11y/axs_ruleset.py | AxsAudit.report_errors | def report_errors(audit, url):
"""
Args:
audit: results of `AxsAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
"""
errors = AxsAudit.get_errors(audit)
if errors:
msg = u"URL '{}' has {} errors:\... | python | def report_errors(audit, url):
"""
Args:
audit: results of `AxsAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
"""
errors = AxsAudit.get_errors(audit)
if errors:
msg = u"URL '{}' has {} errors:\... | Args:
audit: results of `AxsAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError` | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axs_ruleset.py#L211-L227 |
edx/bok-choy | bok_choy/promise.py | Promise.fulfill | def fulfill(self):
"""
Evaluate the promise and return the result.
Returns:
The result of the `Promise` (second return value from the `check_func`)
Raises:
BrokenPromise: the `Promise` was not satisfied within the time or attempt limits.
"""
is_... | python | def fulfill(self):
"""
Evaluate the promise and return the result.
Returns:
The result of the `Promise` (second return value from the `check_func`)
Raises:
BrokenPromise: the `Promise` was not satisfied within the time or attempt limits.
"""
is_... | Evaluate the promise and return the result.
Returns:
The result of the `Promise` (second return value from the `check_func`)
Raises:
BrokenPromise: the `Promise` was not satisfied within the time or attempt limits. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/promise.py#L91-L106 |
edx/bok-choy | bok_choy/promise.py | Promise._check_fulfilled | def _check_fulfilled(self):
"""
Return tuple `(is_fulfilled, result)` where
`is_fulfilled` is a boolean indicating whether the promise has been fulfilled
and `result` is the value to pass to the `with` block.
"""
is_fulfilled = False
result = None
start_ti... | python | def _check_fulfilled(self):
"""
Return tuple `(is_fulfilled, result)` where
`is_fulfilled` is a boolean indicating whether the promise has been fulfilled
and `result` is the value to pass to the `with` block.
"""
is_fulfilled = False
result = None
start_ti... | Return tuple `(is_fulfilled, result)` where
`is_fulfilled` is a boolean indicating whether the promise has been fulfilled
and `result` is the value to pass to the `with` block. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/promise.py#L111-L136 |
edx/bok-choy | docs/code/round_3/pages.py | GitHubSearchPage.search | def search(self):
"""
Click on the Search button and wait for the
results page to be displayed
"""
self.q(css='button.btn').click()
GitHubSearchResultsPage(self.browser).wait_for_page() | python | def search(self):
"""
Click on the Search button and wait for the
results page to be displayed
"""
self.q(css='button.btn').click()
GitHubSearchResultsPage(self.browser).wait_for_page() | Click on the Search button and wait for the
results page to be displayed | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/docs/code/round_3/pages.py#L43-L49 |
edx/bok-choy | bok_choy/a11y/axe_core_ruleset.py | AxeCoreAuditConfig.set_rules | def set_rules(self, rules):
"""
Set rules to ignore XOR limit to when checking for accessibility
errors on the page.
Args:
rules: a dictionary one of the following formats.
If you want to run all of the rules except for some::
{"ignore":... | python | def set_rules(self, rules):
"""
Set rules to ignore XOR limit to when checking for accessibility
errors on the page.
Args:
rules: a dictionary one of the following formats.
If you want to run all of the rules except for some::
{"ignore":... | Set rules to ignore XOR limit to when checking for accessibility
errors on the page.
Args:
rules: a dictionary one of the following formats.
If you want to run all of the rules except for some::
{"ignore": []}
If you want to run only a ... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axe_core_ruleset.py#L37-L101 |
edx/bok-choy | bok_choy/a11y/axe_core_ruleset.py | AxeCoreAuditConfig.set_scope | def set_scope(self, include=None, exclude=None):
"""
Sets `scope` (refered to as `context` in ruleset documentation), which
defines the elements on a page to include or exclude in the audit. If
neither `include` nor `exclude` are passed, the entire document will
be included.
... | python | def set_scope(self, include=None, exclude=None):
"""
Sets `scope` (refered to as `context` in ruleset documentation), which
defines the elements on a page to include or exclude in the audit. If
neither `include` nor `exclude` are passed, the entire document will
be included.
... | Sets `scope` (refered to as `context` in ruleset documentation), which
defines the elements on a page to include or exclude in the audit. If
neither `include` nor `exclude` are passed, the entire document will
be included.
Args:
include (optional): a list of css selectors f... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axe_core_ruleset.py#L103-L154 |
edx/bok-choy | bok_choy/a11y/axe_core_ruleset.py | AxeCoreAuditConfig.customize_ruleset | def customize_ruleset(self, custom_ruleset_file=None):
"""
Updates the ruleset to include a set of custom rules. These rules will
be _added_ to the existing ruleset or replace the existing rule with
the same ID.
Args:
custom_ruleset_file (optional): The filepath to ... | python | def customize_ruleset(self, custom_ruleset_file=None):
"""
Updates the ruleset to include a set of custom rules. These rules will
be _added_ to the existing ruleset or replace the existing rule with
the same ID.
Args:
custom_ruleset_file (optional): The filepath to ... | Updates the ruleset to include a set of custom rules. These rules will
be _added_ to the existing ruleset or replace the existing rule with
the same ID.
Args:
custom_ruleset_file (optional): The filepath to the custom rules.
Defaults to `None`. If `custom_ruleset_fi... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axe_core_ruleset.py#L156-L207 |
edx/bok-choy | bok_choy/a11y/axe_core_ruleset.py | AxeCoreAudit._check_rules | def _check_rules(browser, rules_js, config):
"""
Run an accessibility audit on the page using the axe-core ruleset.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an AxsAuditConfig instance.
Returns:
... | python | def _check_rules(browser, rules_js, config):
"""
Run an accessibility audit on the page using the axe-core ruleset.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an AxsAuditConfig instance.
Returns:
... | Run an accessibility audit on the page using the axe-core ruleset.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an AxsAuditConfig instance.
Returns:
A list of violations.
Related documentation:
... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axe_core_ruleset.py#L227-L300 |
edx/bok-choy | bok_choy/a11y/axe_core_ruleset.py | AxeCoreAudit.get_errors | def get_errors(audit_results):
"""
Args:
audit_results: results of `AxeCoreAudit.do_audit()`.
Returns:
A dictionary with keys "errors" and "total".
"""
errors = {"errors": [], "total": 0}
if audit_results:
errors["errors"].extend(aud... | python | def get_errors(audit_results):
"""
Args:
audit_results: results of `AxeCoreAudit.do_audit()`.
Returns:
A dictionary with keys "errors" and "total".
"""
errors = {"errors": [], "total": 0}
if audit_results:
errors["errors"].extend(aud... | Args:
audit_results: results of `AxeCoreAudit.do_audit()`.
Returns:
A dictionary with keys "errors" and "total". | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axe_core_ruleset.py#L303-L319 |
edx/bok-choy | bok_choy/a11y/axe_core_ruleset.py | AxeCoreAudit.format_errors | def format_errors(errors):
"""
Args:
errors: results of `AxeCoreAudit.get_errors()`.
Returns: The errors as a formatted string.
"""
def _get_message(node):
"""
Get the message to display in the error output.
"""
messa... | python | def format_errors(errors):
"""
Args:
errors: results of `AxeCoreAudit.get_errors()`.
Returns: The errors as a formatted string.
"""
def _get_message(node):
"""
Get the message to display in the error output.
"""
messa... | Args:
errors: results of `AxeCoreAudit.get_errors()`.
Returns: The errors as a formatted string. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axe_core_ruleset.py#L322-L372 |
edx/bok-choy | bok_choy/a11y/axe_core_ruleset.py | AxeCoreAudit.report_errors | def report_errors(audit, url):
"""
Args:
audit: results of `AxeCoreAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
"""
errors = AxeCoreAudit.get_errors(audit)
if errors["total"] > 0:
msg = u"URL... | python | def report_errors(audit, url):
"""
Args:
audit: results of `AxeCoreAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError`
"""
errors = AxeCoreAudit.get_errors(audit)
if errors["total"] > 0:
msg = u"URL... | Args:
audit: results of `AxeCoreAudit.do_audit()`.
url: the url of the page being audited.
Raises: `AccessibilityError` | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/a11y/axe_core_ruleset.py#L375-L391 |
edx/bok-choy | bok_choy/browser.py | save_source | def save_source(driver, name):
"""
Save the rendered HTML of the browser.
The location of the source can be configured
by the environment variable `SAVED_SOURCE_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlled... | python | def save_source(driver, name):
"""
Save the rendered HTML of the browser.
The location of the source can be configured
by the environment variable `SAVED_SOURCE_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlled... | Save the rendered HTML of the browser.
The location of the source can be configured
by the environment variable `SAVED_SOURCE_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlled browser.
name (str): A name to use... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L79-L104 |
edx/bok-choy | bok_choy/browser.py | save_screenshot | def save_screenshot(driver, name):
"""
Save a screenshot of the browser.
The location of the screenshot can be configured
by the environment variable `SCREENSHOT_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlle... | python | def save_screenshot(driver, name):
"""
Save a screenshot of the browser.
The location of the screenshot can be configured
by the environment variable `SCREENSHOT_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlle... | Save a screenshot of the browser.
The location of the screenshot can be configured
by the environment variable `SCREENSHOT_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlled browser.
name (str): A name for the s... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L107-L138 |
edx/bok-choy | bok_choy/browser.py | save_driver_logs | def save_driver_logs(driver, prefix):
"""
Save the selenium driver logs.
The location of the driver log files can be configured
by the environment variable `SELENIUM_DRIVER_LOG_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Sel... | python | def save_driver_logs(driver, prefix):
"""
Save the selenium driver logs.
The location of the driver log files can be configured
by the environment variable `SELENIUM_DRIVER_LOG_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Sel... | Save the selenium driver logs.
The location of the driver log files can be configured
by the environment variable `SELENIUM_DRIVER_LOG_DIR`. If not set,
this defaults to the current working directory.
Args:
driver (selenium.webdriver): The Selenium-controlled browser.
prefix (str): A ... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L141-L189 |
edx/bok-choy | bok_choy/browser.py | browser | def browser(tags=None, proxy=None, other_caps=None):
"""
Interpret environment variables to configure Selenium.
Performs validation, logging, and sensible defaults.
There are three cases:
1. Local browsers: If the proper environment variables are not all set for the second case,
then we us... | python | def browser(tags=None, proxy=None, other_caps=None):
"""
Interpret environment variables to configure Selenium.
Performs validation, logging, and sensible defaults.
There are three cases:
1. Local browsers: If the proper environment variables are not all set for the second case,
then we us... | Interpret environment variables to configure Selenium.
Performs validation, logging, and sensible defaults.
There are three cases:
1. Local browsers: If the proper environment variables are not all set for the second case,
then we use a local browser.
* The environment variable `SELENIUM_... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L192-L296 |
edx/bok-choy | bok_choy/browser.py | _firefox_profile | def _firefox_profile():
"""Configure the Firefox profile, respecting FIREFOX_PROFILE_PATH if set"""
profile_dir = os.environ.get(FIREFOX_PROFILE_ENV_VAR)
if profile_dir:
LOGGER.info(u"Using firefox profile: %s", profile_dir)
try:
firefox_profile = webdriver.FirefoxProfile(profil... | python | def _firefox_profile():
"""Configure the Firefox profile, respecting FIREFOX_PROFILE_PATH if set"""
profile_dir = os.environ.get(FIREFOX_PROFILE_ENV_VAR)
if profile_dir:
LOGGER.info(u"Using firefox profile: %s", profile_dir)
try:
firefox_profile = webdriver.FirefoxProfile(profil... | Configure the Firefox profile, respecting FIREFOX_PROFILE_PATH if set | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L309-L367 |
edx/bok-choy | bok_choy/browser.py | _local_browser_class | def _local_browser_class(browser_name):
"""
Returns class, kwargs, and args needed to instantiate the local browser.
"""
# Log name of local browser
LOGGER.info(u"Using local browser: %s [Default is firefox]", browser_name)
# Get class of local browser based on name
browser_class = BROWSER... | python | def _local_browser_class(browser_name):
"""
Returns class, kwargs, and args needed to instantiate the local browser.
"""
# Log name of local browser
LOGGER.info(u"Using local browser: %s [Default is firefox]", browser_name)
# Get class of local browser based on name
browser_class = BROWSER... | Returns class, kwargs, and args needed to instantiate the local browser. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L370-L437 |
edx/bok-choy | bok_choy/browser.py | _remote_browser_class | def _remote_browser_class(env_vars, tags=None):
"""
Returns class, kwargs, and args needed to instantiate the remote browser.
"""
if tags is None:
tags = []
# Interpret the environment variables, raising an exception if they're
# invalid
envs = _required_envs(env_vars)
envs.upda... | python | def _remote_browser_class(env_vars, tags=None):
"""
Returns class, kwargs, and args needed to instantiate the remote browser.
"""
if tags is None:
tags = []
# Interpret the environment variables, raising an exception if they're
# invalid
envs = _required_envs(env_vars)
envs.upda... | Returns class, kwargs, and args needed to instantiate the remote browser. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L440-L474 |
edx/bok-choy | bok_choy/browser.py | _proxy_kwargs | def _proxy_kwargs(browser_name, proxy, browser_kwargs={}): # pylint: disable=dangerous-default-value
"""
Determines the kwargs needed to set up a proxy based on the
browser type.
Returns: a dictionary of arguments needed to pass when
instantiating the WebDriver instance.
"""
proxy_dic... | python | def _proxy_kwargs(browser_name, proxy, browser_kwargs={}): # pylint: disable=dangerous-default-value
"""
Determines the kwargs needed to set up a proxy based on the
browser type.
Returns: a dictionary of arguments needed to pass when
instantiating the WebDriver instance.
"""
proxy_dic... | Determines the kwargs needed to set up a proxy based on the
browser type.
Returns: a dictionary of arguments needed to pass when
instantiating the WebDriver instance. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L477-L503 |
edx/bok-choy | bok_choy/browser.py | _required_envs | def _required_envs(env_vars):
"""
Parse environment variables for required values,
raising a `BrowserConfig` error if they are not found.
Returns a `dict` of environment variables.
"""
envs = {
key: os.environ.get(key)
for key in env_vars
}
# Check for missing keys
... | python | def _required_envs(env_vars):
"""
Parse environment variables for required values,
raising a `BrowserConfig` error if they are not found.
Returns a `dict` of environment variables.
"""
envs = {
key: os.environ.get(key)
for key in env_vars
}
# Check for missing keys
... | Parse environment variables for required values,
raising a `BrowserConfig` error if they are not found.
Returns a `dict` of environment variables. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L519-L544 |
edx/bok-choy | bok_choy/browser.py | _optional_envs | def _optional_envs():
"""
Parse environment variables for optional values,
raising a `BrowserConfig` error if they are insufficiently specified.
Returns a `dict` of environment variables.
"""
envs = {
key: os.environ.get(key)
for key in OPTIONAL_ENV_VARS
if key in os.env... | python | def _optional_envs():
"""
Parse environment variables for optional values,
raising a `BrowserConfig` error if they are insufficiently specified.
Returns a `dict` of environment variables.
"""
envs = {
key: os.environ.get(key)
for key in OPTIONAL_ENV_VARS
if key in os.env... | Parse environment variables for optional values,
raising a `BrowserConfig` error if they are insufficiently specified.
Returns a `dict` of environment variables. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L547-L567 |
edx/bok-choy | bok_choy/browser.py | _capabilities_dict | def _capabilities_dict(envs, tags):
"""
Convert the dictionary of environment variables to
a dictionary of desired capabilities to send to the
Remote WebDriver.
`tags` is a list of string tags to apply to the SauceLabs job.
"""
capabilities = {
'browserName': envs['SELENIUM_BROWSER'... | python | def _capabilities_dict(envs, tags):
"""
Convert the dictionary of environment variables to
a dictionary of desired capabilities to send to the
Remote WebDriver.
`tags` is a list of string tags to apply to the SauceLabs job.
"""
capabilities = {
'browserName': envs['SELENIUM_BROWSER'... | Convert the dictionary of environment variables to
a dictionary of desired capabilities to send to the
Remote WebDriver.
`tags` is a list of string tags to apply to the SauceLabs job. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/browser.py#L570-L611 |
edx/bok-choy | bok_choy/query.py | Query.replace | def replace(self, **kwargs):
"""
Return a copy of this `Query`, but with attributes specified
as keyword arguments replaced by the keyword values.
Keyword Args:
Attributes/values to replace in the copy.
Returns:
A copy of the query that has its attribut... | python | def replace(self, **kwargs):
"""
Return a copy of this `Query`, but with attributes specified
as keyword arguments replaced by the keyword values.
Keyword Args:
Attributes/values to replace in the copy.
Returns:
A copy of the query that has its attribut... | Return a copy of this `Query`, but with attributes specified
as keyword arguments replaced by the keyword values.
Keyword Args:
Attributes/values to replace in the copy.
Returns:
A copy of the query that has its attributes updated with the specified values.
Ra... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L81-L103 |
edx/bok-choy | bok_choy/query.py | Query.transform | def transform(self, transform, desc=None):
"""
Create a copy of this query, transformed by `transform`.
Args:
transform (callable): Callable that takes an iterable of values and
returns an iterable of transformed values.
Keyword Args:
desc (str):... | python | def transform(self, transform, desc=None):
"""
Create a copy of this query, transformed by `transform`.
Args:
transform (callable): Callable that takes an iterable of values and
returns an iterable of transformed values.
Keyword Args:
desc (str):... | Create a copy of this query, transformed by `transform`.
Args:
transform (callable): Callable that takes an iterable of values and
returns an iterable of transformed values.
Keyword Args:
desc (str): A description of the transform, to use in log messages.
... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L105-L126 |
edx/bok-choy | bok_choy/query.py | Query.map | def map(self, map_fn, desc=None):
"""
Return a copy of this query, with the values mapped through `map_fn`.
Args:
map_fn (callable): A callable that takes a single argument and returns a new value.
Keyword Args:
desc (str): A description of the mapping transform... | python | def map(self, map_fn, desc=None):
"""
Return a copy of this query, with the values mapped through `map_fn`.
Args:
map_fn (callable): A callable that takes a single argument and returns a new value.
Keyword Args:
desc (str): A description of the mapping transform... | Return a copy of this query, with the values mapped through `map_fn`.
Args:
map_fn (callable): A callable that takes a single argument and returns a new value.
Keyword Args:
desc (str): A description of the mapping transform, for use in log message.
Defaults to ... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L128-L146 |
edx/bok-choy | bok_choy/query.py | Query.filter | def filter(self, filter_fn=None, desc=None, **kwargs):
"""
Return a copy of this query, with some values removed.
Example usages:
.. code:: python
# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)
# Returns a query tha... | python | def filter(self, filter_fn=None, desc=None, **kwargs):
"""
Return a copy of this query, with some values removed.
Example usages:
.. code:: python
# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)
# Returns a query tha... | Return a copy of this query, with some values removed.
Example usages:
.. code:: python
# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)
# Returns a query that matches elements with el.description == "foo"
q.filter(descri... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L148-L194 |
edx/bok-choy | bok_choy/query.py | Query._execute | def _execute(self):
"""
Run the query, generating data from the `seed_fn` and performing transforms on the results.
"""
data = self.seed_fn()
for transform in self.transforms:
data = transform(data)
return list(data) | python | def _execute(self):
"""
Run the query, generating data from the `seed_fn` and performing transforms on the results.
"""
data = self.seed_fn()
for transform in self.transforms:
data = transform(data)
return list(data) | Run the query, generating data from the `seed_fn` and performing transforms on the results. | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L196-L203 |
edx/bok-choy | bok_choy/query.py | Query.execute | def execute(self, try_limit=5, try_interval=0.5, timeout=30):
"""
Execute this query, retrying based on the supplied parameters.
Keyword Args:
try_limit (int): The number of times to retry the query.
try_interval (float): The number of seconds to wait between each try (f... | python | def execute(self, try_limit=5, try_interval=0.5, timeout=30):
"""
Execute this query, retrying based on the supplied parameters.
Keyword Args:
try_limit (int): The number of times to retry the query.
try_interval (float): The number of seconds to wait between each try (f... | Execute this query, retrying based on the supplied parameters.
Keyword Args:
try_limit (int): The number of times to retry the query.
try_interval (float): The number of seconds to wait between each try (float).
timeout (float): The maximum number of seconds to spend retryin... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L205-L226 |
edx/bok-choy | bok_choy/query.py | Query.first | def first(self):
"""
Return a Query that selects only the first element of this Query.
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.first.results
[0]... | python | def first(self):
"""
Return a Query that selects only the first element of this Query.
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.first.results
[0]... | Return a Query that selects only the first element of this Query.
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.first.results
[0]
Returns:
Query | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L258-L280 |
edx/bok-choy | bok_choy/query.py | Query.nth | def nth(self, index):
"""
Return a query that selects the element at `index` (starts from 0).
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.nth(2).results
... | python | def nth(self, index):
"""
Return a query that selects the element at `index` (starts from 0).
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.nth(2).results
... | Return a query that selects the element at `index` (starts from 0).
If no elements are available, returns a query with no results.
Example usage:
.. code:: python
>> q = Query(lambda: list(range(5)))
>> q.nth(2).results
[2]
Args:
index ... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L282-L309 |
edx/bok-choy | bok_choy/query.py | BrowserQuery.attrs | def attrs(self, attribute_name):
"""
Retrieve HTML attribute values from the elements matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div class="foo"> and <div class="bar">
>> q.attrs('class')
... | python | def attrs(self, attribute_name):
"""
Retrieve HTML attribute values from the elements matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div class="foo"> and <div class="bar">
>> q.attrs('class')
... | Retrieve HTML attribute values from the elements matched by the query.
Example usage:
.. code:: python
# Assume that the query matches html elements:
# <div class="foo"> and <div class="bar">
>> q.attrs('class')
['foo', 'bar']
Args:
... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L356-L376 |
edx/bok-choy | bok_choy/query.py | BrowserQuery.selected | def selected(self):
"""
Check whether all the matched elements are selected.
Returns:
bool
"""
query_results = self.map(lambda el: el.is_selected(), 'selected').results
if query_results:
return all(query_results)
return False | python | def selected(self):
"""
Check whether all the matched elements are selected.
Returns:
bool
"""
query_results = self.map(lambda el: el.is_selected(), 'selected').results
if query_results:
return all(query_results)
return False | Check whether all the matched elements are selected.
Returns:
bool | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L417-L427 |
edx/bok-choy | bok_choy/query.py | BrowserQuery.visible | def visible(self):
"""
Check whether all matched elements are visible.
Returns:
bool
"""
query_results = self.map(lambda el: el.is_displayed(), 'visible').results
if query_results:
return all(query_results)
return False | python | def visible(self):
"""
Check whether all matched elements are visible.
Returns:
bool
"""
query_results = self.map(lambda el: el.is_displayed(), 'visible').results
if query_results:
return all(query_results)
return False | Check whether all matched elements are visible.
Returns:
bool | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L430-L440 |
edx/bok-choy | bok_choy/query.py | BrowserQuery.is_focused | def is_focused(self):
"""
Checks that *at least one* matched element is focused. More
specifically, it checks whether the element is document.activeElement.
If no matching element is focused, this returns `False`.
Returns:
bool
"""
active_el = self.br... | python | def is_focused(self):
"""
Checks that *at least one* matched element is focused. More
specifically, it checks whether the element is document.activeElement.
If no matching element is focused, this returns `False`.
Returns:
bool
"""
active_el = self.br... | Checks that *at least one* matched element is focused. More
specifically, it checks whether the element is document.activeElement.
If no matching element is focused, this returns `False`.
Returns:
bool | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L452-L466 |
edx/bok-choy | bok_choy/query.py | BrowserQuery.fill | def fill(self, text):
"""
Set the text value of each matched element to `text`.
Example usage:
.. code:: python
# Set the text of the first element matched by the query to "Foo"
q.first.fill('Foo')
Args:
text (str): The text used to fill th... | python | def fill(self, text):
"""
Set the text value of each matched element to `text`.
Example usage:
.. code:: python
# Set the text of the first element matched by the query to "Foo"
q.first.fill('Foo')
Args:
text (str): The text used to fill th... | Set the text value of each matched element to `text`.
Example usage:
.. code:: python
# Set the text of the first element matched by the query to "Foo"
q.first.fill('Foo')
Args:
text (str): The text used to fill the element (usually a text field or text ar... | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L486-L507 |
metakermit/django-spa | spa/storage.py | PatchedManifestStaticFilesStorage.url_converter | def url_converter(self, *args, **kwargs):
"""
Return the custom URL converter for the given file name.
"""
upstream_converter = super(PatchedManifestStaticFilesStorage, self).url_converter(*args, **kwargs)
def converter(matchobj):
try:
upstream_conver... | python | def url_converter(self, *args, **kwargs):
"""
Return the custom URL converter for the given file name.
"""
upstream_converter = super(PatchedManifestStaticFilesStorage, self).url_converter(*args, **kwargs)
def converter(matchobj):
try:
upstream_conver... | Return the custom URL converter for the given file name. | https://github.com/metakermit/django-spa/blob/dbdfa6d06c1077fade729db25b3b137d44299db6/spa/storage.py#L12-L27 |
TriOptima/tri.table | lib/tri/table/__init__.py | prepare_headers | def prepare_headers(table, bound_columns):
"""
:type bound_columns: list of BoundColumn
"""
if table.request is None:
return
for column in bound_columns:
if column.sortable:
params = table.request.GET.copy()
param_path = _with_path_prefix(table, 'order')
... | python | def prepare_headers(table, bound_columns):
"""
:type bound_columns: list of BoundColumn
"""
if table.request is None:
return
for column in bound_columns:
if column.sortable:
params = table.request.GET.copy()
param_path = _with_path_prefix(table, 'order')
... | :type bound_columns: list of BoundColumn | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L112-L138 |
TriOptima/tri.table | lib/tri/table/__init__.py | order_by_on_list | def order_by_on_list(objects, order_field, is_desc=False):
"""
Utility function to sort objects django-style even for non-query set collections
:param objects: list of objects to sort
:param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
:para... | python | def order_by_on_list(objects, order_field, is_desc=False):
"""
Utility function to sort objects django-style even for non-query set collections
:param objects: list of objects to sort
:param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
:para... | Utility function to sort objects django-style even for non-query set collections
:param objects: list of objects to sort
:param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
:param is_desc: reverse the sorting
:return: | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L153-L172 |
TriOptima/tri.table | lib/tri/table/__init__.py | default_cell_formatter | def default_cell_formatter(table, column, row, value, **_):
"""
:type column: tri.table.Column
"""
formatter = _cell_formatters.get(type(value))
if formatter:
value = formatter(table=table, column=column, row=row, value=value)
if value is None:
return ''
return conditional_... | python | def default_cell_formatter(table, column, row, value, **_):
"""
:type column: tri.table.Column
"""
formatter = _cell_formatters.get(type(value))
if formatter:
value = formatter(table=table, column=column, row=row, value=value)
if value is None:
return ''
return conditional_... | :type column: tri.table.Column | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L207-L218 |
TriOptima/tri.table | lib/tri/table/__init__.py | django_pre_2_0_table_context | def django_pre_2_0_table_context(
request,
table,
links=None,
paginate_by=None,
page=None,
extra_context=None,
paginator=None,
show_hits=False,
hit_label='Items'):
"""
:type table: Table
"""
if extra_context is None: # pragma: no c... | python | def django_pre_2_0_table_context(
request,
table,
links=None,
paginate_by=None,
page=None,
extra_context=None,
paginator=None,
show_hits=False,
hit_label='Items'):
"""
:type table: Table
"""
if extra_context is None: # pragma: no c... | :type table: Table | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L1450-L1521 |
TriOptima/tri.table | lib/tri/table/__init__.py | table_context | def table_context(request,
table,
links=None,
paginate_by=None,
page=None,
extra_context=None,
paginator=None,
show_hits=False,
hit_label='Items'):
"""
:type table: Tab... | python | def table_context(request,
table,
links=None,
paginate_by=None,
page=None,
extra_context=None,
paginator=None,
show_hits=False,
hit_label='Items'):
"""
:type table: Tab... | :type table: Table | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L1524-L1589 |
TriOptima/tri.table | lib/tri/table/__init__.py | render_table | def render_table(request,
table,
links=None,
context=None,
template='tri_table/list.html',
blank_on_empty=False,
paginate_by=40, # pragma: no mutate
page=None,
paginator=None,
... | python | def render_table(request,
table,
links=None,
context=None,
template='tri_table/list.html',
blank_on_empty=False,
paginate_by=40, # pragma: no mutate
page=None,
paginator=None,
... | Render a table. This automatically handles pagination, sorting, filtering and bulk operations.
:param request: the request object. This is set on the table object so that it is available for lambda expressions.
:param table: an instance of Table
:param links: a list of instances of Link
:param context:... | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L1595-L1671 |
TriOptima/tri.table | lib/tri/table/__init__.py | render_table_to_response | def render_table_to_response(*args, **kwargs):
"""
Shortcut for `HttpResponse(render_table(*args, **kwargs))`
"""
response = render_table(*args, **kwargs)
if isinstance(response, HttpResponse): # pragma: no cover
return response
return HttpResponse(response) | python | def render_table_to_response(*args, **kwargs):
"""
Shortcut for `HttpResponse(render_table(*args, **kwargs))`
"""
response = render_table(*args, **kwargs)
if isinstance(response, HttpResponse): # pragma: no cover
return response
return HttpResponse(response) | Shortcut for `HttpResponse(render_table(*args, **kwargs))` | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L1674-L1681 |
infobloxopen/infoblox-client | infoblox_client/utils.py | generate_duid | def generate_duid(mac):
"""DUID is consisted of 10 hex numbers.
0x00 + mac with last 3 hex + mac with 6 hex
"""
valid = mac and isinstance(mac, six.string_types)
if not valid:
raise ValueError("Invalid argument was passed")
return "00:" + mac[9:] + ":" + mac | python | def generate_duid(mac):
"""DUID is consisted of 10 hex numbers.
0x00 + mac with last 3 hex + mac with 6 hex
"""
valid = mac and isinstance(mac, six.string_types)
if not valid:
raise ValueError("Invalid argument was passed")
return "00:" + mac[9:] + ":" + mac | DUID is consisted of 10 hex numbers.
0x00 + mac with last 3 hex + mac with 6 hex | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/utils.py#L41-L49 |
infobloxopen/infoblox-client | infoblox_client/utils.py | try_value_to_bool | def try_value_to_bool(value, strict_mode=True):
"""Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks... | python | def try_value_to_bool(value, strict_mode=True):
"""Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks... | Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks like True or False is converted into booleans.
Val... | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/utils.py#L85-L114 |
infobloxopen/infoblox-client | infoblox_client/object_manager.py | InfobloxObjectManager.create_network | def create_network(self, net_view_name, cidr, nameservers=None,
members=None, gateway_ip=None, dhcp_trel_ip=None,
network_extattrs=None):
"""Create NIOS Network and prepare DHCP options.
Some DHCP options are valid for IPv4 only, so just skip processing
... | python | def create_network(self, net_view_name, cidr, nameservers=None,
members=None, gateway_ip=None, dhcp_trel_ip=None,
network_extattrs=None):
"""Create NIOS Network and prepare DHCP options.
Some DHCP options are valid for IPv4 only, so just skip processing
... | Create NIOS Network and prepare DHCP options.
Some DHCP options are valid for IPv4 only, so just skip processing
them for IPv6 case.
:param net_view_name: network view name
:param cidr: network to allocate, example '172.23.23.0/24'
:param nameservers: list of name servers hosts... | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/object_manager.py#L58-L96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.