_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q39100 | ids_from_seqs_iterative | train | def ids_from_seqs_iterative(seqs, app, query_parser, \
scorer=keep_everything_scorer, max_iterations=None, blast_db=None,\
max_seqs=None, ):
"""Gets the ids from each seq, then does each additional id until all done.
If scorer is passed in as an int, uses shotgun scorer with that # hits.
"""
if... | python | {
"resource": ""
} |
q39101 | blastp | train | def blastp(seqs, blast_db="nr", e_value="1e-20", max_hits=200,
working_dir=tempfile.gettempdir(), blast_mat_root=None,
extra_params={}):
"""
Returns BlastResult from input seqs, using blastp.
Need to add doc string
"""
# set up params to use with blastp
params = {
... | python | {
"resource": ""
} |
q39102 | set_lock | train | def set_lock(fname):
"""
Try to lock file and write PID.
Return the status of operation.
"""
global fh
fh = open(fname, 'w')
if os.name == 'nt':
# Code for NT systems got from: http://code.activestate.com/recipes/65203/
import win32con
import win32... | python | {
"resource": ""
} |
q39103 | assert_lock | train | def assert_lock(fname):
"""
If file is locked then terminate program else lock file.
"""
if not set_lock(fname):
logger.error('File {} is already locked. Terminating.'.format(fname))
sys.exit() | python | {
"resource": ""
} |
q39104 | build_blast_db_from_seqs | train | def build_blast_db_from_seqs(seqs, is_protein=False, output_dir='./',
HALT_EXEC=False):
"""Build blast db from seqs; return db name and list of files created
**If using to create temporary blast databases, you can call
cogent.util.misc.remove_files(db_filepaths) to clea... | python | {
"resource": ""
} |
q39105 | RedisSessionMiddleware._session_key | train | def _session_key(self):
"""Gets the redis key for a session"""
if not hasattr(self, "_cached_session_key"):
session_id_bytes = self.get_secure_cookie("session_id")
session_id = None
if session_id_bytes:
try:
session_id = session_i... | python | {
"resource": ""
} |
q39106 | RedisSessionMiddleware._update_session_expiration | train | def _update_session_expiration(self):
"""
Updates a redis item to expire later since it has been interacted with
recently
"""
session_time = oz.settings["session_time"]
if session_time:
self.redis().expire(self._session_key, session_time) | python | {
"resource": ""
} |
q39107 | RedisSessionMiddleware.get_session_value | train | def get_session_value(self, name, default=None):
"""Gets a session value"""
value = self.redis().hget(self._session_key, name) or default
self._update_session_expiration()
return value | python | {
"resource": ""
} |
q39108 | RedisSessionMiddleware.set_session_value | train | def set_session_value(self, name, value):
"""Sets a session value"""
self.redis().hset(self._session_key, name, value)
self._update_session_expiration() | python | {
"resource": ""
} |
q39109 | RedisSessionMiddleware.clear_session_value | train | def clear_session_value(self, name):
"""Removes a session value"""
self.redis().hdel(self._session_key, name)
self._update_session_expiration() | python | {
"resource": ""
} |
q39110 | rewrite_middleware | train | async def rewrite_middleware(server, request):
'''
Sanic middleware that utilizes a security class's "rewrite" method to
check
'''
if singletons.settings.SECURITY is not None:
security_class = singletons.settings.load('SECURITY')
else:
security_class = DummySecurity
security ... | python | {
"resource": ""
} |
q39111 | Commit.get_objects | train | def get_objects(self, uri, pull=True, **kwargs):
'''
Walk through repo commits to generate a list of repo commit
objects.
Each object has the following properties:
* repo uri
* general commit info
* files added, removed fnames
* lines adde... | python | {
"resource": ""
} |
q39112 | _dict_values_sorted_by_key | train | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value | python | {
"resource": ""
} |
q39113 | _ondemand | train | def _ondemand(f):
"""Decorator to only request information if not in cache already.
"""
name = f.__name__
def func(self, *args, **kwargs):
if not args and not kwargs:
if hasattr(self, '_%s' % name):
return getattr(self, '_%s' % name)
a = f(self, *args, *... | python | {
"resource": ""
} |
q39114 | CachedIDAMemory.get_memory | train | def get_memory(self, start, size):
"""Retrieve an area of memory from IDA.
Returns a sparse dictionary of address -> value.
"""
LOG.debug('get_memory: %d bytes from %x', size, start)
return get_memory(self.ida.idaapi, start, size,
default_byte=self.defau... | python | {
"resource": ""
} |
q39115 | handle_404 | train | def handle_404(request, exception):
'''Handle 404 Not Found
This handler should be used to handle error http 404 not found for all
endpoints or if resource not available.
'''
error = format_error(title='Resource not found', detail=str(exception))
return json(return_an_error(error), status=HTTPSt... | python | {
"resource": ""
} |
q39116 | _add_to_dict | train | def _add_to_dict(t, container, name, value):
"""
Adds an item to a dictionary, or raises an exception if an item with the
specified key already exists in the dictionary.
"""
if name in container:
raise Exception("%s '%s' already exists" % (t, name))
else:
container[name] = value | python | {
"resource": ""
} |
q39117 | RequestHandler.trigger | train | def trigger(self, name, *args, **kwargs):
"""
Triggers an event to run through middleware. This method will execute
a chain of relevant trigger callbacks, until one of the callbacks
returns the `break_trigger`.
"""
# Relevant middleware is cached so we don't have to redi... | python | {
"resource": ""
} |
q39118 | Resource.cache_makedirs | train | def cache_makedirs(self, subdir=None):
'''
Make necessary directories to hold cache value
'''
if subdir is not None:
dirname = self.cache_path
if subdir:
dirname = os.path.join(dirname, subdir)
else:
dirname = os.path.dirname(se... | python | {
"resource": ""
} |
q39119 | session | train | def session(connection_string=None):
"""Gets a SQLAlchemy session"""
global _session_makers
connection_string = connection_string or oz.settings["db"]
if not connection_string in _session_makers:
_session_makers[connection_string] = sessionmaker(bind=engine(connection_string=connection_string))... | python | {
"resource": ""
} |
q39120 | assign_dna_reads_to_dna_database | train | def assign_dna_reads_to_dna_database(query_fasta_fp, database_fasta_fp,
output_fp, params=None):
"""Assign DNA reads to a database fasta of DNA sequences.
Wraps assign_reads_to_database, setting database and query types. All
parameters are set to default unless params i... | python | {
"resource": ""
} |
q39121 | assign_dna_reads_to_protein_database | train | def assign_dna_reads_to_protein_database(query_fasta_fp, database_fasta_fp,
output_fp, temp_dir="/tmp", params=None):
"""Assign DNA reads to a database fasta of protein sequences.
Wraps assign_reads_to_database, setting database and query types. All
parameters are s... | python | {
"resource": ""
} |
q39122 | Blat._get_base_command | train | def _get_base_command(self):
"""Gets the command that will be run when the app controller is
called.
"""
command_parts = []
cd_command = ''.join(['cd ', str(self.WorkingDir), ';'])
if self._command is None:
raise ApplicationError('_command has not been set.')
... | python | {
"resource": ""
} |
q39123 | woa_profile_from_dap | train | def woa_profile_from_dap(var, d, lat, lon, depth, cfg):
"""
Monthly Climatologic Mean and Standard Deviation from WOA,
used either for temperature or salinity.
INPUTS
time: [day of the year]
lat: [-90<lat<90]
lon: [-180<lon<180]
depth: [meters]
Reads the WOA Monthly... | python | {
"resource": ""
} |
q39124 | DatabaseCollection.iterator | train | def iterator(cls, path=None, objtype=None, query=None, page_size=1000, **kwargs):
""""
Linear time, constant memory, iterator for a mongo collection.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
... | python | {
"resource": ""
} |
q39125 | pair_hmm_align_unaligned_seqs | train | def pair_hmm_align_unaligned_seqs(seqs, moltype=DNA_cogent, params={}):
"""
Checks parameters for pairwise alignment, returns alignment.
Code from Greg Caporaso.
"""
seqs = LoadSeqs(data=seqs, moltype=moltype, aligned=False)
try:
s1, s2 = seqs.values()
except ValueError:
... | python | {
"resource": ""
} |
q39126 | viewers_js | train | async def viewers_js(request):
'''
Viewers determines the viewers installed based on settings, then uses the
conversion infrastructure to convert all these JS files into a single JS
bundle, that is then served. As with media, it will simply serve a cached
version if necessary.
'''
# Generate... | python | {
"resource": ""
} |
q39127 | Rows.get_objects | train | def get_objects(self, uri, _oid=None, _start=None, _end=None,
load_kwargs=None, **kwargs):
'''
Load and transform csv data into a list of dictionaries.
Each row in the csv will result in one dictionary in the list.
:param uri: uri (file://, http(s)://) of csv file t... | python | {
"resource": ""
} |
q39128 | vsearch_dereplicate_exact_seqs | train | def vsearch_dereplicate_exact_seqs(
fasta_filepath,
output_filepath,
output_uc=False,
working_dir=None,
strand="both",
maxuniquesize=None,
minuniquesize=None,
sizein=False,
sizeout=True,
log_name="derep.log",
HALT_EXEC=False):
""" Generates clusters and fasta file of
... | python | {
"resource": ""
} |
q39129 | PaaSProvider.init | train | def init(cls, site):
"""
put site settings in the header of the script
"""
bash_header = ""
for k,v in site.items():
bash_header += "%s=%s" % (k.upper(), v)
bash_header += '\n'
site['bash_header'] = bash_header
# TODO: execute before_deplo... | python | {
"resource": ""
} |
q39130 | PaaSProvider._render_config | train | def _render_config(cls, dest, template_name, template_args):
"""
Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations
"""
template_args = template_args.copy()
# Substitute values here
pyversion = tem... | python | {
"resource": ""
} |
q39131 | CommandParser.parse_args_to_action_args | train | def parse_args_to_action_args(self, argv=None):
'''
Parses args and returns an action and the args that were parsed
'''
args = self.parse_args(argv)
action = self.subcommands[args.subcommand][1]
return action, args | python | {
"resource": ""
} |
q39132 | CommandParser.register_subparser | train | def register_subparser(self, action, name, description='', arguments={}):
'''
Registers a new subcommand with a given function action.
If the function action is synchronous
'''
action = coerce_to_synchronous(action)
opts = []
for flags, kwargs in arguments.items(... | python | {
"resource": ""
} |
q39133 | CommandParser.subcommand | train | def subcommand(self, description='', arguments={}):
'''
Decorator for quickly adding subcommands to the omnic CLI
'''
def decorator(func):
self.register_subparser(
func,
func.__name__.replace('_', '-'),
description=description,
... | python | {
"resource": ""
} |
q39134 | CommandParser.print | train | def print(self, *args, **kwargs):
'''
Utility function that behaves identically to 'print' except it only
prints if verbose
'''
if self._last_args and self._last_args.verbose:
print(*args, **kwargs) | python | {
"resource": ""
} |
q39135 | process_uclust_pw_alignment_results | train | def process_uclust_pw_alignment_results(fasta_pairs_lines, uc_lines):
""" Process results of uclust search and align """
alignments = get_next_two_fasta_records(fasta_pairs_lines)
for hit in get_next_record_type(uc_lines, 'H'):
matching_strand = hit[4]
if matching_strand == '-':
... | python | {
"resource": ""
} |
q39136 | uclust_search_and_align_from_fasta_filepath | train | def uclust_search_and_align_from_fasta_filepath(
query_fasta_filepath,
subject_fasta_filepath,
percent_ID=0.75,
enable_rev_strand_matching=True,
max_accepts=8,
max_rejects=32,
tmp_dir=gettempdir(),
HALT_EXEC=False):
""" query seqs against subject fasta... | python | {
"resource": ""
} |
q39137 | uclust_cluster_from_sorted_fasta_filepath | train | def uclust_cluster_from_sorted_fasta_filepath(
fasta_filepath,
uc_save_filepath=None,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
enable_rev_strand_matc... | python | {
"resource": ""
} |
q39138 | get_clusters_from_fasta_filepath | train | def get_clusters_from_fasta_filepath(
fasta_filepath,
original_fasta_path,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
output_dir=None,
enable_r... | python | {
"resource": ""
} |
q39139 | Generic._activity_import_doc | train | def _activity_import_doc(self, time_doc, activities):
'''
Import activities for a single document into timeline.
'''
batch_updates = [time_doc]
# We want to consider only activities that happend before time_doc
# do not move this, because time_doc._start changes
#... | python | {
"resource": ""
} |
q39140 | Generic.get_changed_oids | train | def get_changed_oids(self, last_update=None):
'''
Returns a list of object ids of those objects that have changed since
`mtime`. This method expects that the changed objects can be
determined based on the `delta_mtime` property of the cube which
specifies the field name that carr... | python | {
"resource": ""
} |
q39141 | Generic.get_objects | train | def get_objects(self, force=None, last_update=None, flush=False):
'''
Extract routine for SQL based cubes.
:param force:
for querying for all objects (True) or only those passed in as list
:param last_update: manual override for 'changed since date'
'''
retur... | python | {
"resource": ""
} |
q39142 | Generic.get_new_oids | train | def get_new_oids(self):
'''
Returns a list of unique oids that have not been extracted yet.
Essentially, a diff of distinct oids in the source database
compared to cube.
'''
table = self.lconfig.get('table')
_oid = self.lconfig.get('_oid')
if is_array(_oi... | python | {
"resource": ""
} |
q39143 | Generic.get_full_history | train | def get_full_history(self, force=None, last_update=None, flush=False):
'''
Fields change depending on when you run activity_import,
such as "last_updated" type fields which don't have activity
being tracked, which means we'll always end up with different
hash values, so we need t... | python | {
"resource": ""
} |
q39144 | Generic.sql_get_oids | train | def sql_get_oids(self, where=None):
'''
Query source database for a distinct list of oids.
'''
table = self.lconfig.get('table')
db = self.lconfig.get('db_schema_name') or self.lconfig.get('db')
_oid = self.lconfig.get('_oid')
if is_array(_oid):
_oid =... | python | {
"resource": ""
} |
q39145 | Pplacer.getTmpFilename | train | def getTmpFilename(self, tmp_dir="/tmp",prefix='tmp',suffix='.fasta',\
include_class_id=False,result_constructor=FilePath):
""" Define Tmp filename to contain .fasta suffix, since pplacer requires
the suffix to be .fasta """
return super(Pplacer,self).getTmpFilename(tmp_dir=tmp_d... | python | {
"resource": ""
} |
q39146 | Pplacer._get_result_paths | train | def _get_result_paths(self,data):
""" Define the output filepaths """
output_dir = self.Parameters['--out-dir'].Value
result = {}
result['json'] = ResultPath(Path=join(output_dir,
splitext(split(self._input_filename)[-1])[0] + \
... | python | {
"resource": ""
} |
q39147 | chi_squared | train | def chi_squared(*choices):
"""Calculates the chi squared"""
term = lambda expected, observed: float((expected - observed) ** 2) / max(expected, 1)
mean_success_rate = float(sum([c.rewards for c in choices])) / max(sum([c.plays for c in choices]), 1)
mean_failure_rate = 1 - mean_success_rate
return... | python | {
"resource": ""
} |
q39148 | get_experiments | train | def get_experiments(redis, active=True):
"""Gets the full list of experiments"""
key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY
return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)] | python | {
"resource": ""
} |
q39149 | Experiment.choices | train | def choices(self):
"""Gets the experiment choices"""
if self._choices == None:
self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names]
return self._choices | python | {
"resource": ""
} |
q39150 | Experiment.add_play | train | def add_play(self, choice, count=1):
"""Increments the play count for a given experiment choice"""
self.redis.hincrby(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "%s:plays" % choice, count)
self._choices = None | python | {
"resource": ""
} |
q39151 | Experiment.compute_default_choice | train | def compute_default_choice(self):
"""Computes and sets the default choice"""
choices = self.choices
if len(choices) == 0:
return None
high_choice = max(choices, key=lambda choice: choice.performance)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "defau... | python | {
"resource": ""
} |
q39152 | await_all | train | async def await_all():
'''
Simple utility function that drains all pending tasks
'''
tasks = asyncio.Task.all_tasks()
for task in tasks:
try:
await task
except RuntimeError as e:
# Python 3.5.x: Error if attempting to await parent task
if 'Task can... | python | {
"resource": ""
} |
q39153 | coerce_to_synchronous | train | def coerce_to_synchronous(func):
'''
Given a function that might be async, wrap it in an explicit loop so it can
be run in a synchronous context.
'''
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
def sync_wrapper(*args, **kwargs):
loop = asyncio.get_event_l... | python | {
"resource": ""
} |
q39154 | _get_matchable_segments | train | def _get_matchable_segments(segments):
"""
Performs a depth-first search of the segment tree to get all matchable
segments.
"""
for subsegment in segments:
if isinstance(subsegment, Token):
break # No tokens allowed next to segments
if isinstance(subsegment, Segment):
... | python | {
"resource": ""
} |
q39155 | VW._get_response | train | def _get_response(self, parse_result=True):
"""If 'parse_result' is False, ignore the received output and return None."""
# expect_exact is faster than just exact, and fine for our purpose
# (http://pexpect.readthedocs.org/en/latest/api/pexpect.html#pexpect.spawn.expect_exact)
# searchwi... | python | {
"resource": ""
} |
q39156 | VW.send_example | train | def send_example(self,
*args,
**kwargs
):
"""Send a labeled or unlabeled example to the VW instance.
If 'parse_result' kwarg is False, ignore the result and return None.
All other parameters are passed to self.send_line().
... | python | {
"resource": ""
} |
q39157 | VW.save_model | train | def save_model(self, model_filename):
"""Pass a "command example" to the VW subprocess requesting
that the current model be serialized to model_filename immediately.
"""
line = "save_{}|".format(model_filename)
self.vw_process.sendline(line) | python | {
"resource": ""
} |
q39158 | WebServer.route_path | train | def route_path(self, path):
'''
Hacky function that's presently only useful for testing, gets the view
that handles the given path.
Later may be incorporated into the URL routing
'''
path = path.strip('/')
name, _, subpath = path.partition('/')
for service... | python | {
"resource": ""
} |
q39159 | pair_looper | train | def pair_looper(iterator):
'''
Loop through iterator yielding items in adjacent pairs
'''
left = START
for item in iterator:
if left is not START:
yield (left, item)
left = item | python | {
"resource": ""
} |
q39160 | clear_stale_pids | train | def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
'check for and remove any pids which have no corresponding process'
if isinstance(pids, (int, float, long)):
pids = [pids]
pids = str2list(pids, map_=unicode)
procs = map(unicode, os.listdir('/proc'))
running = [pid for pid ... | python | {
"resource": ""
} |
q39161 | cube_pkg_mod_cls | train | def cube_pkg_mod_cls(cube):
'''
Used to dynamically importing cube classes
based on string slug name.
Converts 'pkg_mod' -> pkg, mod, Cls
eg: tw_tweet -> tw, tweet, Tweet
Assumes `Metrique Cube Naming Convention` is used
:param cube: cube name to use when searching for cube pkg.mod.class... | python | {
"resource": ""
} |
q39162 | debug_setup | train | def debug_setup(logger=None, level=None, log2file=None,
log_file=None, log_format=None, log_dir=None,
log2stdout=None, truncate=False):
'''
Local object instance logger setup.
Verbosity levels are determined as such::
if level in [-1, False]:
logger.setL... | python | {
"resource": ""
} |
q39163 | get_cube | train | def get_cube(cube, init=False, pkgs=None, cube_paths=None, config=None,
backends=None, **kwargs):
'''
Dynamically locate and load a metrique cube
:param cube: name of the cube class to import from given module
:param init: flag to request initialized instance or uninitialized class
:pa... | python | {
"resource": ""
} |
q39164 | get_timezone_converter | train | def get_timezone_converter(from_timezone, to_tz=None, tz_aware=False):
'''
return a function that converts a given
datetime object from a timezone to utc
:param from_timezone: timezone name as string
'''
if not from_timezone:
return None
is_true(HAS_DATEUTIL, "`pip install python_da... | python | {
"resource": ""
} |
q39165 | is_empty | train | def is_empty(value, msg=None, except_=None, inc_zeros=True):
'''
is defined, but null or empty like value
'''
if hasattr(value, 'empty'):
# dataframes must check for .empty
# since they don't define truth value attr
# take the negative, since below we're
# checking for ca... | python | {
"resource": ""
} |
q39166 | is_null | train | def is_null(value, msg=None, except_=None):
'''
ie, "is not defined"
'''
# dataframes, even if empty, are not considered null
value = False if hasattr(value, 'empty') else value
result = bool(
value is None or
value != value or
repr(value) == 'NaT')
if except_:
... | python | {
"resource": ""
} |
q39167 | json_encode_default | train | def json_encode_default(obj):
'''
Convert datetime.datetime to timestamp
:param obj: value to (possibly) convert
'''
if isinstance(obj, (datetime, date)):
result = dt2ts(obj)
else:
result = json_encoder.default(obj)
return to_encoding(result) | python | {
"resource": ""
} |
q39168 | jsonhash | train | def jsonhash(obj, root=True, exclude=None, hash_func=_jsonhash_sha1):
'''
calculate the objects hash based on all field values
'''
if isinstance(obj, Mapping):
# assumption: using in against set() is faster than in against list()
if root and exclude:
obj = {k: v for k, v in o... | python | {
"resource": ""
} |
q39169 | load | train | def load(path, filetype=None, as_df=False, retries=None,
_oid=None, quiet=False, **kwargs):
'''Load multiple files from various file types automatically.
Supports glob paths, eg::
path = 'data/*.csv'
Filetypes are autodetected by common extension strings.
Currently supports loadings... | python | {
"resource": ""
} |
q39170 | read_file | train | def read_file(rel_path, paths=None, raw=False, as_list=False, as_iter=False,
*args, **kwargs):
'''
find a file that lives somewhere within a set of paths and
return its contents. Default paths include 'static_dir'
'''
if not rel_path:
raise ValueError("rel_path can not ... | python | {
"resource": ""
} |
q39171 | safestr | train | def safestr(str_):
''' get back an alphanumeric only version of source '''
str_ = str_ or ""
return "".join(x for x in str_ if x.isalnum()) | python | {
"resource": ""
} |
q39172 | urlretrieve | train | def urlretrieve(uri, saveas=None, retries=3, cache_dir=None):
'''urllib.urlretrieve wrapper'''
retries = int(retries) if retries else 3
# FIXME: make random filename (saveas) in cache_dir...
# cache_dir = cache_dir or CACHE_DIR
while retries:
try:
_path, headers = urllib.urlretri... | python | {
"resource": ""
} |
q39173 | reverse_media_url | train | def reverse_media_url(target_type, url_string, *args, **kwargs):
'''
Given a target type and an resource URL, generates a valid URL to this via
'''
args_str = '<%s>' % '><'.join(args)
kwargs_str = '<%s>' % '><'.join('%s:%s' % pair for pair in kwargs.items())
url_str = ''.join([url_string, args_s... | python | {
"resource": ""
} |
q39174 | _isbn_cleanse | train | def _isbn_cleanse(isbn, checksum=True):
"""Check ISBN is a string, and passes basic sanity checks.
Args:
isbn (str): SBN, ISBN-10 or ISBN-13
checksum (bool): ``True`` if ``isbn`` includes checksum character
Returns:
``str``: ISBN with hyphenation removed, including when called with... | python | {
"resource": ""
} |
q39175 | convert | train | def convert(isbn, code='978'):
"""Convert ISBNs between ISBN-10 and ISBN-13.
Note:
No attempt to hyphenate converted ISBNs is made, because the
specification requires that *any* hyphenation must be correct but
allows ISBNs without hyphenation.
Args:
isbn (str): SBN, ISBN-10... | python | {
"resource": ""
} |
q39176 | Isbn.to_url | train | def to_url(self, site='amazon', country='us'):
"""Generate a link to an online book site.
Args:
site (str): Site to create link to
country (str): Country specific version of ``site``
Returns:
``str``: URL on ``site`` for book
Raises:
Sit... | python | {
"resource": ""
} |
q39177 | RegexTokenizer._tokenize | train | def _tokenize(self, text, token_class=None):
"""
Tokenizes a text
:Returns:
A `list` of tokens
"""
token_class = token_class or Token
tokens = {}
for i, match in enumerate(self.regex.finditer(text)):
value = match.group(0)
tr... | python | {
"resource": ""
} |
q39178 | _parse_cli_facter_results | train | def _parse_cli_facter_results(facter_results):
'''Parse key value pairs printed with "=>" separators.
YAML is preferred output scheme for facter.
>>> list(_parse_cli_facter_results("""foo => bar
... baz => 1
... foo_bar => True"""))
[('foo', 'bar'), ('baz', '1'), ('foo_bar', 'True')]
>>> li... | python | {
"resource": ""
} |
q39179 | Facter.run_facter | train | def run_facter(self, key=None):
"""Run the facter executable with an optional specfic
fact. Output is parsed to yaml if available and
selected. Puppet facts are always selected. Returns a
dictionary if no key is given, and the value if a key is
passed."""
args = [self.fac... | python | {
"resource": ""
} |
q39180 | Facter.has_cache | train | def has_cache(self):
"""Intended to be called before any call that might access the
cache. If the cache is not selected, then returns False,
otherwise the cache is build if needed and returns True."""
if not self.cache_enabled:
return False
if self._cache is None:
... | python | {
"resource": ""
} |
q39181 | Facter.lookup | train | def lookup(self, fact, cache=True):
"""Return the value of a given fact and raise a KeyError if
it is not available. If `cache` is False, force the lookup of
the fact."""
if (not cache) or (not self.has_cache()):
val = self.run_facter(fact)
if val is None or val ... | python | {
"resource": ""
} |
q39182 | Frisbee._reset | train | def _reset(self) -> None:
"""Reset some of the state in the class for multi-searches."""
self.project: str = namesgenerator.get_random_name()
self._processed: List = list()
self.results: List = list() | python | {
"resource": ""
} |
q39183 | Frisbee._config_bootstrap | train | def _config_bootstrap(self) -> None:
"""Handle the basic setup of the tool prior to user control.
Bootstrap will load all the available modules for searching and set
them up for use by this main class.
"""
if self.output:
self.folder: str = os.getcwd() + "/" + self.p... | python | {
"resource": ""
} |
q39184 | Frisbee._dyn_loader | train | def _dyn_loader(self, module: str, kwargs: str):
"""Dynamically load a specific module instance."""
package_directory: str = os.path.dirname(os.path.abspath(__file__))
modules: str = package_directory + "/modules"
module = module + ".py"
if module not in os.listdir(modules):
... | python | {
"resource": ""
} |
q39185 | Frisbee._job_handler | train | def _job_handler(self) -> bool:
"""Process the work items."""
while True:
try:
task = self._unfullfilled.get_nowait()
except queue.Empty:
break
else:
self._log.debug("Job: %s" % str(task))
engine = self._... | python | {
"resource": ""
} |
q39186 | Frisbee._save | train | def _save(self) -> None:
"""Save output to a directory."""
self._log.info("Saving results to '%s'" % self.folder)
path: str = self.folder + "/"
for job in self.results:
if job['domain'] in self.saved:
continue
job['start_time'] = str_datetime(job['... | python | {
"resource": ""
} |
q39187 | Frisbee.search | train | def search(self, jobs: List[Dict[str, str]]) -> None:
"""Perform searches based on job orders."""
if not isinstance(jobs, list):
raise Exception("Jobs must be of type list.")
self._log.info("Project: %s" % self.project)
self._log.info("Processing jobs: %d", len(jobs))
... | python | {
"resource": ""
} |
q39188 | step_along_mag_unit_vector | train | def step_along_mag_unit_vector(x, y, z, date, direction=None, num_steps=5.,
step_size=5., scalar=1):
"""
Move along 'lines' formed by following the magnetic unit vector directions.
Moving along the field is effectively the same as a field line trace though
extended movem... | python | {
"resource": ""
} |
q39189 | add_fabfile | train | def add_fabfile():
"""
Copy the base fabfile.py to the current working directory.
"""
fabfile_src = os.path.join(PACKAGE_ROOT, 'fabfile.py')
fabfile_dest = os.path.join(os.getcwd(), 'fabfile_deployer.py')
if os.path.exists(fabfile_dest):
print "`fabfile.py` exists in the current direct... | python | {
"resource": ""
} |
q39190 | Record.delete | train | def delete(self):
"""Remove the item from the infoblox server.
:rtype: bool
:raises: AssertionError
:raises: ValueError
:raises: infoblox.exceptions.ProtocolError
"""
if not self._ref:
raise ValueError('Object has no reference id for deletion')
... | python | {
"resource": ""
} |
q39191 | Record.fetch | train | def fetch(self):
"""Attempt to fetch the object from the Infoblox device. If successful
the object will be updated and the method will return True.
:rtype: bool
:raises: infoblox.exceptions.ProtocolError
"""
LOGGER.debug('Fetching %s, %s', self._path, self._search_value... | python | {
"resource": ""
} |
q39192 | Record.save | train | def save(self):
"""Update the infoblox with new values for the specified object, or add
the values if it's a new object all together.
:raises: AssertionError
:raises: infoblox.exceptions.ProtocolError
"""
if 'save' not in self._supports:
raise AssertionError... | python | {
"resource": ""
} |
q39193 | Record._assign | train | def _assign(self, values):
"""Assign the values passed as either a dict or list to the object if
the key for each value matches an available attribute on the object.
:param dict values: The values to assign
"""
LOGGER.debug('Assigning values: %r', values)
if not values:... | python | {
"resource": ""
} |
q39194 | Record._build_search_values | train | def _build_search_values(self, kwargs):
"""Build the search criteria dictionary. It will first try and build
the values from already set attributes on the object, falling back
to the passed in kwargs.
:param dict kwargs: Values to build the dict from
:rtype: dict
"""
... | python | {
"resource": ""
} |
q39195 | Host.add_ipv4addr | train | def add_ipv4addr(self, ipv4addr):
"""Add an IPv4 address to the host.
:param str ipv4addr: The IP address to add.
:raises: ValueError
"""
for addr in self.ipv4addrs:
if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or
(isinstance(addr, H... | python | {
"resource": ""
} |
q39196 | Host.remove_ipv4addr | train | def remove_ipv4addr(self, ipv4addr):
"""Remove an IPv4 address from the host.
:param str ipv4addr: The IP address to remove
"""
for addr in self.ipv4addrs:
if ((isinstance(addr, dict) and addr['ipv4addr'] == ipv4addr) or
(isinstance(addr, HostIPv4) and addr.... | python | {
"resource": ""
} |
q39197 | Host.add_ipv6addr | train | def add_ipv6addr(self, ipv6addr):
"""Add an IPv6 address to the host.
:param str ipv6addr: The IP address to add.
:raises: ValueError
"""
for addr in self.ipv6addrs:
if ((isinstance(addr, dict) and addr['ipv6addr'] == ipv6addr) or
(isinstance(addr, H... | python | {
"resource": ""
} |
q39198 | Host.remove_ipv6addr | train | def remove_ipv6addr(self, ipv6addr):
"""Remove an IPv6 address from the host.
:param str ipv6addr: The IP address to remove
"""
for addr in self.ipv6addrs:
if ((isinstance(addr, dict) and addr['ipv6addr'] == ipv6addr) or
(isinstance(addr, HostIPv4) and addr.... | python | {
"resource": ""
} |
q39199 | SQLAlchemyProxy.autoschema | train | def autoschema(self, objects, **kwargs):
''' wrapper around utils.autoschema function '''
return autoschema(objects=objects, exclude_keys=self.RESTRICTED_KEYS,
**kwargs) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.