_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q233500 | DataIterator | train | 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 | {
"resource": ""
} |
q233501 | inspect | train | 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 | {
"resource": ""
} |
q233502 | clean_gff | train | 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 | {
"resource": ""
} |
q233503 | feature_from_line | train | 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 | {
"resource": ""
} |
q233504 | Feature.calc_bin | train | 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 | {
"resource": ""
} |
q233505 | Feature.astuple | train | 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 | {
"resource": ""
} |
q233506 | Feature.sequence | train | 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 | {
"resource": ""
} |
q233507 | infer_dialect | train | 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 | {
"resource": ""
} |
q233508 | _choose_dialect | train | 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 | {
"resource": ""
} |
q233509 | _bin_from_dict | train | 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 | {
"resource": ""
} |
q233510 | _jsonify | train | 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 | {
"resource": ""
} |
q233511 | _unjsonify | train | 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 | {
"resource": ""
} |
q233512 | _feature_to_fields | train | 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 | {
"resource": ""
} |
q233513 | _dict_to_fields | train | 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 | {
"resource": ""
} |
q233514 | merge_attributes | train | 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 | {
"resource": ""
} |
q233515 | dialect_compare | train | 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 | {
"resource": ""
} |
q233516 | sanitize_gff_db | train | 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 | {
"resource": ""
} |
q233517 | sanitize_gff_file | train | 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 | {
"resource": ""
} |
q233518 | is_gff_db | train | 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 | {
"resource": ""
} |
q233519 | get_gff_db | train | 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 | {
"resource": ""
} |
q233520 | _reconstruct | train | 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 | {
"resource": ""
} |
q233521 | create_db | train | 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 | {
"resource": ""
} |
q233522 | _DBCreator._id_handler | train | 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 | {
"resource": ""
} |
q233523 | _DBCreator.create | train | 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 | {
"resource": ""
} |
q233524 | _DBCreator.execute | train | 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 | {
"resource": ""
} |
q233525 | wait_for_js | train | 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 | {
"resource": ""
} |
q233526 | _wait_for_js | train | 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 | {
"resource": ""
} |
q233527 | _are_js_vars_defined | train | 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 | {
"resource": ""
} |
q233528 | _are_requirejs_deps_loaded | train | 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 | {
"resource": ""
} |
q233529 | no_selenium_errors | train | 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 | {
"resource": ""
} |
q233530 | AxsAuditConfig.set_rules | train | 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 | {
"resource": ""
} |
q233531 | AxsAuditConfig.set_scope | train | 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 | {
"resource": ""
} |
q233532 | AxsAudit._check_rules | train | 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 | {
"resource": ""
} |
q233533 | Promise.fulfill | train | 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 | {
"resource": ""
} |
q233534 | GitHubSearchPage.search | train | 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 | {
"resource": ""
} |
q233535 | AxeCoreAuditConfig.set_rules | train | 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 | {
"resource": ""
} |
q233536 | AxeCoreAuditConfig.customize_ruleset | train | 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 | {
"resource": ""
} |
q233537 | AxeCoreAudit._check_rules | train | 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 | {
"resource": ""
} |
q233538 | save_source | train | 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 | {
"resource": ""
} |
q233539 | save_screenshot | train | 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 | {
"resource": ""
} |
q233540 | save_driver_logs | train | 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 | {
"resource": ""
} |
q233541 | browser | train | 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 | {
"resource": ""
} |
q233542 | _firefox_profile | train | 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 | {
"resource": ""
} |
q233543 | _local_browser_class | train | 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 | {
"resource": ""
} |
q233544 | _remote_browser_class | train | 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 | {
"resource": ""
} |
q233545 | _proxy_kwargs | train | 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 | {
"resource": ""
} |
q233546 | _required_envs | train | 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 | {
"resource": ""
} |
q233547 | _optional_envs | train | 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 | {
"resource": ""
} |
q233548 | _capabilities_dict | train | 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 | {
"resource": ""
} |
q233549 | Query.replace | train | 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 | {
"resource": ""
} |
q233550 | Query.transform | train | 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 | {
"resource": ""
} |
q233551 | Query.map | train | 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 | {
"resource": ""
} |
q233552 | Query.filter | train | 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 | {
"resource": ""
} |
q233553 | Query._execute | train | 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 | {
"resource": ""
} |
q233554 | Query.execute | train | 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 | {
"resource": ""
} |
q233555 | Query.first | train | 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 | {
"resource": ""
} |
q233556 | BrowserQuery.attrs | train | 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 | {
"resource": ""
} |
q233557 | BrowserQuery.selected | train | 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 | {
"resource": ""
} |
q233558 | BrowserQuery.visible | train | 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 | {
"resource": ""
} |
q233559 | BrowserQuery.fill | train | 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 | {
"resource": ""
} |
q233560 | PatchedManifestStaticFilesStorage.url_converter | train | 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 | {
"resource": ""
} |
q233561 | order_by_on_list | train | 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 | {
"resource": ""
} |
q233562 | render_table | train | 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 | {
"resource": ""
} |
q233563 | generate_duid | train | 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 | {
"resource": ""
} |
q233564 | try_value_to_bool | train | 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 | {
"resource": ""
} |
q233565 | InfobloxObjectManager.create_network | train | 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 | {
"resource": ""
} |
q233566 | InfobloxObjectManager.create_ip_range | train | def create_ip_range(self, network_view, start_ip, end_ip, network,
disable, range_extattrs):
"""Creates IPRange or fails if already exists."""
return obj.IPRange.create(self.connector,
network_view=network_view,
... | python | {
"resource": ""
} |
q233567 | Connector._parse_options | train | def _parse_options(self, options):
"""Copy needed options to self"""
attributes = ('host', 'wapi_version', 'username', 'password',
'ssl_verify', 'http_request_timeout', 'max_retries',
'http_pool_connections', 'http_pool_maxsize',
'silent_... | python | {
"resource": ""
} |
q233568 | Connector._parse_reply | train | def _parse_reply(request):
"""Tries to parse reply from NIOS.
Raises exception with content if reply is not in json format
"""
try:
return jsonutils.loads(request.content)
except ValueError:
raise ib_ex.InfobloxConnectionError(reason=request.content) | python | {
"resource": ""
} |
q233569 | Connector.get_object | train | def get_object(self, obj_type, payload=None, return_fields=None,
extattrs=None, force_proxy=False, max_results=None,
paging=False):
"""Retrieve a list of Infoblox objects of type 'obj_type'
Some get requests like 'ipv4address' should be always
proxied to GM... | python | {
"resource": ""
} |
q233570 | Connector.create_object | train | def create_object(self, obj_type, payload, return_fields=None):
"""Create an Infoblox object of type 'obj_type'
Args:
obj_type (str): Infoblox object type,
e.g. 'network', 'range', etc.
payload (dict): Payload with data to send
... | python | {
"resource": ""
} |
q233571 | Connector.update_object | train | def update_object(self, ref, payload, return_fields=None):
"""Update an Infoblox object
Args:
ref (str): Infoblox object reference
payload (dict): Payload with data to send
Returns:
The object reference of the updated object
Raises:
I... | python | {
"resource": ""
} |
q233572 | Connector.delete_object | train | def delete_object(self, ref, delete_arguments=None):
"""Remove an Infoblox object
Args:
ref (str): Object reference
delete_arguments (dict): Extra delete arguments
Returns:
The object reference of the removed object
Raises:
I... | python | {
"resource": ""
} |
q233573 | BaseObject._remap_fields | train | def _remap_fields(cls, kwargs):
"""Map fields from kwargs into dict acceptable by NIOS"""
mapped = {}
for key in kwargs:
if key in cls._remap:
mapped[cls._remap[key]] = kwargs[key]
else:
mapped[key] = kwargs[key]
return mapped | python | {
"resource": ""
} |
q233574 | EA.from_dict | train | def from_dict(cls, eas_from_nios):
"""Converts extensible attributes from the NIOS reply."""
if not eas_from_nios:
return
return cls({name: cls._process_value(ib_utils.try_value_to_bool,
eas_from_nios[name]['value'])
fo... | python | {
"resource": ""
} |
q233575 | EA.to_dict | train | def to_dict(self):
"""Converts extensible attributes into the format suitable for NIOS."""
return {name: {'value': self._process_value(str, value)}
for name, value in self._ea_dict.items()
if not (value is None or value == "" or value == [])} | python | {
"resource": ""
} |
q233576 | EA._process_value | train | def _process_value(func, value):
"""Applies processing method for value or each element in it.
:param func: method to be called with value
:param value: value to process
:return: if 'value' is list/tupe, returns iterable with func results,
else func result is returned
... | python | {
"resource": ""
} |
q233577 | InfobloxObject.from_dict | train | def from_dict(cls, connector, ip_dict):
"""Build dict fields as SubObjects if needed.
Checks if lambda for building object from dict exists.
_global_field_processing and _custom_field_processing rules
are checked.
"""
mapping = cls._global_field_processing.copy()
... | python | {
"resource": ""
} |
q233578 | InfobloxObject.field_to_dict | train | def field_to_dict(self, field):
"""Read field value and converts to dict if possible"""
value = getattr(self, field)
if isinstance(value, (list, tuple)):
return [self.value_to_dict(val) for val in value]
return self.value_to_dict(value) | python | {
"resource": ""
} |
q233579 | InfobloxObject.to_dict | train | def to_dict(self, search_fields=None):
"""Builds dict without None object fields"""
fields = self._fields
if search_fields == 'update':
fields = self._search_for_update_fields
elif search_fields == 'all':
fields = self._all_searchable_fields
elif search_fi... | python | {
"resource": ""
} |
q233580 | InfobloxObject.fetch | train | def fetch(self, only_ref=False):
"""Fetch object from NIOS by _ref or searchfields
Update existent object with fields returned from NIOS
Return True on successful object fetch
"""
if self.ref:
reply = self.connector.get_object(
self.ref, return_fields... | python | {
"resource": ""
} |
q233581 | HostRecord._ip_setter | train | def _ip_setter(self, ipaddr_name, ipaddrs_name, ips):
"""Setter for ip fields
Accept as input string or list of IP instances.
String case:
only ipvXaddr is going to be filled, that is enough to perform
host record search using ip
List of IP instances case:
... | python | {
"resource": ""
} |
q233582 | FixedAddressV6.mac | train | def mac(self, mac):
"""Set mac and duid fields
To have common interface with FixedAddress accept mac address
and set duid as a side effect.
'mac' was added to _shadow_fields to prevent sending it out over wapi.
"""
self._mac = mac
if mac:
self.duid = ... | python | {
"resource": ""
} |
q233583 | render_property | train | def render_property(property):
"""Render a property for bosh manifest, according to its type."""
# This ain't the prettiest thing, but it should get the job done.
# I don't think we have anything more elegant available at bosh-manifest-generation time.
# See https://docs.pivotal.io/partners/product-template-referen... | python | {
"resource": ""
} |
q233584 | match | train | def match(obj, matchers=TYPES):
"""
Matches the given input againts the available
file type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if type matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
"""
buf... | python | {
"resource": ""
} |
q233585 | signature | train | def signature(array):
"""
Returns the first 262 bytes of the given bytearray
as part of the file header signature.
Args:
array: bytearray to extract the header signature.
Returns:
First 262 bytes of the file content as bytearray type.
"""
length = len(array)
index = _NU... | python | {
"resource": ""
} |
q233586 | get_bytes | train | def get_bytes(obj):
"""
Infers the input type and reads the first 262 bytes,
returning a sliced bytearray.
Args:
obj: path to readable, file, bytes or bytearray.
Returns:
First 262 bytes of the file content as bytearray type.
Raises:
TypeError: if obj is not a supporte... | python | {
"resource": ""
} |
q233587 | get_type | train | def get_type(mime=None, ext=None):
"""
Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type instance. Otherwise None.
... | python | {
"resource": ""
} |
q233588 | Tail.open | train | def open(self, encoding=None):
"""Opens the file with the appropriate call"""
try:
if IS_GZIPPED_FILE.search(self._filename):
_file = gzip.open(self._filename, 'rb')
else:
if encoding:
_file = io.open(self._filename, 'r', encodi... | python | {
"resource": ""
} |
q233589 | Tail.close | train | def close(self):
"""Closes all currently open file pointers"""
if not self.active:
return
self.active = False
if self._file:
self._file.close()
self._sincedb_update_position(force_update=True)
if self._current_event:
event = '\n'.... | python | {
"resource": ""
} |
q233590 | Tail._ensure_file_is_good | train | def _ensure_file_is_good(self, current_time):
"""Every N seconds, ensures that the file we are tailing is the file we expect to be tailing"""
if self._last_file_mapping_update and current_time - self._last_file_mapping_update <= self._stat_interval:
return
self._last_file_mapping_up... | python | {
"resource": ""
} |
q233591 | Tail._run_pass | train | def _run_pass(self):
"""Read lines from a file and performs a callback against them"""
while True:
try:
data = self._file.read(4096)
except IOError, e:
if e.errno == errno.ESTALE:
self.active = False
return F... | python | {
"resource": ""
} |
q233592 | Tail._sincedb_init | train | def _sincedb_init(self):
"""Initializes the sincedb schema in an sqlite db"""
if not self._sincedb_path:
return
if not os.path.exists(self._sincedb_path):
self._log_debug('initializing sincedb sqlite schema')
conn = sqlite3.connect(self._sincedb_path, isolati... | python | {
"resource": ""
} |
q233593 | Tail._sincedb_update_position | train | def _sincedb_update_position(self, lines=0, force_update=False):
"""Retrieves the starting position from the sincedb sql db for a given file
Returns a boolean representing whether or not it updated the record
"""
if not self._sincedb_path:
return False
self._line_cou... | python | {
"resource": ""
} |
q233594 | Tail._sincedb_start_position | train | def _sincedb_start_position(self):
"""Retrieves the starting position from the sincedb sql db
for a given file
"""
if not self._sincedb_path:
return None
self._sincedb_init()
self._log_debug('retrieving start_position from sincedb')
conn = sqlite3.con... | python | {
"resource": ""
} |
q233595 | Tail._update_file | train | def _update_file(self, seek_to_end=True):
"""Open the file for tailing"""
try:
self.close()
self._file = self.open()
except IOError:
pass
else:
if not self._file:
return
self.active = True
try:
... | python | {
"resource": ""
} |
q233596 | Tail.tail | train | def tail(self, fname, encoding, window, position=None):
"""Read last N lines from file fname."""
if window <= 0:
raise ValueError('invalid window %r' % window)
encodings = ENCODINGS
if encoding:
encodings = [encoding] + ENCODINGS
for enc in encodings:
... | python | {
"resource": ""
} |
q233597 | create_transport | train | def create_transport(beaver_config, logger):
"""Creates and returns a transport object"""
transport_str = beaver_config.get('transport')
if '.' not in transport_str:
# allow simple names like 'redis' to load a beaver built-in transport
module_path = 'beaver.transports.%s_transport' % transpo... | python | {
"resource": ""
} |
q233598 | TailManager.update_files | train | def update_files(self):
"""Ensures all files are properly loaded.
Detects new files, file removals, file rotation, and truncation.
On non-linux platforms, it will also manually reload the file for tailing.
Note that this hack is necessary because EOF is cached on BSD systems.
"""... | python | {
"resource": ""
} |
q233599 | TailManager.close | train | def close(self, signalnum=None, frame=None):
self._running = False
"""Closes all currently open Tail objects"""
self._log_debug("Closing all tail objects")
self._active = False
for fid in self._tails:
self._tails[fid].close()
for n in range(0,self._number_of_c... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.