_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q49700 | ClusterLab.wait | train | def wait( self, timeout = -1 ):
"""Wait for all pending results to be finished. If timeout is set,
return after this many seconds regardless.
:param timeout: timeout period in seconds (defaults to forever)
:returns: True if all the results completed"""
# we can't use ipyparalle... | python | {
"resource": ""
} |
q49701 | ClusterLab._abortJobs | train | def _abortJobs( self, js ):
"""Private method to abort a set of jobs.
:param js: the job ids to be aborted"""
self.open()
self._client.abort(jobs = js)
self.close() | python | {
"resource": ""
} |
q49702 | ClusterLab.cancelPendingResultsFor | train | def cancelPendingResultsFor( self, params ):
"""Cancel any results pending for experiments at the given point
in the parameter space.
:param params: the experimental parameters"""
# grab the result job ids
jobs = self.pendingResultsFor(params)
if len(jo... | python | {
"resource": ""
} |
q49703 | ClusterLab.cancelAllPendingResults | train | def cancelAllPendingResults( self ):
"""Cancel all pending results."""
# grab all the pending job ids
jobs = self.pendingResults()
if len(jobs) > 0:
# abort in the cluster
self._abortJobs(jobs)
# cancel in the notebook ... | python | {
"resource": ""
} |
q49704 | TableFu.facet_by | train | def facet_by(self, column):
"""
Faceting creates new TableFu instances with rows matching
each possible value.
"""
faceted_spreadsheets = {}
for row in self.rows:
if row[column]:
col = row[column].value
if faceted_spreadsheets.h... | python | {
"resource": ""
} |
q49705 | TableFu.map | train | def map(self, func, *columns):
"""
Map a function to rows, or to given columns
"""
if not columns:
return map(func, self.rows)
else:
values = (self.values(column) for column in columns)
result = [map(func, v) for v in values]
if len... | python | {
"resource": ""
} |
q49706 | TableFu.csv | train | def csv(self, **kwargs):
"""
Export this table as a CSV
"""
out = StringIO()
writer = csv.DictWriter(out, self.columns, **kwargs)
writer.writerow(dict(zip(self.columns, self.columns)))
writer.writerows(dict(row.items()) for row in self.rows)
retur... | python | {
"resource": ""
} |
q49707 | TableFu.from_file | train | def from_file(fn, **options):
"""
Creates a new TableFu instance from a file or path
"""
if hasattr(fn, 'read'):
return TableFu(fn, **options)
with open(fn) as f:
return TableFu(f, **options) | python | {
"resource": ""
} |
q49708 | TableFu.from_url | train | def from_url(url, **options):
"""
Downloads the contents of a given URL and loads it
into a new TableFu instance
"""
resp = urllib2.urlopen(url)
return TableFu(resp, **options) | python | {
"resource": ""
} |
q49709 | Row.get | train | def get(self, column_name, default=None):
"""
Return the Datum for column_name, or default.
"""
if column_name in self.table.default_columns:
index = self.table.default_columns.index(column_name)
return Datum(self.cells[index], self.row_num, column_name, self.tabl... | python | {
"resource": ""
} |
q49710 | read_eigenvalues | train | def read_eigenvalues(i_filename):
"""Reads the eigenvalues from EIGENSOFT results.
:param i_filename: the name of the input file.
:type i_filename: str
:returns: a :py:class:`numpy.ndarray` array containing the eigenvalues.
"""
# The data is the first line of the result file (should begin wi... | python | {
"resource": ""
} |
q49711 | dump_json | train | def dump_json(token_dict, dump_path):
"""write json data to file
"""
if sys.version > '3':
with open(dump_path, 'w', encoding='utf-8') as output_file:
json.dump(token_dict, output_file, indent=4)
else:
with open(dump_path, 'w') as output_file:
json.dump(token_dict... | python | {
"resource": ""
} |
q49712 | parse | train | def parse():
"""parse arguments supplied by cmd-line
"""
parser = argparse.ArgumentParser(
description='BabelFy Entity Tagger',
formatter_class=argparse.RawTextHelpFormatter
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
... | python | {
"resource": ""
} |
q49713 | FIR.main | train | def main(self, x):
""" Transposed FIR structure """
self.acc[0] = x * self.TAPS[-1]
for i in range(1, len(self.acc)):
self.acc[i] = self.acc[i - 1] + x * self.TAPS[len(self.TAPS) - 1 - i]
self.out = self.acc[-1]
return self.out | python | {
"resource": ""
} |
q49714 | ClientCompat.record | train | def record(self, action, props=None, path=KISSmetrics.RECORD_PATH,
resp=False):
"""Record event for identity with any properties.
:param action: event performed
:param props: any additional data to include
:type props: dict
:param resp: indicate whether to return ... | python | {
"resource": ""
} |
q49715 | ClientCompat.set | train | def set(self, data, path=KISSmetrics.SET_PATH, resp=False):
"""Set a properties provided in `data` for identity.
:param data: key-value pairs to associate with identity
:type data: dict
:param path: endpoint path; defaults to ``KISSmetrics.SET_PATH``
:param resp: indicate whethe... | python | {
"resource": ""
} |
q49716 | ClientCompat.alias | train | def alias(self, name, alias_to, path=KISSmetrics.ALIAS_PATH, resp=False):
"""Map `name` to `alias_to`; actions done by one resolve to other.
:param name: consider as same individual as ``alias_to``
:param alias_to: consider an alias of ``name``
:param path: endpoint path; defaults to ``... | python | {
"resource": ""
} |
q49717 | PMF | train | def PMF(samples, y):
""" Compute the probability mass function.
The set of samples defines a probability density P(y),
which is computed using a kernel density estimator.
From :math:`P(y)` we define:
:math:`\mathrm{pmf}(p) = \int_{P(y)<p} P(y) dy`
This is the cumulative d... | python | {
"resource": ""
} |
q49718 | compute_pmf | train | def compute_pmf(fsamps, y, **kwargs):
""" Compute the pmf defined by fsamps at each x for each y.
Parameters
----------
fsamps: 2D array-like
array of function samples, as returned by
:func:`fgivenx.compute_samples`
y: 1D array-like
y values to evaluate the PMF at
para... | python | {
"resource": ""
} |
q49719 | weld_range | train | def weld_range(start, stop, step):
"""Create a vector for the range parameters above.
Parameters
----------
start : int
stop : int or WeldObject
Could be the lazily computed length of a WeldObject vec.
step : int
Returns
-------
WeldObject
Representation of this com... | python | {
"resource": ""
} |
q49720 | weld_compare | train | def weld_compare(array, scalar, operation, weld_type):
"""Applies comparison operation between each element in the array with scalar.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
scalar : {int, float, str, bool, bytes_}
Value to compare with; must be same ty... | python | {
"resource": ""
} |
q49721 | weld_filter | train | def weld_filter(array, weld_type, bool_array):
"""Returns a new array only with the elements with a corresponding True in bool_array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
weld_type : WeldType
Type of the elements in the input array.
bool_array : ... | python | {
"resource": ""
} |
q49722 | weld_slice | train | def weld_slice(array, weld_type, slice_, default_start=0, default_stop=0, default_step=1):
"""Returns a new array according to the given slice.
Parameters
----------
array : numpy.ndarray or WeldObject
1-dimensional array.
weld_type : WeldType
Type of the elements in the input array... | python | {
"resource": ""
} |
q49723 | weld_tail | train | def weld_tail(array, length, n):
"""Return the last n elements.
Parameters
----------
array : numpy.ndarray or WeldObject
Array to select from.
length : int or WeldObject
Length of the array. Int if already known can simplify the computation.
n : int
How many values.
... | python | {
"resource": ""
} |
q49724 | weld_array_op | train | def weld_array_op(array1, array2, result_type, operation):
"""Applies operation to each pair of elements in the arrays.
Their lengths and types are assumed to be the same.
Parameters
----------
array1 : numpy.ndarray or WeldObject
Input array.
array2 : numpy.ndarray or WeldObject
... | python | {
"resource": ""
} |
q49725 | weld_invert | train | def weld_invert(array):
"""Inverts a bool array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data. Assumed to be bool data.
Returns
-------
WeldObject
Representation of this computation.
"""
obj_id, weld_obj = create_weld_object(array)
weld... | python | {
"resource": ""
} |
q49726 | weld_iloc_int | train | def weld_iloc_int(array, index):
"""Retrieves the value at index.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data. Assumed to be bool data.
index : int
The array index from which to retrieve value.
Returns
-------
WeldObject
Representation o... | python | {
"resource": ""
} |
q49727 | weld_iloc_indices | train | def weld_iloc_indices(array, weld_type, indices):
"""Retrieve the values at indices.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data. Assumed to be bool data.
weld_type : WeldType
The WeldType of the array data.
indices : numpy.ndarray or WeldObject
... | python | {
"resource": ""
} |
q49728 | weld_iloc_indices_with_missing | train | def weld_iloc_indices_with_missing(array, weld_type, indices):
"""Retrieve the values at indices. Indices greater than array length get replaced with
a corresponding-type missing value literal.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data. Assumed to be bool data.
... | python | {
"resource": ""
} |
q49729 | weld_element_wise_op | train | def weld_element_wise_op(array, weld_type, scalar, operation):
"""Applies operation to each element in the array with scalar.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
scalar : {int, float... | python | {
"resource": ""
} |
q49730 | weld_sort | train | def weld_sort(arrays, weld_types, readable_text, ascending=True):
"""Sort the arrays.
Parameters
----------
arrays : list of (numpy.ndarray or WeldObject)
Arrays to put in a struct.
weld_types : list of WeldType
The Weld types of the arrays in the same order.
readable_text : str... | python | {
"resource": ""
} |
q49731 | weld_replace | train | def weld_replace(array, weld_type, this, to):
"""Replaces 'this' values to 'to' value.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of the data in the array.
this : {int, float, str, bool, bytes}
Scalar to replace.
... | python | {
"resource": ""
} |
q49732 | weld_udf | train | def weld_udf(weld_template, mapping):
"""Create WeldObject to encode weld_template code given mapping.
Parameters
----------
weld_template : str
Weld code to encode.
mapping : dict
Which substitutions to make in the weld_template.
Returns
-------
WeldObject
Repr... | python | {
"resource": ""
} |
q49733 | option_parser | train | def option_parser():
"""Option Parser to give various options."""
usage = '''
$ ./crawler -d5 <url>
Here in this case it goes till depth of 5 and url is target URL to
start crawling.
'''
version = "2.0.0"
parser = optparse.OptionParser(usage=usag... | python | {
"resource": ""
} |
q49734 | getlinks | train | async def getlinks(url):
"""Get Links from the Linkfetcher class."""
page = Linkfetcher(url)
await page.linkfetch()
for i, url in enumerate(page):
return (i, url) | python | {
"resource": ""
} |
q49735 | main | train | async def main():
""" Main class."""
opts, args = option_parser()
url = args[0]
if opts.links:
getlinks(url)
raise SystemExit(0)
depth = opts.depth
sTime = time.time()
webcrawler = Webcrawler(url, depth)
webcrawler.crawl()
eTime = time.time()
tTime = eTime - sT... | python | {
"resource": ""
} |
q49736 | _get_mapping | train | def _get_mapping():
"""
Finds and loads gulp's rev-manifest.json file.
In default, this is looking for rev-manifest.json file places in your
STATIC_ROOT. Can be overriden to a specific location by setting
DJANGO_GULP_REV_PATH.
"""
global _STATIC_MAPPING
if _STATIC_MAPPING is None:
... | python | {
"resource": ""
} |
q49737 | static_rev | train | def static_rev(path):
"""
Gets a joined path with the STATIC_URL setting, and applies revisioning
depending on DEBUG setting.
Usage::
{% load rev %}
{% static_rev "css/base.css" %}
Example::
{% static_rev "css/base.css" %}
On DEBUG=True will return: /static/css/base... | python | {
"resource": ""
} |
q49738 | RDDL._build_object_table | train | def _build_object_table(self):
'''Builds the object table for each RDDL type.'''
types = self.domain.types
objects = dict(self.non_fluents.objects)
self.object_table = dict()
for name, value in self.domain.types:
if value == 'object':
objs = objects[na... | python | {
"resource": ""
} |
q49739 | RDDL._build_fluent_table | train | def _build_fluent_table(self):
'''Builds the fluent table for each RDDL pvariable.'''
self.fluent_table = collections.OrderedDict()
for name, size in zip(self.domain.non_fluent_ordering, self.non_fluent_size):
non_fluent = self.domain.non_fluents[name]
self.fluent_table[... | python | {
"resource": ""
} |
q49740 | RDDL.non_fluent_variables | train | def non_fluent_variables(self) -> FluentParamsList:
'''Returns the instantiated non-fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
'''
fluents = self... | python | {
"resource": ""
} |
q49741 | RDDL.state_fluent_variables | train | def state_fluent_variables(self) -> FluentParamsList:
'''Returns the instantiated state fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
'''
fluents = ... | python | {
"resource": ""
} |
q49742 | RDDL.interm_fluent_variables | train | def interm_fluent_variables(self) -> FluentParamsList:
'''Returns the instantiated intermediate fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
'''
fl... | python | {
"resource": ""
} |
q49743 | RDDL.action_fluent_variables | train | def action_fluent_variables(self) -> FluentParamsList:
'''Returns the instantiated action fluents in canonical order.
Returns:
Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name
and a list of instantiated fluents represented as strings.
'''
fluents ... | python | {
"resource": ""
} |
q49744 | RDDL.non_fluent_size | train | def non_fluent_size(self) -> Sequence[Sequence[int]]:
'''The size of each non-fluent in canonical order.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each non-fluent.
'''
fluents = self.domain.non_fluents
... | python | {
"resource": ""
} |
q49745 | RDDL.state_size | train | def state_size(self) -> Sequence[Sequence[int]]:
'''The size of each state fluent in canonical order.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each fluent.
'''
fluents = self.domain.state_fluents
or... | python | {
"resource": ""
} |
q49746 | RDDL.action_size | train | def action_size(self) -> Sequence[Sequence[int]]:
'''The size of each action fluent in canonical order.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each fluent.
'''
fluents = self.domain.action_fluents
... | python | {
"resource": ""
} |
q49747 | RDDL.interm_size | train | def interm_size(self)-> Sequence[Sequence[int]]:
'''The size of each intermediate fluent in canonical order.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each fluent.
'''
fluents = self.domain.intermediate_flue... | python | {
"resource": ""
} |
q49748 | RDDL.state_range_type | train | def state_range_type(self) -> Sequence[str]:
'''The range type of each state fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
'''
fluents = self.domain.state_fluents
ordering = self.domain.st... | python | {
"resource": ""
} |
q49749 | RDDL.action_range_type | train | def action_range_type(self) -> Sequence[str]:
'''The range type of each action fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
'''
fluents = self.domain.action_fluents
ordering = self.domain... | python | {
"resource": ""
} |
q49750 | RDDL.interm_range_type | train | def interm_range_type(self) -> Sequence[str]:
'''The range type of each intermediate fluent in canonical order.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
'''
fluents = self.domain.intermediate_fluents
ordering =... | python | {
"resource": ""
} |
q49751 | RDDL._fluent_range_type | train | def _fluent_range_type(cls, fluents, ordering) -> Sequence[str]:
'''Returns the range types of `fluents` following the given `ordering`.
Returns:
Sequence[str]: A tuple of range types representing
the range of each fluent.
'''
range_types = []
for name in... | python | {
"resource": ""
} |
q49752 | RDDL._fluent_params | train | def _fluent_params(self, fluents, ordering) -> FluentParamsList:
'''Returns the instantiated `fluents` for the given `ordering`.
For each fluent in `fluents`, it instantiates each parameter
type w.r.t. the contents of the object table.
Returns:
Sequence[Tuple[str, List[str]... | python | {
"resource": ""
} |
q49753 | RDDL._fluent_size | train | def _fluent_size(self, fluents, ordering) -> Sequence[Sequence[int]]:
'''Returns the sizes of `fluents` following the given `ordering`.
Returns:
Sequence[Sequence[int]]: A tuple of tuple of integers
representing the shape and size of each fluent.
'''
shapes = []
... | python | {
"resource": ""
} |
q49754 | RDDL._param_types_to_shape | train | def _param_types_to_shape(self, param_types: Optional[str]) -> Sequence[int]:
'''Returns the fluent shape given its `param_types`.'''
param_types = [] if param_types is None else param_types
shape = tuple(self.object_table[ptype]['size'] for ptype in param_types)
return shape | python | {
"resource": ""
} |
q49755 | base_ctx | train | def base_ctx(ctx):
"""Get base ctx.
:param ctx: initial ctx.
:return: base ctx."""
result = None
if isclass(ctx):
result = getattr(ctx, '__base__', None)
if result is None:
mro = getmro(ctx)
if len(mro) > 1:
result = mro[1]
else:
... | python | {
"resource": ""
} |
q49756 | super_method | train | def super_method(name, ctx):
"""Get super ctx method and ctx where name matches with input name.
:param name: method name to find in super ctx.
:param ctx: initial method ctx.
:return: method in super ctx and super ctx.
:rtype: tuple"""
result = None, None
# get class ctx
if isclass(c... | python | {
"resource": ""
} |
q49757 | _apply_interception | train | def _apply_interception(
target, interception_fn, ctx=None, _globals=None
):
"""Apply interception on input target and return the final target.
:param Callable target: target on applying the interception_fn.
:param function interception_fn: interception function to apply on
target
:para... | python | {
"resource": ""
} |
q49758 | _unapply_interception | train | def _unapply_interception(target, ctx=None):
"""Unapply interception on input target in cleaning it.
:param routine target: target from where removing an interception
function. is_joinpoint(target) must be True.
:param ctx: target ctx.
"""
# try to get the right ctx
if ctx is None:
... | python | {
"resource": ""
} |
q49759 | is_intercepted | train | def is_intercepted(target):
"""True iif input target is intercepted.
:param target: target to check such as an intercepted target.
:return: True iif input target is intercepted.
:rtype: bool
"""
result = False
# get interception function from input target
function = _get_function(tar... | python | {
"resource": ""
} |
q49760 | get_intercepted | train | def get_intercepted(target):
"""Get intercepted function and ctx from input target.
:param target: target from where getting the intercepted function and ctx.
:return: target intercepted function and ctx.
(None, None) if no intercepted function exist.
(fn, None) if not ctx exists.
:rty... | python | {
"resource": ""
} |
q49761 | _get_function | train | def _get_function(target):
"""Get target function.
:param callable target: target from where get function.
:return: depending on target type::
- class: constructor.
- method: method function.
- function: function.
- else: __call__ method.
:raises: TypeError if target ... | python | {
"resource": ""
} |
q49762 | Joinpoint.set_target | train | def set_target(self, target, ctx=None):
"""Set target.
:param target: new target to use.
:param target ctx: target ctx if target is an class/instance attribute.
"""
if target is not None:
# check if target is already intercepted
if is_intercepted(target)... | python | {
"resource": ""
} |
q49763 | Joinpoint.start | train | def start(
self, target=None, args=None, kwargs=None, advices=None,
exec_ctx=None, ctx=None
):
""" Start to proceed this Joinpoint in initializing target, its
arguments and advices. Call self.proceed at the end.
:param callable target: new target to use in proceeding... | python | {
"resource": ""
} |
q49764 | Joinpoint.proceed | train | def proceed(self):
"""Proceed this Joinpoint in calling all advices with this joinpoint
as the only one parameter, and call at the end the target.
"""
try:
# get next advice
advice = next(self._advices_iterator)
except StopIteration: # if no advice can ... | python | {
"resource": ""
} |
q49765 | PyVDF.formatData | train | def formatData(data):
"""
Format a dictionary object to look like a VDF file
:param data: Data
:type data: :py:obj:`dict`
:returns: A vdf string representation of data
"""
condensed = PyVDF.__CondensedOutput
indentation = PyVDF.__OutputIndentation
spacing = PyVDF.__OutputSpacing
... | python | {
"resource": ""
} |
q49766 | PyVDF.writeData | train | def writeData(f, data):
"""
Write a dictionary object to a file
:param f: The file to write to
:type f: file/string
:param data: The data to write to the file
:type data: dict
"""
if not isinstance(data, dict):
raise Exception(PyVDF.__ERR_NotDict.format(repr(data)))
data = PyV... | python | {
"resource": ""
} |
q49767 | PyVDF.find | train | def find(self, path):
"""
Find a value
:param path: The Key path to search for
:type path: :py:obj:`str`
:returns: The found value or an empty string if not found.
"""
p = [re.sub('[\[\]]', '', w) for w in PyVDF.__RE_Path_Seperator.findall(path)]
array = self.getData()
for c in p:
... | python | {
"resource": ""
} |
q49768 | PyVDF.edit | train | def edit(self, path, value):
"""
Edit a key value
:param path: The path key for the value
:type path: :py:obj:`str`
:param value: The value to be set
:type value: :py:obj:`str`
"""
_dict = PyVDF.__UseDict
p = [re.sub('[\[\]]', '', w) for w in PyVDF.__RE_Path_Seperator.findall(path)]... | python | {
"resource": ""
} |
q49769 | split_line | train | def split_line(what, indent='', cols=79):
"""Split a line on the closest space, or break the last word with '-'.
Args:
what(str): text to spli one line of.
indent(str): will prepend this indent to the split line, taking it into
account in the column count.
cols(int): maximum len... | python | {
"resource": ""
} |
q49770 | fit_to_cols | train | def fit_to_cols(what, indent='', cols=79):
"""Wrap the given text to the columns, prepending the indent to each line.
Args:
what(str): text to wrap.
indent(str): indentation to use.
cols(int): colt to wrap to.
Returns:
str: Wrapped text
"""
lines = []
while what... | python | {
"resource": ""
} |
q49771 | CaptchaField.compress | train | def compress(self, data_list):
"""Validates the captcha answer and returns the result
If no data is provided, this method will simply return None. Otherwise,
it will validate that the provided answer and timestamp hash to the
supplied hash value, and that the timestamp is within the con... | python | {
"resource": ""
} |
q49772 | create_query | train | def create_query(key, person, event=None, timestamp=None,
identity=None, properties=None):
"""Build and encode query string.
:param key: API key for product, found on the
"KISSmetrics Settings".
:param person: individual performing `event`
:param event: event name that ... | python | {
"resource": ""
} |
q49773 | Cache.check | train | def check(self, *args):
""" Check that the arguments haven't changed since the last call.
Parameters
----------
*args:
All but the last argument are inputs to the cached function. The
last is the actual value of the function.
Returns
-------
... | python | {
"resource": ""
} |
q49774 | Cache.load | train | def load(self):
""" Load cache from file using pickle. """
try:
with open(self.file_root + '.pkl', "rb") as f:
return pickle.load(f)
except IOError:
raise CacheMissing(self.file_root) | python | {
"resource": ""
} |
q49775 | Cache.save | train | def save(self, *args):
""" Save cache to file using pickle.
Parameters
----------
*args:
All but the last argument are inputs to the cached function. The
last is the actual value of the function.
"""
with open(self.file_root + '.pkl', "wb") as f:
... | python | {
"resource": ""
} |
q49776 | main | train | def main(req_port=None, res_port=None, use_security=False):
'''main of queue
:param req_port: port for clients
:param res_port: port for servers
'''
if req_port is None:
req_port = env.get_req_port()
if res_port is None:
res_port = env.get_res_port()
auth = None
try:
... | python | {
"resource": ""
} |
q49777 | TroveboxObject._set_fields | train | def _set_fields(self, json_dict):
""" Set this object's attributes specified in json_dict """
for key, value in json_dict.items():
if not key.startswith("_"):
setattr(self, key, value) | python | {
"resource": ""
} |
q49778 | TroveboxObject._replace_fields | train | def _replace_fields(self, json_dict):
"""
Delete this object's attributes, and replace with
those in json_dict.
"""
for key in self._json_dict.keys():
if not key.startswith("_"):
delattr(self, key)
self._json_dict = json_dict
self._set_... | python | {
"resource": ""
} |
q49779 | TroveboxObject._delete_fields | train | def _delete_fields(self):
"""
Delete this object's attributes, including name and id
"""
for key in self._json_dict.keys():
if not key.startswith("_"):
delattr(self, key)
self._json_dict = {}
self.id = None
self.name = None | python | {
"resource": ""
} |
q49780 | ABCMeta.register | train | def register(cls, subclass):
"""Register a virtual subclass of an ABC."""
if not isinstance(cls, type):
raise TypeError("Can only register classes")
if issubclass(subclass, cls):
return # Already a subclass
# Subtle: test for cycles *after* testing for "already a... | python | {
"resource": ""
} |
q49781 | main | train | def main(pub_port=None, sub_port=None):
'''main of forwarder
:param sub_port: port for subscribers
:param pub_port: port for publishers
'''
try:
if sub_port is None:
sub_port = get_sub_port()
if pub_port is None:
pub_port = get_pub_port()
context = zm... | python | {
"resource": ""
} |
q49782 | trackrApiInterface.update_state_from_api | train | def update_state_from_api(self):
"""
Pull and update the current state from the API.
"""
if self.last_api_call is not None:
difference = (datetime.datetime.now() - self.last_api_call).seconds
else:
# This is the first run, so we need to get the lastest sta... | python | {
"resource": ""
} |
q49783 | trackrApiInterface.authenticate | train | def authenticate(self, reauth=False):
"""
Authenticate with the API and return an authentication token.
"""
auth_url = BASE_URL + "/rest/user"
payload = {'email': self.email, 'password': self.password}
arequest = requests.get(auth_url, params=payload)
status = are... | python | {
"resource": ""
} |
q49784 | trackrApiInterface.get_trackrs | train | def get_trackrs(self):
"""
Extract each Trackr device from the trackrApiInterface state.
return a list of all Trackr objects from account.
"""
trackrs = []
for trackr in self.state:
trackrs.append(trackrDevice(trackr, self))
return trackrs | python | {
"resource": ""
} |
q49785 | check_python_version | train | def check_python_version():
"""Checks the python version, exists if != 2.7."""
python_major, python_minor = sys.version_info[:2]
if python_major != 2 or python_minor != 7:
sys.stderr.write("pyGenClean requires python 2.7")
sys.exit(1) | python | {
"resource": ""
} |
q49786 | MultiIndex.evaluate | train | def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
"""Evaluates by creating a MultiIndex containing evaluated data and index.
See `LazyResult`
Returns
-------
MultiIndex
MultiIndex with evaluated data.
"""
... | python | {
"resource": ""
} |
q49787 | MultiIndex.tail | train | def tail(self, n=5):
"""Return MultiIndex with the last n values in each column.
Parameters
----------
n : int
Number of values.
Returns
-------
MultiIndex
MultiIndex containing the last n values in each column.
"""
# not... | python | {
"resource": ""
} |
q49788 | MultiIndex.dropna | train | def dropna(self):
"""Returns MultiIndex without any rows containing null values according to Baloo's convention.
Returns
-------
MultiIndex
MultiIndex with no null values.
"""
not_nas = [v.notna() for v in self.values]
and_filter = reduce(lambda x, y... | python | {
"resource": ""
} |
q49789 | MultiIndex.from_pandas | train | def from_pandas(cls, index):
"""Create baloo MultiIndex from pandas MultiIndex.
Parameters
----------
index : pandas.multi.MultiIndex
Returns
-------
MultiIndex
"""
from pandas import MultiIndex as PandasMultiIndex
check_type(index, Pand... | python | {
"resource": ""
} |
q49790 | MultiIndex.to_pandas | train | def to_pandas(self):
"""Convert to pandas MultiIndex.
Returns
-------
pandas.base.MultiIndex
"""
if not all(ind.is_raw() for ind in self.values):
raise ValueError('Cannot convert to pandas MultiIndex if not evaluated.')
from pandas import MultiIndex... | python | {
"resource": ""
} |
q49791 | parallel_apply | train | def parallel_apply(f, array, **kwargs):
""" Apply a function to an array with openmp parallelisation.
Equivalent to `[f(x) for x in array]`, but parallelised if required.
Parameters
----------
f: function
Univariate function to apply to each element of array
array: array-like
... | python | {
"resource": ""
} |
q49792 | SplitMiddleware._copy_body_to_tempfile | train | def _copy_body_to_tempfile(cls, environ):
"""
Copy wsgi.input to a tempfile so it can be reused.
"""
try:
length = int(environ.get('CONTENT_LENGTH', 0))
except ValueError:
length = 0
try:
fileobj = tempfile.SpooledTemporaryFile(1024*10... | python | {
"resource": ""
} |
q49793 | find_by_name | train | def find_by_name(collection, name, exact=True):
"""
Searches collection by resource name.
:param rightscale.ResourceCollection collection: The collection in which to
look for :attr:`name`.
:param str name: The name to look for in collection.
:param bool exact: A RightScale ``index`` searc... | python | {
"resource": ""
} |
q49794 | annotate_diamond | train | def annotate_diamond(records, diamond_path):
'''
Retrieve scientific names and lineages for taxon IDs in Diamond output
Returns taxonomically annotated SeqRecords with modified description attributes
'''
contigs_metadata = {}
with open(diamond_path) as diamond_tax_fh:
for line in diamond... | python | {
"resource": ""
} |
q49795 | matrix | train | def matrix(records, scafstats_path):
'''
Generate taxonomic count matrix from BBMap scafstats output to tictax classified contigs
'''
ncbi = ete3.NCBITaxa()
# # Single file version
# contigs_lineages = {r.id: r.description.strip().partition(' ')[2].split('|')[2] for r in records}
# df ... | python | {
"resource": ""
} |
q49796 | build_slide | train | def build_slide(filename: Path, pptx_template: Path, master_slide_idx: int, slide_layout_idx: int, font_size: int,
dst_dir: Path, font_name: str, slide_txt_alignment: str = "left") -> Path:
"""Builds a powerpoint presentation using data read from a yaml file
:param filename: path to the yaml fi... | python | {
"resource": ""
} |
q49797 | pick_master_slide | train | def pick_master_slide(master_slides_path: Path) -> Path:
"""Returns path to a master slide. If argument is a directory,
returns a randomly chosen file in the directory and if argument
is a file, returns the argument itself
:return: path to chosen master slide
"""
if master_slides_path.is_file(... | python | {
"resource": ""
} |
q49798 | validate_yaml_file | train | def validate_yaml_file(schema: dict, yaml_file: Path):
"""Validates yaml data against the defined schema
:param schema: schema in json format
:param yaml_file: path to yaml_file
:return:
"""
with yaml_file.open() as f:
data = yaml.load(f)
jsonschema.validate(data, schema) | python | {
"resource": ""
} |
q49799 | cli | train | def cli(yaml_paths, pptx_template_path, font_size, master_slide_idx, slide_layout_idx, dst_dir, font_name,
slide_txt_alignment, validate):
"""
A powerpoint builder
https://github.com/sukujgrg/pptx-builder-from-yaml
"""
dst_dir = Path(dst_dir)
pptx_template_path = Path(pptx_template_p... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.