_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q34600 | _reldiff | train | def _reldiff(a, b):
"""
Computes the relative difference of two floating-point numbers
rel = abs(a-b)/min(abs(a), abs(b))
If a == 0 and b == 0, then 0.0 is returned
Otherwise if a or b is 0.0, inf is returned.
"""
a = float(a)
b = float(b)
aa = abs(a)
ba = abs(b)
if a == ... | python | {
"resource": ""
} |
q34601 | _compare_keys | train | def _compare_keys(element1, element2, key, compare_func, *args):
"""
Compares a specific key between two elements of a basis set
If the key exists in one element but not the other, False is returned.
If the key exists in neither element, True is returned.
Parameters
----------
element1 : ... | python | {
"resource": ""
} |
q34602 | electron_shells_are_subset | train | def electron_shells_are_subset(subset, superset, compare_meta=False, rel_tol=0.0):
'''
Determine if a list of electron shells is a subset of another
If 'subset' is a subset of the 'superset', True is returned.
The shells are compared approximately (exponents/coefficients are
within a tolerance)
... | python | {
"resource": ""
} |
q34603 | ecp_pots_are_subset | train | def ecp_pots_are_subset(subset, superset, compare_meta=False, rel_tol=0.0):
'''
Determine if a list of ecp potentials is a subset of another
If 'subset' is a subset of the 'superset', True is returned.
The potentials are compared approximately (exponents/coefficients are
within a tolerance)
... | python | {
"resource": ""
} |
q34604 | compare_elements | train | def compare_elements(element1,
element2,
compare_electron_shells_meta=False,
compare_ecp_pots_meta=False,
compare_meta=False,
rel_tol=0.0):
'''
Determine if the basis information for two elements is the same... | python | {
"resource": ""
} |
q34605 | compare_basis | train | def compare_basis(bs1,
bs2,
compare_electron_shells_meta=False,
compare_ecp_pots_meta=False,
compare_elements_meta=False,
compare_meta=False,
rel_tol=0.0):
'''
Determine if two basis set dictionaries are ... | python | {
"resource": ""
} |
q34606 | create_metadata_file | train | def create_metadata_file(output_path, data_dir):
'''Creates a METADATA.json file from a data directory
The file is written to output_path
'''
# Relative path to all (BASIS).metadata.json files
meta_filelist, table_filelist, _, _ = get_all_filelist(data_dir)
metadata = {}
for meta_file_rel... | python | {
"resource": ""
} |
q34607 | write_txt | train | def write_txt(refs):
'''Converts references to plain text format
'''
full_str = '\n'
lib_citation_desc, lib_citations = get_library_citation()
# Add the refs for the libarary at the top
full_str += '*' * 80 + '\n'
full_str += lib_citation_desc
full_str += '*' * 80 + '\n'
for r in l... | python | {
"resource": ""
} |
q34608 | diff_basis_dict | train | def diff_basis_dict(left_list, right_list):
'''
Compute the difference between two sets of basis set dictionaries
The result is a list of dictionaries that correspond to each dictionary in
`left_list`. Each resulting dictionary will contain only the elements/shells
that exist in that entry and not ... | python | {
"resource": ""
} |
q34609 | diff_json_files | train | def diff_json_files(left_files, right_files):
'''
Compute the difference between two sets of basis set JSON files
The output is a set of files that correspond to each file in
`left_files`. Each resulting dictionary will contain only the elements/shells
that exist in that entry and not in any of the... | python | {
"resource": ""
} |
q34610 | shells_difference | train | def shells_difference(s1, s2):
"""
Computes and prints the differences between two lists of shells
If the shells contain a different number primitives,
or the lists are of different length, inf is returned.
Otherwise, the maximum relative difference is returned.
"""
max_rdiff = 0.0
nsh... | python | {
"resource": ""
} |
q34611 | potentials_difference | train | def potentials_difference(p1, p2):
"""
Computes and prints the differences between two lists of potentials
If the shells contain a different number primitives,
or the lists are of different length, inf is returned.
Otherwise, the maximum relative difference is returned.
"""
max_rdiff = 0.0... | python | {
"resource": ""
} |
q34612 | basis_comparison_report | train | def basis_comparison_report(bs1, bs2, uncontract_general=False):
'''
Compares two basis set dictionaries and prints a report about their differences
'''
all_bs1 = list(bs1['elements'].keys())
if uncontract_general:
bs1 = manip.uncontract_general(bs1)
bs2 = manip.uncontract_general(... | python | {
"resource": ""
} |
q34613 | compare_basis_against_file | train | def compare_basis_against_file(basis_name,
src_filepath,
file_type=None,
version=None,
uncontract_general=False,
data_dir=None):
'''Compare a basis set in the BS... | python | {
"resource": ""
} |
q34614 | _bse_cli_list_basis_sets | train | def _bse_cli_list_basis_sets(args):
'''Handles the list-basis-sets subcommand'''
metadata = api.filter_basis_sets(args.substr, args.family, args.role, args.data_dir)
if args.no_description:
liststr = metadata.keys()
else:
liststr = format_columns([(k, v['description']) for k, v in metad... | python | {
"resource": ""
} |
q34615 | _bse_cli_list_formats | train | def _bse_cli_list_formats(args):
'''Handles the list-formats subcommand'''
all_formats = api.get_formats()
if args.no_description:
liststr = all_formats.keys()
else:
liststr = format_columns(all_formats.items())
return '\n'.join(liststr) | python | {
"resource": ""
} |
q34616 | _bse_cli_list_ref_formats | train | def _bse_cli_list_ref_formats(args):
'''Handles the list-ref-formats subcommand'''
all_refformats = api.get_reference_formats()
if args.no_description:
liststr = all_refformats.keys()
else:
liststr = format_columns(all_refformats.items())
return '\n'.join(liststr) | python | {
"resource": ""
} |
q34617 | _bse_cli_list_roles | train | def _bse_cli_list_roles(args):
'''Handles the list-roles subcommand'''
all_roles = api.get_roles()
if args.no_description:
liststr = all_roles.keys()
else:
liststr = format_columns(all_roles.items())
return '\n'.join(liststr) | python | {
"resource": ""
} |
q34618 | _bse_cli_lookup_by_role | train | def _bse_cli_lookup_by_role(args):
'''Handles the lookup-by-role subcommand'''
return api.lookup_basis_by_role(args.basis, args.role, args.data_dir) | python | {
"resource": ""
} |
q34619 | _bse_cli_get_basis | train | def _bse_cli_get_basis(args):
'''Handles the get-basis subcommand'''
return api.get_basis(
name=args.basis,
elements=args.elements,
version=args.version,
fmt=args.fmt,
uncontract_general=args.unc_gen,
uncontract_spdf=args.unc_spdf,
uncontract_segmented=ar... | python | {
"resource": ""
} |
q34620 | _bse_cli_get_refs | train | def _bse_cli_get_refs(args):
'''Handles the get-refs subcommand'''
return api.get_references(
basis_name=args.basis, elements=args.elements, version=args.version, fmt=args.reffmt, data_dir=args.data_dir) | python | {
"resource": ""
} |
q34621 | _bse_cli_get_info | train | def _bse_cli_get_info(args):
'''Handles the get-info subcommand'''
bs_meta = api.get_metadata(args.data_dir)[args.basis]
ret = []
ret.append('-' * 80)
ret.append(args.basis)
ret.append('-' * 80)
ret.append(' Display Name: ' + bs_meta['display_name'])
ret.append(' Description: ' +... | python | {
"resource": ""
} |
q34622 | _bse_cli_get_versions | train | def _bse_cli_get_versions(args):
'''Handles the get-versions subcommand'''
name = args.basis.lower()
metadata = api.get_metadata(args.data_dir)
if not name in metadata:
raise KeyError(
"Basis set {} does not exist. For a complete list of basis sets, use the 'list-basis-sets' command"... | python | {
"resource": ""
} |
q34623 | _bse_cli_create_bundle | train | def _bse_cli_create_bundle(args):
'''Handles the create-bundle subcommand'''
bundle.create_bundle(args.bundle_file, args.fmt, args.reffmt, args.archive_type, args.data_dir)
return "Created " + args.bundle_file | python | {
"resource": ""
} |
q34624 | Client.wait_ready | train | def wait_ready(self, timeout=120):
"""
wait until WDA back to normal
Returns:
bool (if wda works)
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
self.status()
return True
except:... | python | {
"resource": ""
} |
q34625 | Client.screenshot | train | def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
... | python | {
"resource": ""
} |
q34626 | Session.tap_hold | train | def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
... | python | {
"resource": ""
} |
q34627 | Session.screenshot | train | def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(b... | python | {
"resource": ""
} |
q34628 | Session.send_keys | train | def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value}) | python | {
"resource": ""
} |
q34629 | Selector.click_exists | train | def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
re... | python | {
"resource": ""
} |
q34630 | _GraphDataFilter.get_graph_data | train | def get_graph_data(self, graph, benchmark):
"""
Iterator over graph data sets
Yields
------
param_idx
Flat index to parameter permutations for parameterized benchmarks.
None if benchmark is not parameterized.
entry_name
Name for the da... | python | {
"resource": ""
} |
q34631 | _GraphDataFilter._get_start_revision | train | def _get_start_revision(self, graph, benchmark, entry_name):
"""
Compute the first revision allowed by asv.conf.json.
Revisions correspond to linearized commit history and the
regression detection runs on this order --- the starting commit
thus corresponds to a specific starting... | python | {
"resource": ""
} |
q34632 | _GraphDataFilter._get_threshold | train | def _get_threshold(self, graph, benchmark, entry_name):
"""
Compute the regression threshold in asv.conf.json.
"""
if graph.params.get('branch'):
branch_suffix = '@' + graph.params.get('branch')
else:
branch_suffix = ''
max_threshold = None
... | python | {
"resource": ""
} |
q34633 | sdist_checked.__check_submodules | train | def __check_submodules(self):
"""
Verify that the submodules are checked out and clean.
"""
if not os.path.exists('.git'):
return
with open('.gitmodules') as f:
for l in f:
if 'path' in l:
p = l.split('=')[-1].strip()
... | python | {
"resource": ""
} |
q34634 | solve_potts_autogamma | train | def solve_potts_autogamma(y, w, beta=None, **kw):
"""Solve Potts problem with automatically determined gamma.
The optimal value is determined by minimizing the information measure::
f(gamma) = beta J(x(gamma)) + log sum(abs(x(gamma) - y)**p)
where x(gamma) is the solution to the Potts problem for... | python | {
"resource": ""
} |
q34635 | merge_pieces | train | def merge_pieces(gamma, right, values, dists, mu_dist, max_size):
"""
Combine consecutive intervals in Potts model solution, if doing
that reduces the cost function.
"""
mu, dist = mu_dist.mu, mu_dist.dist
right = list(right)
# Combine consecutive intervals, if it results to decrease of co... | python | {
"resource": ""
} |
q34636 | weighted_median | train | def weighted_median(y, w):
"""
Compute weighted median of `y` with weights `w`.
"""
items = sorted(zip(y, w))
midpoint = sum(w) / 2
yvals = []
wsum = 0
for yy, ww in items:
wsum += ww
if wsum > midpoint:
yvals.append(yy)
break
elif wsum =... | python | {
"resource": ""
} |
q34637 | Virtualenv._find_python | train | def _find_python(python):
"""Find Python executable for the given Python version"""
is_pypy = python.startswith("pypy")
# Parse python specifier
if is_pypy:
executable = python
if python == 'pypy':
python_version = '2'
else:
... | python | {
"resource": ""
} |
q34638 | Virtualenv.name | train | def name(self):
"""
Get a name to uniquely identify this environment.
"""
python = self._python
if self._python.startswith('pypy'):
# get_env_name adds py-prefix
python = python[2:]
return environment.get_env_name(self.tool_name, python, self._requ... | python | {
"resource": ""
} |
q34639 | Virtualenv._setup | train | def _setup(self):
"""
Setup the environment on disk using virtualenv.
Then, all of the requirements are installed into
it using `pip install`.
"""
log.info("Creating virtualenv for {0}".format(self.name))
util.check_call([
sys.executable,
"... | python | {
"resource": ""
} |
q34640 | _basicsize | train | def _basicsize(t, base=0, heap=False, obj=None):
'''Get non-zero basicsize of type,
including the header sizes.
'''
s = max(getattr(t, '__basicsize__', 0), base)
# include gc header size
if t != _Type_type:
h = getattr(t, '__flags__', 0) & _Py_TPFLAGS_HAVE_GC
elif heap: # type,... | python | {
"resource": ""
} |
q34641 | _derive_typedef | train | def _derive_typedef(typ):
'''Return single, existing super type typedef or None.
'''
v = [v for v in _values(_typedefs) if _issubclass(typ, v.type)]
if len(v) == 1:
return v[0]
return None | python | {
"resource": ""
} |
q34642 | _infer_dict | train | def _infer_dict(obj):
'''Return True for likely dict object.
'''
for ats in (('__len__', 'get', 'has_key', 'items', 'keys', 'values'),
('__len__', 'get', 'has_key', 'iteritems', 'iterkeys', 'itervalues')):
for a in ats: # no all(<generator_expression>) in Python 2.2
... | python | {
"resource": ""
} |
q34643 | _isdictclass | train | def _isdictclass(obj):
'''Return True for known dict objects.
'''
c = getattr(obj, '__class__', None)
return c and c.__name__ in _dict_classes.get(c.__module__, ()) | python | {
"resource": ""
} |
q34644 | _lengstr | train | def _lengstr(obj):
'''Object length as a string.
'''
n = leng(obj)
if n is None: # no len
r = ''
elif n > _len(obj): # extended
r = ' leng %d!' % n
else:
r = ' leng %d' % n
return r | python | {
"resource": ""
} |
q34645 | _objs_opts | train | def _objs_opts(objs, all=None, **opts):
'''Return given or 'all' objects
and the remaining options.
'''
if objs: # given objects
t = objs
elif all in (False, None):
t = ()
elif all is True: # 'all' objects ...
# ... modules first, globals and stack
# (may c... | python | {
"resource": ""
} |
q34646 | _p100 | train | def _p100(part, total, prec=1):
'''Return percentage as string.
'''
r = float(total)
if r:
r = part * 100.0 / r
return '%.*f%%' % (prec, r)
return 'n/a' | python | {
"resource": ""
} |
q34647 | _printf | train | def _printf(fmt, *args, **print3opts):
'''Formatted print.
'''
if print3opts: # like Python 3.0
f = print3opts.get('file', None) or sys.stdout
if args:
f.write(fmt % args)
else:
f.write(fmt)
f.write(print3opts.get('end', linesep))
elif args:
... | python | {
"resource": ""
} |
q34648 | _refs | train | def _refs(obj, named, *ats, **kwds):
'''Return specific attribute objects of an object.
'''
if named:
for a in ats: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _NamedRef(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(... | python | {
"resource": ""
} |
q34649 | _SI | train | def _SI(size, K=1024, i='i'):
'''Return size as SI string.
'''
if 1 < K < size:
f = float(size)
for si in iter('KMGPTE'):
f /= K
if f < K:
return ' or %.1f %s%sB' % (f, si, i)
return '' | python | {
"resource": ""
} |
q34650 | _module_refs | train | def _module_refs(obj, named):
'''Return specific referents of a module object.
'''
# ignore this very module
if obj.__name__ == __name__:
return ()
# module is essentially a dict
return _dict_refs(obj.__dict__, named) | python | {
"resource": ""
} |
q34651 | _len_frame | train | def _len_frame(obj):
'''Length of a frame object.
'''
c = getattr(obj, 'f_code', None)
if c:
n = _len_code(c)
else:
n = 0
return n | python | {
"resource": ""
} |
q34652 | _len_slice | train | def _len_slice(obj):
'''Slice length.
'''
try:
return ((obj.stop - obj.start + 1) // obj.step)
except (AttributeError, TypeError):
return 0 | python | {
"resource": ""
} |
q34653 | _claskey | train | def _claskey(obj, style):
'''Wrap an old- or new-style class object.
'''
i = id(obj)
k = _claskeys.get(i, None)
if not k:
_claskeys[i] = k = _Claskey(obj, style)
return k | python | {
"resource": ""
} |
q34654 | _typedef_both | train | def _typedef_both(t, base=0, item=0, leng=None, refs=None, kind=_kind_static, heap=False):
'''Add new typedef for both data and code.
'''
v = _Typedef(base=_basicsize(t, base=base), item=_itemsize(t, item),
refs=refs, leng=leng,
both=True, kind=kind, type=t)
v.save(t, b... | python | {
"resource": ""
} |
q34655 | _typedef_code | train | def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False):
'''Add new typedef for code only.
'''
v = _Typedef(base=_basicsize(t, base=base),
refs=refs,
both=False, kind=kind, type=t)
v.save(t, base=base, heap=heap)
return v | python | {
"resource": ""
} |
q34656 | _typedef | train | def _typedef(obj, derive=False, infer=False):
'''Create a new typedef for an object.
'''
t = type(obj)
v = _Typedef(base=_basicsize(t, obj=obj),
kind=_kind_dynamic, type=t)
##_printf('new %r %r/%r %s', t, _basicsize(t), _itemsize(t), _repr(dir(obj)))
if ismodule(obj): # handle m... | python | {
"resource": ""
} |
q34657 | adict | train | def adict(*classes):
'''Install one or more classes to be handled as dict.
'''
a = True
for c in classes:
# if class is dict-like, add class
# name to _dict_classes[module]
if isclass(c) and _infer_dict(c):
t = _dict_classes.get(c.__module__, ())
if c.__... | python | {
"resource": ""
} |
q34658 | asizeof | train | def asizeof(*objs, **opts):
'''Return the combined size in bytes of all objects passed as positional argments.
The available options and defaults are the following.
*align=8* -- size alignment
*all=False* -- all current objects
*clip=80* -- clip ``repr()`` strings
... | python | {
"resource": ""
} |
q34659 | asizesof | train | def asizesof(*objs, **opts):
'''Return a tuple containing the size in bytes of all objects
passed as positional argments using the following options.
*align=8* -- size alignment
*clip=80* -- clip ``repr()`` strings
*code=False* -- incl. (byte)code size
... | python | {
"resource": ""
} |
q34660 | _typedefof | train | def _typedefof(obj, save=False, **opts):
'''Get the typedef for an object.
'''
k = _objkey(obj)
v = _typedefs.get(k, None)
if not v: # new typedef
v = _typedef(obj, **opts)
if save:
_typedefs[k] = v
return v | python | {
"resource": ""
} |
q34661 | _Typedef.args | train | def args(self): # as args tuple
'''Return all attributes as arguments tuple.
'''
return (self.base, self.item, self.leng, self.refs,
self.both, self.kind, self.type) | python | {
"resource": ""
} |
q34662 | _Typedef.dup | train | def dup(self, other=None, **kwds):
'''Duplicate attributes of dict or other typedef.
'''
if other is None:
d = _dict_typedef.kwds()
else:
d = other.kwds()
d.update(kwds)
self.reset(**d) | python | {
"resource": ""
} |
q34663 | _Typedef.flat | train | def flat(self, obj, mask=0):
'''Return the aligned flat size.
'''
s = self.base
if self.leng and self.item > 0: # include items
s += self.leng(obj) * self.item
if _getsizeof: # _getsizeof prevails
s = _getsizeof(obj, s)
if mask: # align
... | python | {
"resource": ""
} |
q34664 | _Typedef.kwds | train | def kwds(self):
'''Return all attributes as keywords dict.
'''
# no dict(refs=self.refs, ..., kind=self.kind) in Python 2.0
return _kwds(base=self.base, item=self.item,
leng=self.leng, refs=self.refs,
both=self.both, kind=self.kind, type=self.ty... | python | {
"resource": ""
} |
q34665 | _Typedef.save | train | def save(self, t, base=0, heap=False):
'''Save this typedef plus its class typedef.
'''
c, k = _keytuple(t)
if k and k not in _typedefs: # instance key
_typedefs[k] = self
if c and c not in _typedefs: # class key
if t.__module__ in _builtin_modul... | python | {
"resource": ""
} |
q34666 | _Typedef.set | train | def set(self, safe_len=False, **kwds):
'''Set one or more attributes.
'''
if kwds: # double check
d = self.kwds()
d.update(kwds)
self.reset(**d)
if safe_len and self.item:
self.leng = _len | python | {
"resource": ""
} |
q34667 | _Typedef.reset | train | def reset(self, base=0, item=0, leng=None, refs=None,
both=True, kind=None, type=None):
'''Reset all specified attributes.
'''
if base < 0:
raise ValueError('invalid option: %s=%r' % ('base', base))
else:
self.base = base
... | python | {
"resource": ""
} |
q34668 | _Prof.update | train | def update(self, obj, size):
'''Update this profile.
'''
self.number += 1
self.total += size
if self.high < size: # largest
self.high = size
try: # prefer using weak ref
self.objref, self.weak = Weakref.ref(obj), True
except Type... | python | {
"resource": ""
} |
q34669 | Asizer._printf | train | def _printf(self, *args, **kwargs):
'''Print to configured stream if any is specified and the file argument
is not already set for this specific call.
'''
if self._stream and not kwargs.get('file'):
kwargs['file'] = self._stream
_printf(*args, **kwargs) | python | {
"resource": ""
} |
q34670 | Asizer._clear | train | def _clear(self):
'''Clear state.
'''
self._depth = 0 # recursion depth
self._duplicate = 0
self._incl = '' # or ' (incl. code)'
self._missed = 0 # due to errors
self._profile = False
self._profs = {}
self._seen = {}
... | python | {
"resource": ""
} |
q34671 | Asizer._prof | train | def _prof(self, key):
'''Get _Prof object.
'''
p = self._profs.get(key, None)
if not p:
self._profs[key] = p = _Prof()
return p | python | {
"resource": ""
} |
q34672 | Asizer._sizer | train | def _sizer(self, obj, deep, sized):
'''Size an object, recursively.
'''
s, f, i = 0, 0, id(obj)
# skip obj if seen before
# or if ref of a given obj
if i in self._seen:
if deep:
self._seen[i] += 1
if sized:
... | python | {
"resource": ""
} |
q34673 | Asizer.exclude_refs | train | def exclude_refs(self, *objs):
'''Exclude any references to the specified objects from sizing.
While any references to the given objects are excluded, the
objects will be sized if specified as positional arguments
in subsequent calls to methods **asizeof** and **asizesof**.
... | python | {
"resource": ""
} |
q34674 | Asizer.exclude_types | train | def exclude_types(self, *objs):
'''Exclude the specified object instances and types from sizing.
All instances and types of the given objects are excluded,
even objects specified as positional arguments in subsequent
calls to methods **asizeof** and **asizesof**.
'''
... | python | {
"resource": ""
} |
q34675 | Asizer.print_summary | train | def print_summary(self, w=0, objs=(), **print3opts):
'''Print the summary statistics.
*w=0* -- indentation for each line
*objs=()* -- optional, list of objects
*print3options* -- print options, as in Python 3.0
'''
self._printf('... | python | {
"resource": ""
} |
q34676 | Asizer.print_typedefs | train | def print_typedefs(self, w=0, **print3opts):
'''Print the types and dict tables.
*w=0* -- indentation for each line
*print3options* -- print options, as in Python 3.0
'''
for k in _all_kinds:
# XXX Python 3.0 doesn't sort type objects
... | python | {
"resource": ""
} |
q34677 | Asizer.reset | train | def reset(self, align=8, clip=80, code=False, derive=False,
detail=0, ignored=True, infer=False, limit=100, stats=0,
stream=None):
'''Reset options, state, etc.
The available options and default values are:
*align=8* -- size alignment
... | python | {
"resource": ""
} |
q34678 | _find_conda | train | def _find_conda():
"""Find the conda executable robustly across conda versions.
Returns
-------
conda : str
Path to the conda executable.
Raises
------
IOError
If the executable cannot be found in either the CONDA_EXE environment
variable or in the PATH.
Notes
... | python | {
"resource": ""
} |
q34679 | recvall | train | def recvall(sock, size):
"""
Receive data of given size from a socket connection
"""
data = b""
while len(data) < size:
s = sock.recv(size - len(data))
data += s
if not s:
raise RuntimeError("did not receive data from socket "
"(size... | python | {
"resource": ""
} |
q34680 | get_source_code | train | def get_source_code(items):
"""
Extract source code of given items, and concatenate and dedent it.
"""
sources = []
prev_class_name = None
for func in items:
try:
lines, lineno = inspect.getsourcelines(func)
except TypeError:
continue
if not line... | python | {
"resource": ""
} |
q34681 | disc_modules | train | def disc_modules(module_name, ignore_import_errors=False):
"""
Recursively import a module and all sub-modules in the package
Yields
------
module
Imported module in the package tree
"""
if not ignore_import_errors:
module = import_module(module_name)
else:
try:... | python | {
"resource": ""
} |
q34682 | disc_benchmarks | train | def disc_benchmarks(root, ignore_import_errors=False):
"""
Discover all benchmarks in a given directory tree, yielding Benchmark
objects
For each class definition, looks for any methods with a
special name.
For each free function, yields all functions with a special
name.
"""
root... | python | {
"resource": ""
} |
q34683 | get_benchmark_from_name | train | def get_benchmark_from_name(root, name, extra_params=None):
"""
Create a benchmark from a fully-qualified benchmark name.
Parameters
----------
root : str
Path to the root of a benchmark suite.
name : str
Fully-qualified name to a specific benchmark.
"""
if '-' in name... | python | {
"resource": ""
} |
q34684 | list_benchmarks | train | def list_benchmarks(root, fp):
"""
List all of the discovered benchmarks to fp as JSON.
"""
update_sys_path(root)
# Streaming of JSON back out to the master process
fp.write('[')
first = True
for benchmark in disc_benchmarks(root):
if not first:
fp.write(', ')
... | python | {
"resource": ""
} |
q34685 | Benchmark.insert_param | train | def insert_param(self, param):
"""
Insert a parameter at the front of the parameter list.
"""
self._current_params = tuple([param] + list(self._current_params)) | python | {
"resource": ""
} |
q34686 | BuildCache._get_cache_dir | train | def _get_cache_dir(self, commit_hash):
"""
Get the cache dir and timestamp file corresponding to a given commit hash.
"""
path = os.path.join(self._path, commit_hash)
stamp = path + ".timestamp"
return path, stamp | python | {
"resource": ""
} |
q34687 | write_atom | train | def write_atom(dest, entries, author, title, address, updated=None, link=None,
language="en"):
"""
Write an atom feed to a file.
Parameters
----------
dest : str
Destination file path, or a file-like object
entries : list of FeedEntry
Feed entries.
author : st... | python | {
"resource": ""
} |
q34688 | _etree_py26_write | train | def _etree_py26_write(f, tree):
"""
Compatibility workaround for ElementTree shipped with py2.6
"""
f.write("<?xml version='1.0' encoding='utf-8'?>\n".encode('utf-8'))
if etree.VERSION[:3] == '1.2':
def fixtag(tag, namespaces):
if tag == XML_NS + 'lang':
return '... | python | {
"resource": ""
} |
q34689 | _get_id | train | def _get_id(owner, date, content):
"""
Generate an unique Atom id for the given content
"""
h = hashlib.sha256()
# Hash still contains the original project url, keep as is
h.update("github.com/spacetelescope/asv".encode('utf-8'))
for x in content:
if x is None:
h.update("... | python | {
"resource": ""
} |
q34690 | GcpHubClient.InitializeDebuggeeLabels | train | def InitializeDebuggeeLabels(self, flags):
"""Initialize debuggee labels from environment variables and flags.
The caller passes all the flags that the the debuglet got. This function
will only use the flags used to label the debuggee. Flags take precedence
over environment variables.
Debuggee des... | python | {
"resource": ""
} |
q34691 | GcpHubClient.SetupAuth | train | def SetupAuth(self,
project_id=None,
project_number=None,
service_account_json_file=None):
"""Sets up authentication with Google APIs.
This will use the credentials from service_account_json_file if provided,
falling back to application default credentials.
... | python | {
"resource": ""
} |
q34692 | GcpHubClient.Start | train | def Start(self):
"""Starts the worker thread."""
self._shutdown = False
self._main_thread = threading.Thread(target=self._MainThreadProc)
self._main_thread.name = 'Cloud Debugger main worker thread'
self._main_thread.daemon = True
self._main_thread.start() | python | {
"resource": ""
} |
q34693 | GcpHubClient.Stop | train | def Stop(self):
"""Signals the worker threads to shut down and waits until it exits."""
self._shutdown = True
self._new_updates.set() # Wake up the transmission thread.
if self._main_thread is not None:
self._main_thread.join()
self._main_thread = None
if self._transmission_thread is ... | python | {
"resource": ""
} |
q34694 | GcpHubClient.EnqueueBreakpointUpdate | train | def EnqueueBreakpointUpdate(self, breakpoint):
"""Asynchronously updates the specified breakpoint on the backend.
This function returns immediately. The worker thread is actually doing
all the work. The worker thread is responsible to retry the transmission
in case of transient errors.
Args:
... | python | {
"resource": ""
} |
q34695 | GcpHubClient._MainThreadProc | train | def _MainThreadProc(self):
"""Entry point for the worker thread."""
registration_required = True
while not self._shutdown:
if registration_required:
service = self._BuildService()
registration_required, delay = self._RegisterDebuggee(service)
if not registration_required:
... | python | {
"resource": ""
} |
q34696 | GcpHubClient._TransmissionThreadProc | train | def _TransmissionThreadProc(self):
"""Entry point for the transmission worker thread."""
reconnect = True
while not self._shutdown:
self._new_updates.clear()
if reconnect:
service = self._BuildService()
reconnect = False
reconnect, delay = self._TransmitBreakpointUpdates... | python | {
"resource": ""
} |
q34697 | GcpHubClient._RegisterDebuggee | train | def _RegisterDebuggee(self, service):
"""Single attempt to register the debuggee.
If the registration succeeds, sets self._debuggee_id to the registered
debuggee ID.
Args:
service: client to use for API calls
Returns:
(registration_required, delay) tuple
"""
try:
request... | python | {
"resource": ""
} |
q34698 | GcpHubClient._ListActiveBreakpoints | train | def _ListActiveBreakpoints(self, service):
"""Single attempt query the list of active breakpoints.
Must not be called before the debuggee has been registered. If the request
fails, this function resets self._debuggee_id, which triggers repeated
debuggee registration.
Args:
service: client to... | python | {
"resource": ""
} |
q34699 | GcpHubClient._TransmitBreakpointUpdates | train | def _TransmitBreakpointUpdates(self, service):
"""Tries to send pending breakpoint updates to the backend.
Sends all the pending breakpoint updates. In case of transient failures,
the breakpoint is inserted back to the top of the queue. Application
failures are not retried (for example updating breakpo... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.