text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _pad(arr, n, dir='right'):
"""Pad an array with zeros along the first axis.
Parameters
----------
n : int
Size of the returned array in the first axis.
dir : str
Direction of the padding. Must be one 'left' or 'right'.
"""
assert dir in ('left', 'right')
if n < 0:
... | [
"def",
"_pad",
"(",
"arr",
",",
"n",
",",
"dir",
"=",
"'right'",
")",
":",
"assert",
"dir",
"in",
"(",
"'left'",
",",
"'right'",
")",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"'n' must be positive: {0}.\"",
".",
"format",
"(",
"n",
")"... | 26.621622 | 0.000979 |
def plot(self):
"""
return a toyplot barplot of the results table.
"""
if self.results_table == None:
return "no results found"
else:
bb = self.results_table.sort_values(
by=["ABCD", "ACBD"],
ascending=[False, True],
... | [
"def",
"plot",
"(",
"self",
")",
":",
"if",
"self",
".",
"results_table",
"==",
"None",
":",
"return",
"\"no results found\"",
"else",
":",
"bb",
"=",
"self",
".",
"results_table",
".",
"sort_values",
"(",
"by",
"=",
"[",
"\"ABCD\"",
",",
"\"ACBD\"",
"]"... | 28.333333 | 0.009488 |
def create_snapshot(self, description='', compute_total=False):
"""
Collect current per instance statistics and saves total amount of
memory associated with the Python process.
If `compute_total` is `True`, the total consumption of all objects
known to *asizeof* is computed. The... | [
"def",
"create_snapshot",
"(",
"self",
",",
"description",
"=",
"''",
",",
"compute_total",
"=",
"False",
")",
":",
"try",
":",
"# TODO: It is not clear what happens when memory is allocated or",
"# released while this function is executed but it will likely lead",
"# to inconsis... | 42.333333 | 0.002025 |
def objLon(ID, chart):
""" Returns the longitude of an object. """
if ID.startswith('$R'):
# Return Ruler
ID = ID[2:]
obj = chart.get(ID)
rulerID = essential.ruler(obj.sign)
ruler = chart.getObject(rulerID)
return ruler.lon
elif ID.startswith('Pars'):
... | [
"def",
"objLon",
"(",
"ID",
",",
"chart",
")",
":",
"if",
"ID",
".",
"startswith",
"(",
"'$R'",
")",
":",
"# Return Ruler",
"ID",
"=",
"ID",
"[",
"2",
":",
"]",
"obj",
"=",
"chart",
".",
"get",
"(",
"ID",
")",
"rulerID",
"=",
"essential",
".",
... | 28.125 | 0.002151 |
def free_functions(
self,
name=None,
function=None,
return_type=None,
arg_types=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None):
"""
Returns a set of free function decla... | [
"def",
"free_functions",
"(",
"self",
",",
"name",
"=",
"None",
",",
"function",
"=",
"None",
",",
"return_type",
"=",
"None",
",",
"arg_types",
"=",
"None",
",",
"header_dir",
"=",
"None",
",",
"header_file",
"=",
"None",
",",
"recursive",
"=",
"None",
... | 29.827586 | 0.00224 |
def split_expression_by_depth(where, schema, output=None, var_to_depth=None):
"""
:param where: EXPRESSION TO INSPECT
:param schema: THE SCHEMA
:param output:
:param var_to_depth: MAP FROM EACH VARIABLE NAME TO THE DEPTH
:return:
"""
"""
It is unfortunate that ES can not handle expre... | [
"def",
"split_expression_by_depth",
"(",
"where",
",",
"schema",
",",
"output",
"=",
"None",
",",
"var_to_depth",
"=",
"None",
")",
":",
"\"\"\"\n It is unfortunate that ES can not handle expressions that\n span nested indexes. This will split your where clause\n returning ... | 32.447368 | 0.001575 |
def missing_inds(x, format_data=True):
"""
Returns indices of missing data
This function is useful to identify rows of your array that contain missing
data or nans. The returned indices can be used to remove the rows with
missing data, or label the missing data points that are interpolated
usi... | [
"def",
"missing_inds",
"(",
"x",
",",
"format_data",
"=",
"True",
")",
":",
"if",
"format_data",
":",
"x",
"=",
"formatter",
"(",
"x",
",",
"ppca",
"=",
"False",
")",
"inds",
"=",
"[",
"]",
"for",
"arr",
"in",
"x",
":",
"if",
"np",
".",
"argwhere... | 26.675676 | 0.001955 |
def get_orders(self, product_id=None, status=None, **kwargs):
""" List your current open orders.
This method returns a generator which may make multiple HTTP requests
while iterating through it.
Only open or un-settled orders are returned. As soon as an
order is no longer open ... | [
"def",
"get_orders",
"(",
"self",
",",
"product_id",
"=",
"None",
",",
"status",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"kwargs",
"if",
"product_id",
"is",
"not",
"None",
":",
"params",
"[",
"'product_id'",
"]",
"=",
"product_id... | 41.015625 | 0.000744 |
def crypto_sign_ed25519_sk_to_curve25519(secret_key_bytes):
"""
Converts a secret Ed25519 key (encoded as bytes ``secret_key_bytes``) to
a secret Curve25519 key as bytes.
Raises a ValueError if ``secret_key_bytes``is not of length
``crypto_sign_SECRETKEYBYTES``
:param secret_key_bytes: bytes
... | [
"def",
"crypto_sign_ed25519_sk_to_curve25519",
"(",
"secret_key_bytes",
")",
":",
"if",
"len",
"(",
"secret_key_bytes",
")",
"!=",
"crypto_sign_SECRETKEYBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid curve secret key\"",
")",
"curve_secret_key_len",
"=",
... | 36.083333 | 0.001125 |
def pvariance(data, mu=None):
"""Return the population variance of ``data``.
data should be an iterable of Real-valued numbers, with at least one
value. The optional argument mu, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this func... | [
"def",
"pvariance",
"(",
"data",
",",
"mu",
"=",
"None",
")",
":",
"if",
"iter",
"(",
"data",
")",
"is",
"data",
":",
"data",
"=",
"list",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"<",
"1",
":",
"raise",
"StatisticsError"... | 33.666667 | 0.000962 |
def target_to_ipv4_short(target):
""" Attempt to return a IPv4 short range list from a target string. """
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
end_value = int(splitted[1])
except (socket.er... | [
"def",
"target_to_ipv4_short",
"(",
"target",
")",
":",
"splitted",
"=",
"target",
".",
"split",
"(",
"'-'",
")",
"if",
"len",
"(",
"splitted",
")",
"!=",
"2",
":",
"return",
"None",
"try",
":",
"start_packed",
"=",
"inet_pton",
"(",
"socket",
".",
"AF... | 38.6875 | 0.001577 |
def tostream(func, module_name=None):
"""
Decorator to convert the function output into a Stream. Useful for
generator functions.
Note
----
Always use the ``module_name`` input when "decorating" a function that was
defined in other module.
"""
@wraps(func)
def new_func(*args, **kwargs):
return... | [
"def",
"tostream",
"(",
"func",
",",
"module_name",
"=",
"None",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Stream",
"(",
"func",
"(",
"*",
"args",
",",
"*",
"*",
... | 24.705882 | 0.013761 |
def register(classname, cls):
"""Add a class to the registry of serializer classes. When a class is
registered, an entry for both its classname and its full, module-qualified
path are added to the registry.
Example: ::
class MyClass:
pass
register('MyClass', MyClass)
... | [
"def",
"register",
"(",
"classname",
",",
"cls",
")",
":",
"# Module where the class is located",
"module",
"=",
"cls",
".",
"__module__",
"# Full module path to the class",
"# e.g. user.schemas.UserSchema",
"fullpath",
"=",
"'.'",
".",
"join",
"(",
"[",
"module",
","... | 32.358974 | 0.000769 |
def mtime(self):
"""
Get most recent modify time in timestamp.
"""
try:
return self._stat.st_mtime
except: # pragma: no cover
self._stat = self.stat()
return self.mtime | [
"def",
"mtime",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_stat",
".",
"st_mtime",
"except",
":",
"# pragma: no cover",
"self",
".",
"_stat",
"=",
"self",
".",
"stat",
"(",
")",
"return",
"self",
".",
"mtime"
] | 26.333333 | 0.012245 |
def b6_evalue_filter(handle, e_value, *args, **kwargs):
"""Yields lines from handle with E-value less than or equal to e_value
Args:
handle (file): B6/M8 file handle, can be any iterator so long as it
it returns subsequent "lines" of a B6/M8 entry
e_value (float): max E-value to re... | [
"def",
"b6_evalue_filter",
"(",
"handle",
",",
"e_value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"entry",
"in",
"b6_iter",
"(",
"handle",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"entry",
".",
"evalue",
"<=",
... | 32.964286 | 0.001053 |
def process_management_config_section(config, management_config):
""" Processes the management section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param management_config: Management section from a config... | [
"def",
"process_management_config_section",
"(",
"config",
",",
"management_config",
")",
":",
"if",
"'commands'",
"in",
"management_config",
":",
"for",
"command",
"in",
"management_config",
"[",
"'commands'",
"]",
":",
"config",
".",
"management",
"[",
"'commands'... | 48.2 | 0.002037 |
def view(src, mono):
"""Inspect statistics by TUI view."""
src_type, src_name = src
title = get_title(src_name, src_type)
viewer, loop = make_viewer(mono)
if src_type == 'dump':
time = datetime.fromtimestamp(os.path.getmtime(src_name))
with open(src_name, 'rb') as f:
prof... | [
"def",
"view",
"(",
"src",
",",
"mono",
")",
":",
"src_type",
",",
"src_name",
"=",
"src",
"title",
"=",
"get_title",
"(",
"src_name",
",",
"src_type",
")",
"viewer",
",",
"loop",
"=",
"make_viewer",
"(",
"mono",
")",
"if",
"src_type",
"==",
"'dump'",
... | 40.666667 | 0.001144 |
def wave_range(bins, cenwave, npix, round='round'):
"""Get the wavelength range covered by the given number of pixels
centered on the given wavelength.
Parameters
----------
bins : ndarray
Wavelengths of pixel centers. Must be in the same units as
``cenwave``.
cenwave : float
... | [
"def",
"wave_range",
"(",
"bins",
",",
"cenwave",
",",
"npix",
",",
"round",
"=",
"'round'",
")",
":",
"# make sure that the round keyword is valid",
"if",
"round",
"not",
"in",
"(",
"None",
",",
"'round'",
",",
"'min'",
",",
"'max'",
")",
":",
"raise",
"V... | 37.276836 | 0.001771 |
def process_utterance(self, utterance, frame_size=400, hop_size=160, sr=None, corpus=None):
"""
Process the utterance in **offline** mode, in one go.
Args:
utterance (Utterance): The utterance to process.
frame_size (int): The number of samples per frame.
hop... | [
"def",
"process_utterance",
"(",
"self",
",",
"utterance",
",",
"frame_size",
"=",
"400",
",",
"hop_size",
"=",
"160",
",",
"sr",
"=",
"None",
",",
"corpus",
"=",
"None",
")",
":",
"return",
"self",
".",
"process_track",
"(",
"utterance",
".",
"track",
... | 52.8125 | 0.00814 |
def radianceSpectrum(Omegas,AbsorptionCoefficient,Environment={'l':100.,'T':296.},
File=None, Format='%e %e', Wavenumber=None):
"""
INPUT PARAMETERS:
Wavenumber/Omegas: wavenumber grid (required)
AbsorptionCoefficient: absorption coefficient on grid (re... | [
"def",
"radianceSpectrum",
"(",
"Omegas",
",",
"AbsorptionCoefficient",
",",
"Environment",
"=",
"{",
"'l'",
":",
"100.",
",",
"'T'",
":",
"296.",
"}",
",",
"File",
"=",
"None",
",",
"Format",
"=",
"'%e %e'",
",",
"Wavenumber",
"=",
"None",
")",
":",
"... | 43.567568 | 0.012743 |
def delete_scope(self, scope):
"""
Delete a scope.
This will delete a scope if the client has the right to do so. Sufficient permissions to delete a scope are a
superuser, a user in the `GG:Configurators` group or a user that is the Scope manager of the scope to be
deleted.
... | [
"def",
"delete_scope",
"(",
"self",
",",
"scope",
")",
":",
"assert",
"isinstance",
"(",
"scope",
",",
"Scope",
")",
",",
"'Scope \"{}\" is not a scope!'",
".",
"format",
"(",
"scope",
".",
"name",
")",
"response",
"=",
"self",
".",
"_request",
"(",
"'DELE... | 43.3 | 0.00904 |
def heatmapf(func, scale=10, boundary=True, cmap=None, ax=None,
scientific=False, style='triangular', colorbar=True,
permutation=None, vmin=None, vmax=None, cbarlabel=None,
cb_kwargs=None):
"""
Computes func on heatmap partition coordinates and plots heatmap. In other
... | [
"def",
"heatmapf",
"(",
"func",
",",
"scale",
"=",
"10",
",",
"boundary",
"=",
"True",
",",
"cmap",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"scientific",
"=",
"False",
",",
"style",
"=",
"'triangular'",
",",
"colorbar",
"=",
"True",
",",
"permutati... | 36.509804 | 0.001569 |
def cat_files(infiles, outfile):
'''Cats all files in list infiles into outfile'''
f_out = pyfastaq.utils.open_file_write(outfile)
for filename in infiles:
if os.path.exists(filename):
f_in = pyfastaq.utils.open_file_read(filename)
for line in f_in:
print(lin... | [
"def",
"cat_files",
"(",
"infiles",
",",
"outfile",
")",
":",
"f_out",
"=",
"pyfastaq",
".",
"utils",
".",
"open_file_write",
"(",
"outfile",
")",
"for",
"filename",
"in",
"infiles",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":... | 33.583333 | 0.002415 |
def created_at_pretty(self, date_format=None):
"""Return pretty timestamp."""
if date_format:
return pretty_timestamp(self.created_at, date_format=date_format)
return pretty_timestamp(self.created_at) | [
"def",
"created_at_pretty",
"(",
"self",
",",
"date_format",
"=",
"None",
")",
":",
"if",
"date_format",
":",
"return",
"pretty_timestamp",
"(",
"self",
".",
"created_at",
",",
"date_format",
"=",
"date_format",
")",
"return",
"pretty_timestamp",
"(",
"self",
... | 46.4 | 0.008475 |
def tm(seq, dna_conc=50, salt_conc=50, parameters='cloning'):
'''Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in ... | [
"def",
"tm",
"(",
"seq",
",",
"dna_conc",
"=",
"50",
",",
"salt_conc",
"=",
"50",
",",
"parameters",
"=",
"'cloning'",
")",
":",
"if",
"parameters",
"==",
"'breslauer'",
":",
"params",
"=",
"tm_params",
".",
"BRESLAUER",
"elif",
"parameters",
"==",
"'sug... | 41.601626 | 0.000191 |
def open_this(self, file, how): # type: (str,str) -> Any
"""
Open file while detecting encoding. Use cached when possible.
:param file:
:param how:
:return:
"""
# BUG: risky code here, allowing relative
if not file.startswith("/"):
# raise Typ... | [
"def",
"open_this",
"(",
"self",
",",
"file",
",",
"how",
")",
":",
"# type: (str,str) -> Any",
"# BUG: risky code here, allowing relative",
"if",
"not",
"file",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"# raise TypeError(\"this isn't absolute! We're siths, ya' know.\")",... | 33.516129 | 0.001871 |
def build_lv_graph_ria(lvgd, grid_model_params):
"""Build graph for LV grid of sectors retail/industrial and agricultural
Based on structural description of LV grid topology for sectors
retail/industrial and agricultural (RIA) branches for these sectors are
created and attached to the LV grid's MV-LV s... | [
"def",
"build_lv_graph_ria",
"(",
"lvgd",
",",
"grid_model_params",
")",
":",
"def",
"lv_graph_attach_branch",
"(",
")",
":",
"\"\"\"Attach a single branch including its equipment (cable dist, loads\n and line segments) to graph of `lv_grid`\n \"\"\"",
"# determine maximum ... | 38.611374 | 0.000598 |
def get_nbytes(dset):
"""
If the dataset has an attribute 'nbytes', return it. Otherwise get the size
of the underlying array. Returns None if the dataset is actually a group.
"""
if 'nbytes' in dset.attrs:
# look if the dataset has an attribute nbytes
return dset.attrs['nbytes']
... | [
"def",
"get_nbytes",
"(",
"dset",
")",
":",
"if",
"'nbytes'",
"in",
"dset",
".",
"attrs",
":",
"# look if the dataset has an attribute nbytes",
"return",
"dset",
".",
"attrs",
"[",
"'nbytes'",
"]",
"elif",
"hasattr",
"(",
"dset",
",",
"'dtype'",
")",
":",
"#... | 41.454545 | 0.002146 |
def show_weights(estimator, **kwargs):
""" Return an explanation of estimator parameters (weights)
as an IPython.display.HTML object. Use this function
to show classifier weights in IPython.
:func:`show_weights` accepts all
:func:`eli5.explain_weights` arguments and all
:func:`eli5.formatters.h... | [
"def",
"show_weights",
"(",
"estimator",
",",
"*",
"*",
"kwargs",
")",
":",
"format_kwargs",
",",
"explain_kwargs",
"=",
"_split_kwargs",
"(",
"kwargs",
")",
"expl",
"=",
"explain_weights",
"(",
"estimator",
",",
"*",
"*",
"explain_kwargs",
")",
"html",
"=",... | 42.380952 | 0.000439 |
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
:param config_str: The string to be sprinkled
:return: The string sprinkled
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, le... | [
"def",
"_sprinkle",
"(",
"config_str",
")",
":",
"parts",
"=",
"[",
"x",
"for",
"sub",
"in",
"config_str",
".",
"split",
"(",
"'{'",
")",
"for",
"x",
"in",
"sub",
".",
"split",
"(",
"'}'",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"le... | 37.454545 | 0.00237 |
def get_per_object_threshold(method, image, threshold, mask=None, labels=None,
threshold_range_min = None,
threshold_range_max = None,
**kwargs):
"""Return a matrix giving threshold per pixel calculated per-object
image ... | [
"def",
"get_per_object_threshold",
"(",
"method",
",",
"image",
",",
"threshold",
",",
"mask",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"threshold_range_min",
"=",
"None",
",",
"threshold_range_max",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if... | 44.269231 | 0.012755 |
def serialize(self, data, response=None, request=None, format=None):
"""Serializes the data using a determined serializer.
@param[in] data
The data to be serialized.
@param[in] response
The response object to serialize the data to.
If this method is invoked ... | [
"def",
"serialize",
"(",
"self",
",",
"data",
",",
"response",
"=",
"None",
",",
"request",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"Resource",
")",
":",
"if",
"not",
"request",
":",
"# Ensure we have a ... | 41.060241 | 0.000573 |
def setup_sfr_obs(self):
"""setup sfr ASCII observations"""
if not self.sfr_obs:
return
if self.m.sfr is None:
self.logger.lraise("no sfr package found...")
org_sfr_out_file = os.path.join(self.org_model_ws,"{0}.sfr.out".format(self.m.name))
if not os.pat... | [
"def",
"setup_sfr_obs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"sfr_obs",
":",
"return",
"if",
"self",
".",
"m",
".",
"sfr",
"is",
"None",
":",
"self",
".",
"logger",
".",
"lraise",
"(",
"\"no sfr package found...\"",
")",
"org_sfr_out_file",
"... | 47.545455 | 0.011246 |
def modification_time(self):
"""dfdatetime.DateTimeValues: modification time or None if not available."""
if self._stat_info is None:
return None
timestamp = int(self._stat_info.st_mtime)
return dfdatetime_posix_time.PosixTime(timestamp=timestamp) | [
"def",
"modification_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stat_info",
"is",
"None",
":",
"return",
"None",
"timestamp",
"=",
"int",
"(",
"self",
".",
"_stat_info",
".",
"st_mtime",
")",
"return",
"dfdatetime_posix_time",
".",
"PosixTime",
"(",
... | 37.714286 | 0.011111 |
def visit_insert(self, insert_stmt, asfrom=False, **kw):
"""
used to compile <sql.expression.Insert> expressions.
this function wraps insert_from_select statements inside
parentheses to be conform with earlier versions of CreateDB.
"""
self.stack.append(
{'... | [
"def",
"visit_insert",
"(",
"self",
",",
"insert_stmt",
",",
"asfrom",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"stack",
".",
"append",
"(",
"{",
"'correlate_froms'",
":",
"set",
"(",
")",
",",
"\"asfrom_froms\"",
":",
"set",
"(",
")... | 35.886598 | 0.000559 |
def _get_dict_from_list(dict_key, list_of_dicts):
"""Retrieve a specific dict from a list of dicts.
Parameters
----------
dict_key : str
The (single) key of the dict to be retrieved from the list.
list_of_dicts : list
The list of dicts to search for the specific dict.
Returns
... | [
"def",
"_get_dict_from_list",
"(",
"dict_key",
",",
"list_of_dicts",
")",
":",
"the_dict",
"=",
"[",
"cur_dict",
"for",
"cur_dict",
"in",
"list_of_dicts",
"if",
"cur_dict",
".",
"get",
"(",
"dict_key",
")",
"]",
"if",
"not",
"the_dict",
":",
"raise",
"ValueE... | 30.809524 | 0.001499 |
def reference_contexts_for_variant(
variant,
context_size,
transcript_id_whitelist=None):
"""
variant : varcode.Variant
context_size : int
Max of nucleotides to include to the left and right of the variant
in the context sequence.
transcript_id_whitelist : set, ... | [
"def",
"reference_contexts_for_variant",
"(",
"variant",
",",
"context_size",
",",
"transcript_id_whitelist",
"=",
"None",
")",
":",
"overlapping_transcripts",
"=",
"reference_transcripts_for_variant",
"(",
"variant",
"=",
"variant",
",",
"transcript_id_whitelist",
"=",
"... | 36.547619 | 0.000635 |
def data_log_likelihood(self, successes, trials, beta):
'''Calculates the log-likelihood of a Polya tree bin given the beta values.'''
return binom.logpmf(successes, trials, 1.0 / (1 + np.exp(-beta))).sum() | [
"def",
"data_log_likelihood",
"(",
"self",
",",
"successes",
",",
"trials",
",",
"beta",
")",
":",
"return",
"binom",
".",
"logpmf",
"(",
"successes",
",",
"trials",
",",
"1.0",
"/",
"(",
"1",
"+",
"np",
".",
"exp",
"(",
"-",
"beta",
")",
")",
")",... | 73.333333 | 0.013514 |
def list_(pkg=None, dir=None, runas=None, env=None, depth=None):
'''
List installed NPM packages.
If no directory is specified, this will return the list of globally-
installed packages.
pkg
Limit package listing by name
dir
The directory whose packages will be listed, or None... | [
"def",
"list_",
"(",
"pkg",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"env",
"=",
"None",
",",
"depth",
"=",
"None",
")",
":",
"env",
"=",
"env",
"or",
"{",
"}",
"if",
"runas",
":",
"uid",
"=",
"salt",
".",
"utils"... | 26.471429 | 0.001561 |
def addChildList(self, cur):
"""Add a list of node at the end of the child list of the
parent merging adjacent TEXT nodes (@cur may be freed) """
if cur is None: cur__o = None
else: cur__o = cur._o
ret = libxml2mod.xmlAddChildList(self._o, cur__o)
if ret is None:raise ... | [
"def",
"addChildList",
"(",
"self",
",",
"cur",
")",
":",
"if",
"cur",
"is",
"None",
":",
"cur__o",
"=",
"None",
"else",
":",
"cur__o",
"=",
"cur",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlAddChildList",
"(",
"self",
".",
"_o",
",",
"cur__o",
... | 44.888889 | 0.014563 |
def variablename(var):
"""
Returns the string of a variable name.
"""
s=[tpl[0] for tpl in itertools.ifilter(lambda x: var is x[1], globals().items())]
s=s[0].upper()
return s | [
"def",
"variablename",
"(",
"var",
")",
":",
"s",
"=",
"[",
"tpl",
"[",
"0",
"]",
"for",
"tpl",
"in",
"itertools",
".",
"ifilter",
"(",
"lambda",
"x",
":",
"var",
"is",
"x",
"[",
"1",
"]",
",",
"globals",
"(",
")",
".",
"items",
"(",
")",
")"... | 27.571429 | 0.020101 |
def revisions(self, path, max_revisions):
"""
Get the list of revisions.
:param path: the path to target.
:type path: ``str``
:param max_revisions: the maximum number of revisions.
:type max_revisions: ``int``
:return: A list of revisions.
:rtype: ``l... | [
"def",
"revisions",
"(",
"self",
",",
"path",
",",
"max_revisions",
")",
":",
"if",
"self",
".",
"repo",
".",
"is_dirty",
"(",
")",
":",
"raise",
"DirtyGitRepositoryError",
"(",
"self",
".",
"repo",
".",
"untracked_files",
")",
"revisions",
"=",
"[",
"]"... | 31.172414 | 0.002146 |
def create_logstash(self, **kwargs):
"""
Creates an instance of the Logging Service.
"""
logstash = predix.admin.logstash.Logging(**kwargs)
logstash.create()
logstash.add_to_manifest(self)
logging.info('Install Kibana-Me-Logs application by following GitHub instr... | [
"def",
"create_logstash",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"logstash",
"=",
"predix",
".",
"admin",
".",
"logstash",
".",
"Logging",
"(",
"*",
"*",
"kwargs",
")",
"logstash",
".",
"create",
"(",
")",
"logstash",
".",
"add_to_manifest",
"... | 36.5 | 0.008909 |
def timeFormat(time_from, time_to=None, prefix="", infix=None):
"""
Format the times time_from and optionally time_to, e.g. 10am
"""
retval = ""
if time_from != "" and time_from is not None:
retval += prefix
retval += dateformat.time_format(time_from, "fA").lower()
if time_to != ... | [
"def",
"timeFormat",
"(",
"time_from",
",",
"time_to",
"=",
"None",
",",
"prefix",
"=",
"\"\"",
",",
"infix",
"=",
"None",
")",
":",
"retval",
"=",
"\"\"",
"if",
"time_from",
"!=",
"\"\"",
"and",
"time_from",
"is",
"not",
"None",
":",
"retval",
"+=",
... | 41.6875 | 0.001466 |
def current_fact_index(self):
"""Current fact index in the self.facts list."""
facts_ids = [fact.id for fact in self.facts]
return facts_ids.index(self.current_fact.id) | [
"def",
"current_fact_index",
"(",
"self",
")",
":",
"facts_ids",
"=",
"[",
"fact",
".",
"id",
"for",
"fact",
"in",
"self",
".",
"facts",
"]",
"return",
"facts_ids",
".",
"index",
"(",
"self",
".",
"current_fact",
".",
"id",
")"
] | 47.25 | 0.010417 |
def ghmean(nums):
"""Return geometric-harmonic mean.
Iterates between geometric & harmonic means until they converge to
a single value (rounded to 12 digits).
Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean
Parameters
----------
nums : list
A series of numbers
Retur... | [
"def",
"ghmean",
"(",
"nums",
")",
":",
"m_g",
"=",
"gmean",
"(",
"nums",
")",
"m_h",
"=",
"hmean",
"(",
"nums",
")",
"if",
"math",
".",
"isnan",
"(",
"m_g",
")",
"or",
"math",
".",
"isnan",
"(",
"m_h",
")",
":",
"return",
"float",
"(",
"'nan'"... | 20.8 | 0.001148 |
def auto_update_attrs_from_kwargs(method):
""" this decorator will update the attributes of an
instance object with all the kwargs of the decorated
method, updated with the kwargs of the actual call.
This saves you from boring typing:
self.xxxx = xxxx
self.yyyy = yyyy
...
in the d... | [
"def",
"auto_update_attrs_from_kwargs",
"(",
"method",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# method signature introspection",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"method",
")",
"defaults",
"=",
"argspec",
... | 36.36 | 0.001072 |
def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True):
"""
IoU for foreground class
binary: 1 foreground, 0 background
"""
if not per_image:
preds, labels = (preds,), (labels,)
ious = []
for pred, label in zip(preds, labels):
intersection = ((label == 1) & (pre... | [
"def",
"iou_binary",
"(",
"preds",
",",
"labels",
",",
"EMPTY",
"=",
"1.",
",",
"ignore",
"=",
"None",
",",
"per_image",
"=",
"True",
")",
":",
"if",
"not",
"per_image",
":",
"preds",
",",
"labels",
"=",
"(",
"preds",
",",
")",
",",
"(",
"labels",
... | 33.388889 | 0.001618 |
def _ReadPacket(self):
"""Read a single data record as a string (without length or checksum).
"""
len_char = self.ser.read(1)
if not len_char:
logging.error("Reading from serial port timed out.")
return None
data_len = ord(len_char)
if not data_le... | [
"def",
"_ReadPacket",
"(",
"self",
")",
":",
"len_char",
"=",
"self",
".",
"ser",
".",
"read",
"(",
"1",
")",
"if",
"not",
"len_char",
":",
"logging",
".",
"error",
"(",
"\"Reading from serial port timed out.\"",
")",
"return",
"None",
"data_len",
"=",
"or... | 37.24 | 0.002094 |
def unescape(s):
"""The reverse function of `escape`. This unescapes all the HTML
entities, not only the XML entities inserted by `escape`.
:param s: the string to unescape.
"""
def handle_match(m):
name = m.group(1)
if name in HTMLBuilder._entities:
return unichr(HTMLB... | [
"def",
"unescape",
"(",
"s",
")",
":",
"def",
"handle_match",
"(",
"m",
")",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"name",
"in",
"HTMLBuilder",
".",
"_entities",
":",
"return",
"unichr",
"(",
"HTMLBuilder",
".",
"_entities",
"[",
... | 32.526316 | 0.001572 |
def _log_intermediate_failure(self, err, flaky, name):
"""
Report that the test has failed, but still has reruns left.
Then rerun the test.
:param err:
Information about the test failure (from sys.exc_info())
:type err:
`tuple` of `class`, :class:`Excepti... | [
"def",
"_log_intermediate_failure",
"(",
"self",
",",
"err",
",",
"flaky",
",",
"name",
")",
":",
"max_runs",
"=",
"flaky",
"[",
"FlakyNames",
".",
"MAX_RUNS",
"]",
"runs_left",
"=",
"max_runs",
"-",
"flaky",
"[",
"FlakyNames",
".",
"CURRENT_RUNS",
"]",
"m... | 32.36 | 0.002401 |
def set_position(self, x, y, width, height):
"""Set window top-left corner position and size"""
SetWindowPos(self._hwnd, None, x, y, width, height, ctypes.c_uint(0)) | [
"def",
"set_position",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"SetWindowPos",
"(",
"self",
".",
"_hwnd",
",",
"None",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"ctypes",
".",
"c_uint",
"(",
"0",
")",
... | 59.666667 | 0.01105 |
def run(self):
"""Start the game loop"""
global world
self.__is_running = True
while(self.__is_running):
#Our game loop
#Catch our events
self.__handle_events()
#Update our clock
self.__clock.tick(self.preferred_fps)
... | [
"def",
"run",
"(",
"self",
")",
":",
"global",
"world",
"self",
".",
"__is_running",
"=",
"True",
"while",
"(",
"self",
".",
"__is_running",
")",
":",
"#Our game loop",
"#Catch our events",
"self",
".",
"__handle_events",
"(",
")",
"#Update our clock",
"self",... | 31.363636 | 0.029053 |
def get_except_handler_name(self, node):
"""
Helper to get the exception name from an ExceptHandler node in both py2 and py3.
"""
name = node.name
if not name:
return None
if version_info < (3,):
return name.id
return name | [
"def",
"get_except_handler_name",
"(",
"self",
",",
"node",
")",
":",
"name",
"=",
"node",
".",
"name",
"if",
"not",
"name",
":",
"return",
"None",
"if",
"version_info",
"<",
"(",
"3",
",",
")",
":",
"return",
"name",
".",
"id",
"return",
"name"
] | 24.416667 | 0.009868 |
def read(self, length, timeout):
"""Read 'length' bytes from this stream transport.
Args:
length: If not 0, read this many bytes from the stream, otherwise read all
available data (at least one byte).
timeout: timeouts.PolledTimeout to use for this read operation.
Returns:
The by... | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"timeout",
")",
":",
"self",
".",
"_read_messages_until_true",
"(",
"lambda",
":",
"self",
".",
"_buffer_size",
"and",
"self",
".",
"_buffer_size",
">=",
"length",
",",
"timeout",
")",
"with",
"self",
".",
... | 33.130435 | 0.008929 |
def keep_max_priority_effects(effects):
"""
Given a list of effects, only keep the ones with the maximum priority
effect type.
Parameters
----------
effects : list of MutationEffect subclasses
Returns list of same length or shorter
"""
priority_values = map(effect_priority, effects... | [
"def",
"keep_max_priority_effects",
"(",
"effects",
")",
":",
"priority_values",
"=",
"map",
"(",
"effect_priority",
",",
"effects",
")",
"max_priority",
"=",
"max",
"(",
"priority_values",
")",
"return",
"[",
"e",
"for",
"(",
"e",
",",
"p",
")",
"in",
"zi... | 30.571429 | 0.002268 |
def remove_leaf_names(self):
"""
Set the name of all leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: n.is_leaf) | [
"def",
"remove_leaf_names",
"(",
"self",
")",
":",
"self",
".",
"visit",
"(",
"lambda",
"n",
":",
"setattr",
"(",
"n",
",",
"'name'",
",",
"None",
")",
",",
"lambda",
"n",
":",
"n",
".",
"is_leaf",
")"
] | 37.4 | 0.010471 |
def init_app(self, app):
"""
For Flask using the app config
"""
self.__init__(aws_access_key_id=app.config.get("SES_AWS_ACCESS_KEY"),
aws_secret_access_key=app.config.get("SES_AWS_SECRET_KEY"),
region=app.config.get("SES_REGION", "us-east-1"),
... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"__init__",
"(",
"aws_access_key_id",
"=",
"app",
".",
"config",
".",
"get",
"(",
"\"SES_AWS_ACCESS_KEY\"",
")",
",",
"aws_secret_access_key",
"=",
"app",
".",
"config",
".",
"get",
"(",
... | 50.25 | 0.008143 |
def check_valence(self):
"""
check valences of all atoms
:return: list of invalid atoms
"""
return [x for x, atom in self.atoms() if not atom.check_valence(self.environment(x))] | [
"def",
"check_valence",
"(",
"self",
")",
":",
"return",
"[",
"x",
"for",
"x",
",",
"atom",
"in",
"self",
".",
"atoms",
"(",
")",
"if",
"not",
"atom",
".",
"check_valence",
"(",
"self",
".",
"environment",
"(",
"x",
")",
")",
"]"
] | 30.285714 | 0.013761 |
def create(args):
""" Create a model from wavelength and flux files. """
from sick.models.create import create
return create(os.path.join(args.output_dir, args.model_name),
args.grid_points_filename, args.wavelength_filenames,
clobber=args.clobber) | [
"def",
"create",
"(",
"args",
")",
":",
"from",
"sick",
".",
"models",
".",
"create",
"import",
"create",
"return",
"create",
"(",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"output_dir",
",",
"args",
".",
"model_name",
")",
",",
"args",
".",
... | 38.857143 | 0.014388 |
def sub_state_by_gene_name(self, *gene_names: str) -> 'State':
"""
Create a sub state with only the gene passed in arguments.
Example
-------
>>> state.sub_state_by_gene_name('operon')
{operon: 2}
>>> state.sub_state_by_gene_name('mucuB')
{mucuB: 0}
... | [
"def",
"sub_state_by_gene_name",
"(",
"self",
",",
"*",
"gene_names",
":",
"str",
")",
"->",
"'State'",
":",
"return",
"State",
"(",
"{",
"gene",
":",
"state",
"for",
"gene",
",",
"state",
"in",
"self",
".",
"items",
"(",
")",
"if",
"gene",
".",
"nam... | 29.857143 | 0.009281 |
def _equaBreaks(self, orbit_index_period=24.):
"""Determine where breaks in an equatorial satellite orbit occur.
Looks for negative gradients in local time (or longitude) as well as
breaks in UT.
Parameters
----------
orbit_index_period : float
The change in... | [
"def",
"_equaBreaks",
"(",
"self",
",",
"orbit_index_period",
"=",
"24.",
")",
":",
"if",
"self",
".",
"orbit_index",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Orbit properties must be defined at '",
"+",
"'pysat.Instrument object instantiation.'",
"+",
"'See I... | 44.3 | 0.001019 |
def get_hpkp_pin(cls, certificate: cryptography.x509.Certificate) -> str:
"""Generate the HTTP Public Key Pinning hash (RFC 7469) for the given certificate.
"""
return b64encode(cls.get_public_key_sha256(certificate)).decode('utf-8') | [
"def",
"get_hpkp_pin",
"(",
"cls",
",",
"certificate",
":",
"cryptography",
".",
"x509",
".",
"Certificate",
")",
"->",
"str",
":",
"return",
"b64encode",
"(",
"cls",
".",
"get_public_key_sha256",
"(",
"certificate",
")",
")",
".",
"decode",
"(",
"'utf-8'",
... | 63.5 | 0.015564 |
def array_scanlines_interlace(self, pixels):
"""
Generator for interlaced scanlines from an array.
`pixels` is the full source image as a single array of values.
The generator yields each scanline of the reduced passes in turn,
each scanline being a sequence of values.
""... | [
"def",
"array_scanlines_interlace",
"(",
"self",
",",
"pixels",
")",
":",
"# http://www.w3.org/TR/PNG/#8InterlaceMethods",
"# Array type.",
"fmt",
"=",
"'BH'",
"[",
"self",
".",
"bitdepth",
">",
"8",
"]",
"# Value per row",
"vpr",
"=",
"self",
".",
"width",
"*",
... | 43.2 | 0.001132 |
def cli(ctx, organism_id, common_name, directory, blatdb="", species="", genus="", public=False):
"""Update an organism
Output:
a dictionary with information about the new organism
"""
return ctx.gi.organisms.update_organism(organism_id, common_name, directory, blatdb=blatdb, species=species, genus=ge... | [
"def",
"cli",
"(",
"ctx",
",",
"organism_id",
",",
"common_name",
",",
"directory",
",",
"blatdb",
"=",
"\"\"",
",",
"species",
"=",
"\"\"",
",",
"genus",
"=",
"\"\"",
",",
"public",
"=",
"False",
")",
":",
"return",
"ctx",
".",
"gi",
".",
"organisms... | 41.5 | 0.00885 |
def file_follow_durable( path,
min_dump_interval=10,
xattr_name='user.collectd.logtail.pos', xattr_update=True,
**follow_kwz ):
'''Records log position into xattrs after reading line every
min_dump_interval seconds.
Checksum of the last line at the position
is also recorded (so line itself don't have to ... | [
"def",
"file_follow_durable",
"(",
"path",
",",
"min_dump_interval",
"=",
"10",
",",
"xattr_name",
"=",
"'user.collectd.logtail.pos'",
",",
"xattr_update",
"=",
"True",
",",
"*",
"*",
"follow_kwz",
")",
":",
"from",
"xattr",
"import",
"xattr",
"from",
"io",
"i... | 31.568966 | 0.034958 |
def evaluate(self):
""" Converts the current expression into a single matcher, applying
coordination operators to operands according to their binding rules
"""
# Apply Shunting Yard algorithm to convert the infix expression
# into Reverse Polish Notation. Since we have a ver... | [
"def",
"evaluate",
"(",
"self",
")",
":",
"# Apply Shunting Yard algorithm to convert the infix expression",
"# into Reverse Polish Notation. Since we have a very limited",
"# set of operators and binding rules, the implementation becomes",
"# really simple. The expression is formed of hamcrest ma... | 36.789474 | 0.001858 |
def find(self, name, required):
"""
Finds all matching dependencies by their name.
:param name: the dependency name to locate.
:param required: true to raise an exception when no dependencies are found.
:return: a list of found dependencies
"""
if name == None:... | [
"def",
"find",
"(",
"self",
",",
"name",
",",
"required",
")",
":",
"if",
"name",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Name cannot be null\"",
")",
"locator",
"=",
"self",
".",
"_locate",
"(",
"name",
")",
"if",
"locator",
"==",
"None",
":"... | 29.65 | 0.011438 |
def uncompress_file(input_file_name, file_extension, dest_dir):
"""
Uncompress gz and bz2 files
"""
if file_extension.lower() not in ('.gz', '.bz2'):
raise NotImplementedError("Received {} format. Only gz and bz2 "
"files can currently be uncompressed."
... | [
"def",
"uncompress_file",
"(",
"input_file_name",
",",
"file_extension",
",",
"dest_dir",
")",
":",
"if",
"file_extension",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'.gz'",
",",
"'.bz2'",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Received {} format. On... | 43.777778 | 0.001242 |
def calc_rho_and_rho_bar_squared(final_log_likelihood,
null_log_likelihood,
num_est_parameters):
"""
Calculates McFadden's rho-squared and rho-bar squared for the given model.
Parameters
----------
final_log_likelihood : float.
... | [
"def",
"calc_rho_and_rho_bar_squared",
"(",
"final_log_likelihood",
",",
"null_log_likelihood",
",",
"num_est_parameters",
")",
":",
"rho_squared",
"=",
"1.0",
"-",
"final_log_likelihood",
"/",
"null_log_likelihood",
"rho_bar_squared",
"=",
"1.0",
"-",
"(",
"(",
"final_... | 37.851852 | 0.000954 |
def _params_type(self, method_name, instance):
"""
Check to see if this is a legacy method or shiny new one
legacy update method:
def update(self, i3s_output_list, i3s_config):
...
new update method:
def update(self):
...
... | [
"def",
"_params_type",
"(",
"self",
",",
"method_name",
",",
"instance",
")",
":",
"method",
"=",
"getattr",
"(",
"instance",
",",
"method_name",
",",
"None",
")",
"if",
"not",
"method",
":",
"return",
"False",
"# Check the parameters we simply count the number of... | 30.903226 | 0.002024 |
def _calc(self, x, y):
"""
List based implementation of binary tree algorithm for concordance
measure after :cite:`Christensen2005`.
"""
x = np.array(x)
y = np.array(y)
n = len(y)
perm = list(range(n))
perm.sort(key=lambda a: (x[a], y[a]))
... | [
"def",
"_calc",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"y",
"=",
"np",
".",
"array",
"(",
"y",
")",
"n",
"=",
"len",
"(",
"y",
")",
"perm",
"=",
"list",
"(",
"range",
"(",
"n",
")",
")",
... | 31.593407 | 0.000675 |
def namedb_update_must_equal( rec, change_fields ):
"""
Generate the set of fields that must stay the same across an update.
"""
must_equal = []
if len(change_fields) != 0:
given = rec.keys()
for k in given:
if k not in change_fields:
must_equal.appen... | [
"def",
"namedb_update_must_equal",
"(",
"rec",
",",
"change_fields",
")",
":",
"must_equal",
"=",
"[",
"]",
"if",
"len",
"(",
"change_fields",
")",
"!=",
"0",
":",
"given",
"=",
"rec",
".",
"keys",
"(",
")",
"for",
"k",
"in",
"given",
":",
"if",
"k",... | 25.769231 | 0.011527 |
def _set_choices(self, value):
"""
Also update the widget's choices.
"""
super(LazyChoicesMixin, self)._set_choices(value)
self.widget.choices = value | [
"def",
"_set_choices",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"LazyChoicesMixin",
",",
"self",
")",
".",
"_set_choices",
"(",
"value",
")",
"self",
".",
"widget",
".",
"choices",
"=",
"value"
] | 30.833333 | 0.010526 |
def schema_validate(instance, schema, exc_class, *prefix, **kwargs):
"""
Schema validation helper. Performs JSONSchema validation. If a
schema validation error is encountered, an exception of the
designated class is raised with the validation error message
appropriately simplified and passed as th... | [
"def",
"schema_validate",
"(",
"instance",
",",
"schema",
",",
"exc_class",
",",
"*",
"prefix",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# Do the validation",
"jsonschema",
".",
"validate",
"(",
"instance",
",",
"schema",
")",
"except",
"jsonschema",
... | 41.125 | 0.000742 |
def read_struct_file(struct_data):
"""Interpret a struct file defining the location of variables in memory.
Parameters
----------
struct_data : :py:class:`bytes`
String of :py:class:`bytes` containing data to interpret as the struct
definition.
Returns
-------
{struct_name:... | [
"def",
"read_struct_file",
"(",
"struct_data",
")",
":",
"# Holders for all structs",
"structs",
"=",
"dict",
"(",
")",
"# Holders for the current struct",
"name",
"=",
"None",
"# Iterate over every line in the file",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"str... | 36.554217 | 0.000321 |
def find_command(self, argv):
"""Given an argument list, find a command and
return the processor and any remaining arguments.
"""
search_args = argv[:]
name = ''
while search_args:
if search_args[0].startswith('-'):
name = '%s %s' % (name, sear... | [
"def",
"find_command",
"(",
"self",
",",
"argv",
")",
":",
"search_args",
"=",
"argv",
"[",
":",
"]",
"name",
"=",
"''",
"while",
"search_args",
":",
"if",
"search_args",
"[",
"0",
"]",
".",
"startswith",
"(",
"'-'",
")",
":",
"name",
"=",
"'%s %s'",... | 44.37037 | 0.001634 |
def xmoe2_dense(sz):
"""Series of architectural experiments on language modeling.
Larger models than the ones above.
All models are trained on sequences of 1024 tokens.
We assume infinite training data, so no dropout necessary.
We process 2^36 tokens in training = 524288 steps at batch size 128
TODO(noa... | [
"def",
"xmoe2_dense",
"(",
"sz",
")",
":",
"hparams",
"=",
"mtf_transformer",
".",
"mtf_transformer_paper_lm",
"(",
"sz",
")",
"hparams",
".",
"attention_dropout",
"=",
"0.0",
"hparams",
".",
"relu_dropout",
"=",
"0.0",
"hparams",
".",
"layer_prepostprocess_dropou... | 31.027778 | 0.011285 |
def auto_model_name_recognize(model_name):
"""
自动将 site-user 识别成 SiteUser
:param model_name:
:return:
"""
name_list = model_name.split('-')
return ''.join(['%s%s' % (name[0].upper(), name[1:]) for name in name_list]) | [
"def",
"auto_model_name_recognize",
"(",
"model_name",
")",
":",
"name_list",
"=",
"model_name",
".",
"split",
"(",
"'-'",
")",
"return",
"''",
".",
"join",
"(",
"[",
"'%s%s'",
"%",
"(",
"name",
"[",
"0",
"]",
".",
"upper",
"(",
")",
",",
"name",
"["... | 29.625 | 0.008197 |
def get_version(self):
"""Get blink(1) firmware version
"""
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('v'), 0, 0, 0, 0, 0, 0, 0]
self.write(buf)
time.sleep(.05)
version_raw = self.read()
version = (version_raw[3] - ord('0')) * 100 + (version... | [
"def",
"get_version",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''",
"buf",
"=",
"[",
"REPORT_ID",
",",
"ord",
"(",
"'v'",
")",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
... | 35.8 | 0.019074 |
def assign_bus_results(grid, bus_data):
"""
Write results obtained from PF to graph
Parameters
----------
grid: ding0.network
bus_data: pandas.DataFrame
DataFrame containing voltage levels obtained from PF analysis
"""
# iterate of nodes and assign voltage obtained from power f... | [
"def",
"assign_bus_results",
"(",
"grid",
",",
"bus_data",
")",
":",
"# iterate of nodes and assign voltage obtained from power flow analysis",
"for",
"node",
"in",
"grid",
".",
"_graph",
".",
"nodes",
"(",
")",
":",
"# check if node is connected to graph",
"if",
"(",
"... | 42.148148 | 0.000859 |
def simxSetUISlider(clientID, uiHandle, uiButtonID, position, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
return c_SetUISlider(clientID, uiHandle, uiButtonID, position, operationMode) | [
"def",
"simxSetUISlider",
"(",
"clientID",
",",
"uiHandle",
",",
"uiButtonID",
",",
"position",
",",
"operationMode",
")",
":",
"return",
"c_SetUISlider",
"(",
"clientID",
",",
"uiHandle",
",",
"uiButtonID",
",",
"position",
",",
"operationMode",
")"
] | 43.5 | 0.011278 |
def _save(self, name, content):
"""
Saves only when a file with a name and a content is not already uploaded to Cloudinary.
"""
name = self.clean_name(name) # to change to UNIX style path on windows if necessary
if not self._exists_with_etag(name, content):
content.s... | [
"def",
"_save",
"(",
"self",
",",
"name",
",",
"content",
")",
":",
"name",
"=",
"self",
".",
"clean_name",
"(",
"name",
")",
"# to change to UNIX style path on windows if necessary",
"if",
"not",
"self",
".",
"_exists_with_etag",
"(",
"name",
",",
"content",
... | 47.777778 | 0.009132 |
def query(self, body, params=None):
"""
`<Execute SQL>`_
:arg body: Use the `query` element to start a query. Use the `cursor`
element to continue a query.
:arg format: a short version of the Accept header, e.g. json, yaml
"""
if body in SKIP_IN_PATH:
... | [
"def",
"query",
"(",
"self",
",",
"body",
",",
"params",
"=",
"None",
")",
":",
"if",
"body",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(",
"\"Empty value passed for a required argument 'body'.\"",
")",
"return",
"self",
".",
"transport",
".",
"perform_... | 43.090909 | 0.008264 |
def music_info(songid):
"""
Get music info from baidu music api
"""
if isinstance(songid, list):
songid = ','.join(songid)
data = {
"hq": 1,
"songIds": songid
}
res = requests.post(MUSIC_INFO_URL, data=data)
info = res.json()
music_data = info["data"]
son... | [
"def",
"music_info",
"(",
"songid",
")",
":",
"if",
"isinstance",
"(",
"songid",
",",
"list",
")",
":",
"songid",
"=",
"','",
".",
"join",
"(",
"songid",
")",
"data",
"=",
"{",
"\"hq\"",
":",
"1",
",",
"\"songIds\"",
":",
"songid",
"}",
"res",
"=",... | 25.6 | 0.001506 |
def potinf(self, x, y, aq=None):
'''Can be called with only one x,y value'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
rv = np.zeros((self.nparam, aq.naq))
if aq == self.aq:
pot = np.zeros(aq.naq)
pot[:] = self.bessel.potbeslsho(float(x), float(y),... | [
"def",
"potinf",
"(",
"self",
",",
"x",
",",
"y",
",",
"aq",
"=",
"None",
")",
":",
"if",
"aq",
"is",
"None",
":",
"aq",
"=",
"self",
".",
"model",
".",
"aq",
".",
"find_aquifer_data",
"(",
"x",
",",
"y",
")",
"rv",
"=",
"np",
".",
"zeros",
... | 47.1 | 0.008333 |
def find_in_history(self, tocursor, start_idx, backward):
"""Find text 'tocursor' in history, from index 'start_idx'"""
if start_idx is None:
start_idx = len(self.history)
# Finding text in history
step = -1 if backward else 1
idx = start_idx
if len(toc... | [
"def",
"find_in_history",
"(",
"self",
",",
"tocursor",
",",
"start_idx",
",",
"backward",
")",
":",
"if",
"start_idx",
"is",
"None",
":",
"start_idx",
"=",
"len",
"(",
"self",
".",
"history",
")",
"# Finding text in history\r",
"step",
"=",
"-",
"1",
"if"... | 41.26087 | 0.00206 |
def clinsig_query(self, query, mongo_query):
""" Add clinsig filter values to the mongo query object
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is going to be submitted to the database
Return... | [
"def",
"clinsig_query",
"(",
"self",
",",
"query",
",",
"mongo_query",
")",
":",
"LOG",
".",
"debug",
"(",
"'clinsig is a query parameter'",
")",
"trusted_revision_level",
"=",
"[",
"'mult'",
",",
"'single'",
",",
"'exp'",
",",
"'guideline'",
"]",
"rank",
"=",... | 39.206349 | 0.011848 |
def __select_text_under_cursor_blocks(self, cursor):
"""
Selects the document text under cursor blocks.
:param cursor: Cursor.
:type cursor: QTextCursor
"""
start_block = self.document().findBlock(cursor.selectionStart()).firstLineNumber()
end_block = self.docum... | [
"def",
"__select_text_under_cursor_blocks",
"(",
"self",
",",
"cursor",
")",
":",
"start_block",
"=",
"self",
".",
"document",
"(",
")",
".",
"findBlock",
"(",
"cursor",
".",
"selectionStart",
"(",
")",
")",
".",
"firstLineNumber",
"(",
")",
"end_block",
"="... | 50 | 0.008415 |
def data_to_uuid(data):
"""Convert an array of binary data to the iBeacon uuid format."""
string = data_to_hexstring(data)
return string[0:8]+'-'+string[8:12]+'-'+string[12:16]+'-'+string[16:20]+'-'+string[20:32] | [
"def",
"data_to_uuid",
"(",
"data",
")",
":",
"string",
"=",
"data_to_hexstring",
"(",
"data",
")",
"return",
"string",
"[",
"0",
":",
"8",
"]",
"+",
"'-'",
"+",
"string",
"[",
"8",
":",
"12",
"]",
"+",
"'-'",
"+",
"string",
"[",
"12",
":",
"16",... | 55.25 | 0.008929 |
def hash_stream(fileobj, hasher=None, blocksize=65536):
"""Read from fileobj stream, return hash of its contents.
Args:
fileobj: File-like object with read()
hasher: Hash object such as hashlib.sha1(). Defaults to sha1.
blocksize: Read from fileobj this many bytes at a time.
"""
hashe... | [
"def",
"hash_stream",
"(",
"fileobj",
",",
"hasher",
"=",
"None",
",",
"blocksize",
"=",
"65536",
")",
":",
"hasher",
"=",
"hasher",
"or",
"hashlib",
".",
"sha1",
"(",
")",
"buf",
"=",
"fileobj",
".",
"read",
"(",
"blocksize",
")",
"while",
"buf",
":... | 33.357143 | 0.002083 |
def run(self, model_id, name, arguments={}, properties=None):
"""Create a new model run with given name, arguments, and properties.
Parameters
----------
model_id : string
Unique model identifier
name : string
User-defined name for experiment
argum... | [
"def",
"run",
"(",
"self",
",",
"model_id",
",",
"name",
",",
"arguments",
"=",
"{",
"}",
",",
"properties",
"=",
"None",
")",
":",
"return",
"self",
".",
"sco",
".",
"experiments_predictions_create",
"(",
"model_id",
",",
"name",
",",
"self",
".",
"li... | 33.36 | 0.002331 |
def addCorpusId(self, value):
'''Adds SourceId to External_Info
'''
if isinstance(value, Corpus_Id):
self.corpus_ids.append(value)
else:
raise (TypeError,
'source_id Type should be Source_Id, not %s' % type(source_id)) | [
"def",
"addCorpusId",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Corpus_Id",
")",
":",
"self",
".",
"corpus_ids",
".",
"append",
"(",
"value",
")",
"else",
":",
"raise",
"(",
"TypeError",
",",
"'source_id Type should be So... | 35.75 | 0.010239 |
def remove(name=None, pkgs=None, **kwargs):
'''
Remove a package and all its dependencies which are not in use by other
packages.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
... | [
"def",
"remove",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pkg_params",
"=",
"__salt__",
"[",
"'pkg_resource.parse_targets'",
"]",
"(",
"name",
",",
"pkgs",
")",
"[",
"0",
"]",
"except",
"Mini... | 26.380952 | 0.00087 |
def select(*args):
"""Select specific columns from DataFrame.
Output will be DplyFrame type. Order of columns will be the same as input into
select.
>>> diamonds >> select(X.color, X.carat) >> head(3)
Out:
color carat
0 E 0.23
1 E 0.21
2 E 0.23
Grouping variables are implied... | [
"def",
"select",
"(",
"*",
"args",
")",
":",
"def",
"select_columns",
"(",
"df",
",",
"args",
")",
":",
"columns",
"=",
"[",
"column",
".",
"_name",
"for",
"column",
"in",
"args",
"]",
"if",
"df",
".",
"_grouped_on",
":",
"for",
"col",
"in",
"df",
... | 30.366667 | 0.009574 |
def _filter_unique_identities(uidentities, matcher):
"""Filter a set of unique identities.
This function will use the `matcher` to generate a list
of `FilteredIdentity` objects. It will return a tuple
with the list of filtered objects, the unique identities
not filtered and a table mapping uuids wi... | [
"def",
"_filter_unique_identities",
"(",
"uidentities",
",",
"matcher",
")",
":",
"filtered",
"=",
"[",
"]",
"no_filtered",
"=",
"[",
"]",
"uuids",
"=",
"{",
"}",
"for",
"uidentity",
"in",
"uidentities",
":",
"n",
"=",
"len",
"(",
"filtered",
")",
"filte... | 29.043478 | 0.001449 |
def get_tasker2_slabs(self, tol=0.01, same_species_only=True):
"""
Get a list of slabs that have been Tasker 2 corrected.
Args:
tol (float): Tolerance to determine if atoms are within same plane.
This is a fractional tolerance, not an absolute one.
same_s... | [
"def",
"get_tasker2_slabs",
"(",
"self",
",",
"tol",
"=",
"0.01",
",",
"same_species_only",
"=",
"True",
")",
":",
"sites",
"=",
"list",
"(",
"self",
".",
"sites",
")",
"slabs",
"=",
"[",
"]",
"sortedcsites",
"=",
"sorted",
"(",
"sites",
",",
"key",
... | 44.580645 | 0.000708 |
def prior_model_name_prior_tuples_dict(self):
"""
Returns
-------
class_priors_dict: {String: [Prior]}
A dictionary mapping_matrix the names of priors to lists of associated priors
"""
return {name: list(prior_model.prior_tuples) for name, prior_model in self.... | [
"def",
"prior_model_name_prior_tuples_dict",
"(",
"self",
")",
":",
"return",
"{",
"name",
":",
"list",
"(",
"prior_model",
".",
"prior_tuples",
")",
"for",
"name",
",",
"prior_model",
"in",
"self",
".",
"prior_model_tuples",
"}"
] | 41.5 | 0.011799 |
def handle_control(self, req, worker_id, req_info):
"""
Handles a control_request received from a worker.
Returns:
string or dict: response
'stop' - the worker should quit
'wait' - wait for 1 second
'eval' - evaluate on valid and test set to start... | [
"def",
"handle_control",
"(",
"self",
",",
"req",
",",
"worker_id",
",",
"req_info",
")",
":",
"if",
"self",
".",
"start_time",
"is",
"None",
":",
"self",
".",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"response",
"=",
"\"\"",
"if",
"req",
"=... | 46.040816 | 0.002459 |
def proc_image(self, tokens):
""" Returns the components of an image. """
print "IMAGE:", tokens, tokens.asList(), tokens.keys()
raise NotImplementedError | [
"def",
"proc_image",
"(",
"self",
",",
"tokens",
")",
":",
"print",
"\"IMAGE:\"",
",",
"tokens",
",",
"tokens",
".",
"asList",
"(",
")",
",",
"tokens",
".",
"keys",
"(",
")",
"raise",
"NotImplementedError"
] | 29.166667 | 0.011111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.