text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def write_r(df, f, sep=",", index_join="@", columns_join="."):
"""
Export dataframe in a format easily importable to R
Index fields are joined with "@" and column fields by "." by default.
:param df:
:param f:
:param index_join:
:param columns_join:
:return:
"""
df = df.copy()
... | [
"def",
"write_r",
"(",
"df",
",",
"f",
",",
"sep",
"=",
"\",\"",
",",
"index_join",
"=",
"\"@\"",
",",
"columns_join",
"=",
"\".\"",
")",
":",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"df",
".",
"index",
"=",
"[",
"\"@\"",
".",
"join",
"(",
"[",... | 29.75 | 0.002037 |
def extend_results_extrapoling_relations(helper):
"""Try to extract the bigger group of interlinked tokens.
Should generally be used at last in the collectors chain.
"""
if not helper.bucket_dry:
return # No need.
tokens = set(helper.meaningful + helper.common)
for relation in _extract... | [
"def",
"extend_results_extrapoling_relations",
"(",
"helper",
")",
":",
"if",
"not",
"helper",
".",
"bucket_dry",
":",
"return",
"# No need.",
"tokens",
"=",
"set",
"(",
"helper",
".",
"meaningful",
"+",
"helper",
".",
"common",
")",
"for",
"relation",
"in",
... | 36.357143 | 0.001916 |
async def get_object(source, *args):
"""Get object asynchronously.
:param source: mode class or query to get object from
:param args: lookup parameters
:return: model instance or raises ``peewee.DoesNotExist`` if object not
found
"""
warnings.warn("get_object() is deprecated, Manager.ge... | [
"async",
"def",
"get_object",
"(",
"source",
",",
"*",
"args",
")",
":",
"warnings",
".",
"warn",
"(",
"\"get_object() is deprecated, Manager.get() \"",
"\"should be used instead\"",
",",
"DeprecationWarning",
")",
"if",
"isinstance",
"(",
"source",
",",
"peewee",
"... | 28.08 | 0.001377 |
def get_field_info(self, field, field_name):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', Fal... | [
"def",
"get_field_info",
"(",
"self",
",",
"field",
",",
"field_name",
")",
":",
"field_info",
"=",
"OrderedDict",
"(",
")",
"field_info",
"[",
"'type'",
"]",
"=",
"self",
".",
"label_lookup",
"[",
"field",
"]",
"field_info",
"[",
"'required'",
"]",
"=",
... | 39.444444 | 0.001649 |
def EAS2TAS(ARSP,GPS,BARO,ground_temp=25):
'''EAS2TAS from ARSP.Temp'''
tempK = ground_temp + 273.15 - 0.0065 * GPS.Alt
return sqrt(1.225 / (BARO.Press / (287.26 * tempK))) | [
"def",
"EAS2TAS",
"(",
"ARSP",
",",
"GPS",
",",
"BARO",
",",
"ground_temp",
"=",
"25",
")",
":",
"tempK",
"=",
"ground_temp",
"+",
"273.15",
"-",
"0.0065",
"*",
"GPS",
".",
"Alt",
"return",
"sqrt",
"(",
"1.225",
"/",
"(",
"BARO",
".",
"Press",
"/",... | 45.25 | 0.021739 |
def is_balance_proof_usable_onchain(
received_balance_proof: BalanceProofSignedState,
channel_state: NettingChannelState,
sender_state: NettingChannelEndState,
) -> SuccessOrError:
""" Checks the balance proof can be used on-chain.
For a balance proof to be valid it must be newer than t... | [
"def",
"is_balance_proof_usable_onchain",
"(",
"received_balance_proof",
":",
"BalanceProofSignedState",
",",
"channel_state",
":",
"NettingChannelState",
",",
"sender_state",
":",
"NettingChannelEndState",
",",
")",
"->",
"SuccessOrError",
":",
"expected_nonce",
"=",
"get_... | 39.115789 | 0.00105 |
def _initEphemerals(self):
"""
Initialize all ephemeral members after being restored to a pickled state.
"""
## We store the lists of segments updates, per cell, so that they can be
# applied later during learning, when the cell gets bottom-up activation.
# We store one list per cell. The lists ... | [
"def",
"_initEphemerals",
"(",
"self",
")",
":",
"## We store the lists of segments updates, per cell, so that they can be",
"# applied later during learning, when the cell gets bottom-up activation.",
"# We store one list per cell. The lists are identified with a hash key which",
"# is a tuple (c... | 46 | 0.001082 |
def get_single_lab(lab_slug):
"""Gets data from a single lab from makeinitaly.foundation."""
wiki = MediaWiki(makeinitaly__foundation_api_url)
wiki_response = wiki.call(
{'action': 'query',
'titles': lab_slug,
'prop': 'revisions',
'rvprop': 'content'})
# If we don't k... | [
"def",
"get_single_lab",
"(",
"lab_slug",
")",
":",
"wiki",
"=",
"MediaWiki",
"(",
"makeinitaly__foundation_api_url",
")",
"wiki_response",
"=",
"wiki",
".",
"call",
"(",
"{",
"'action'",
":",
"'query'",
",",
"'titles'",
":",
"lab_slug",
",",
"'prop'",
":",
... | 35.581081 | 0.00037 |
def json_request_response(f):
"""
Parse the JSON from an API response. We do this in a decorator so that our
Twisted library can reuse the underlying functions
"""
@wraps(f)
def wrapper(*args, **kwargs):
response = f(*args, **kwargs)
response.raise_for_status()
return jso... | [
"def",
"json_request_response",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"response",
".",
"raise_... | 31 | 0.00241 |
def fetchall(self):
""" returns the remainder of records from the query. This is
guaranteed by locking, so that no other thread can grab a few records
while the set is fetched. This has the side effect that other threads
may have to wait for an arbitrary long time until this query is done
before the... | [
"def",
"fetchall",
"(",
"self",
")",
":",
"self",
".",
"_cursorLock",
".",
"acquire",
"(",
")",
"recs",
"=",
"[",
"]",
"while",
"True",
":",
"rec",
"=",
"self",
".",
"fetchone",
"(",
")",
"if",
"rec",
"is",
"None",
":",
"break",
"recs",
".",
"app... | 32.888889 | 0.026273 |
def autorun_filters(filters, doc, search_dirs, verbose):
"""
:param filters: list of str
:param doc: panflute.Doc
:param search_dirs: list of str
:param verbose: bool
:return: panflute.Doc
"""
def remove_py(s):
return s[:-3] if s.endswith('.py') else s
filter_paths = []
... | [
"def",
"autorun_filters",
"(",
"filters",
",",
"doc",
",",
"search_dirs",
",",
"verbose",
")",
":",
"def",
"remove_py",
"(",
"s",
")",
":",
"return",
"s",
"[",
":",
"-",
"3",
"]",
"if",
"s",
".",
"endswith",
"(",
"'.py'",
")",
"else",
"s",
"filter_... | 39 | 0.002001 |
def flat_map(coro, iterable, limit=0, loop=None, timeout=None,
return_exceptions=False, initializer=None, *args, **kw):
"""
Concurrently iterates values yielded from an iterable, passing them to
an asynchronous coroutine.
This function is the flatten version of to ``paco.map()``.
Mapp... | [
"def",
"flat_map",
"(",
"coro",
",",
"iterable",
",",
"limit",
"=",
"0",
",",
"loop",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"return_exceptions",
"=",
"False",
",",
"initializer",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":"... | 34.586667 | 0.000375 |
def proposal_metrics(iou):
"""
Add summaries for RPN proposals.
Args:
iou: nxm, #proposal x #gt
"""
# find best roi for each gt, for summary only
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
... | [
"def",
"proposal_metrics",
"(",
"iou",
")",
":",
"# find best roi for each gt, for summary only",
"best_iou",
"=",
"tf",
".",
"reduce_max",
"(",
"iou",
",",
"axis",
"=",
"0",
")",
"mean_best_iou",
"=",
"tf",
".",
"reduce_mean",
"(",
"best_iou",
",",
"name",
"=... | 32.421053 | 0.001577 |
def _load_instance(self, instance_id, force_reload=True):
"""
Return instance with the given id.
For performance reasons, the instance ID is first searched for in the
collection of VM instances started by ElastiCluster
(`self._instances`), then in the list of all instances known... | [
"def",
"_load_instance",
"(",
"self",
",",
"instance_id",
",",
"force_reload",
"=",
"True",
")",
":",
"if",
"force_reload",
":",
"try",
":",
"# Remove from cache and get from server again",
"vm",
"=",
"self",
".",
"nova_client",
".",
"servers",
".",
"get",
"(",
... | 42.607843 | 0.0009 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# Extracting dictionary of coefficients specific to required
... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# Extracting dictionary of coefficients specific to required",
"# intensity measure type.",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"... | 34.043478 | 0.002484 |
def to_trajectory(self, show_ports=False, chains=None,
residues=None, box=None):
"""Convert to an md.Trajectory and flatten the compound.
Parameters
----------
show_ports : bool, optional, default=False
Include all port atoms when converting to trajecto... | [
"def",
"to_trajectory",
"(",
"self",
",",
"show_ports",
"=",
"False",
",",
"chains",
"=",
"None",
",",
"residues",
"=",
"None",
",",
"box",
"=",
"None",
")",
":",
"atom_list",
"=",
"[",
"particle",
"for",
"particle",
"in",
"self",
".",
"particles",
"("... | 37.207547 | 0.001482 |
def put(self, items, indexes=True):
'''Adds feature collections to the store.
This efficiently adds multiple FCs to the store. The iterable
of ``items`` given should yield tuples of ``(content_id, FC)``.
:param items: Iterable of ``(content_id, FC)``.
:param [str] feature_names... | [
"def",
"put",
"(",
"self",
",",
"items",
",",
"indexes",
"=",
"True",
")",
":",
"actions",
"=",
"[",
"]",
"for",
"cid",
",",
"fc",
"in",
"items",
":",
"# TODO: If we store features in a columnar order, then we",
"# could tell ES to index the feature values directly. -... | 43.425 | 0.001126 |
def read(scope, filename):
"""
Reads the given file and returns the result.
The result is also stored in the built-in __response__ variable.
:type filename: string
:param filename: A filename.
:rtype: string
:return: The content of the file.
"""
with open(filename[0], 'r') as fp:
... | [
"def",
"read",
"(",
"scope",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
"[",
"0",
"]",
",",
"'r'",
")",
"as",
"fp",
":",
"lines",
"=",
"fp",
".",
"readlines",
"(",
")",
"scope",
".",
"define",
"(",
"__response__",
"=",
"lines",
"... | 27.928571 | 0.002475 |
def proto_0201(theABF):
"""protocol: membrane test."""
abf=ABF(theABF)
abf.log.info("analyzing as a membrane test")
plot=ABFplot(abf)
plot.figure_height,plot.figure_width=SQUARESIZE/2,SQUARESIZE/2
plot.figure_sweeps()
# save it
plt.tight_layout()
frameAndSave(abf,"membrane test")
... | [
"def",
"proto_0201",
"(",
"theABF",
")",
":",
"abf",
"=",
"ABF",
"(",
"theABF",
")",
"abf",
".",
"log",
".",
"info",
"(",
"\"analyzing as a membrane test\"",
")",
"plot",
"=",
"ABFplot",
"(",
"abf",
")",
"plot",
".",
"figure_height",
",",
"plot",
".",
... | 27.25 | 0.02071 |
def evaluate(self, verbose=True, passes=None):
"""Summary
Returns:
TYPE: Description
"""
i = 0
exprs = []
for column_name in self.column_names:
if len(self.column_names) > 1:
index = "1.$%d" % i
else:
in... | [
"def",
"evaluate",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"passes",
"=",
"None",
")",
":",
"i",
"=",
"0",
"exprs",
"=",
"[",
"]",
"for",
"column_name",
"in",
"self",
".",
"column_names",
":",
"if",
"len",
"(",
"self",
".",
"column_names",
"... | 29.465116 | 0.001528 |
def write_sub_file(self):
"""
Write a submit file for this Condor job.
"""
if not self.__log_file:
raise CondorSubmitError, "Log file not specified."
if not self.__err_file:
raise CondorSubmitError, "Error file not specified."
if not self.__out_file:
raise CondorSubmitError, "O... | [
"def",
"write_sub_file",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__log_file",
":",
"raise",
"CondorSubmitError",
",",
"\"Log file not specified.\"",
"if",
"not",
"self",
".",
"__err_file",
":",
"raise",
"CondorSubmitError",
",",
"\"Error file not specified... | 38.584416 | 0.026584 |
def plot(self, fig=None, draw=True):
"""
Plot the filter
Parameters
----------
fig: bokeh.plotting.figure (optional)
A figure to plot on
draw: bool
Draw the figure, else return it
Returns
-------
bokeh.plotting.figure
... | [
"def",
"plot",
"(",
"self",
",",
"fig",
"=",
"None",
",",
"draw",
"=",
"True",
")",
":",
"COLORS",
"=",
"color_gen",
"(",
"'Category10'",
")",
"# Make the figure",
"if",
"fig",
"is",
"None",
":",
"xlab",
"=",
"'Wavelength [{}]'",
".",
"format",
"(",
"s... | 27.236842 | 0.001866 |
def step(self, **args):
"""
Network.step()
Does a single step. Calls propagate(), backprop(), and
change_weights() if learning is set.
Format for parameters: <layer name> = <activation/target list>
"""
if self.verbosity > 0:
print("Network.ste... | [
"def",
"step",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"if",
"self",
".",
"verbosity",
">",
"0",
":",
"print",
"(",
"\"Network.step() called with:\"",
",",
"args",
")",
"# First, copy the values into either activations or targets:",
"retargs",
"=",
"self",
... | 45.382979 | 0.010096 |
def open_file_cont(self, pathspec, loader_cont_fn):
"""Open a file and do some action on it.
Parameters
----------
pathspec : str
The path of the file to load (can be a URI, but must reference
a local file).
loader_cont_fn : func (data_obj) -> None
... | [
"def",
"open_file_cont",
"(",
"self",
",",
"pathspec",
",",
"loader_cont_fn",
")",
":",
"info",
"=",
"iohelper",
".",
"get_fileinfo",
"(",
"pathspec",
")",
"filepath",
"=",
"info",
".",
"filepath",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fil... | 35.967742 | 0.000873 |
def register_actions(self, shortcut_manager):
"""Register callback methods fot triggered actions.
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_fo... | [
"def",
"register_actions",
"(",
"self",
",",
"shortcut_manager",
")",
":",
"shortcut_manager",
".",
"add_callback_for_action",
"(",
"'close'",
",",
"self",
".",
"on_close_shortcut",
")",
"# Call register_action of parent in order to register actions for child controllers",
"sup... | 53.1 | 0.011111 |
def terminate_processes(pid_list):
"""Terminate a list of processes by sending to each of them a SIGTERM signal,
pre-emptively checking if its PID might have been reused.
Parameters
----------
pid_list : list
A list of process identifiers identifying active processes.
"""
... | [
"def",
"terminate_processes",
"(",
"pid_list",
")",
":",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"if",
"proc",
".",
"pid",
"in",
"pid_list",
":",
"proc",
".",
"terminate",
"(",
")"
] | 31.076923 | 0.009615 |
def new_conn(self):
"""
Create a new ConnectionWrapper instance
:return:
"""
"""
:return:
"""
logger.debug("Opening new connection to rethinkdb with args=%s" % self._conn_args)
return ConnectionWrapper(self._pool, **self._conn_args) | [
"def",
"new_conn",
"(",
"self",
")",
":",
"\"\"\"\n :return:\n \"\"\"",
"logger",
".",
"debug",
"(",
"\"Opening new connection to rethinkdb with args=%s\"",
"%",
"self",
".",
"_conn_args",
")",
"return",
"ConnectionWrapper",
"(",
"self",
".",
"_pool",
",",... | 29.5 | 0.009868 |
def rotated_Gamma_ml(m,l,phi1,phi2,theta1,theta2,gamma_ml):
"""
This function takes any gamma in the computational frame and rotates it to the
cosmic frame.
"""
rotated_gamma = 0
for ii in range(2*l+1):
rotated_gamma += Dlmk(l,m,ii-l,phi1,phi2,theta1,theta2).conjugate()*g... | [
"def",
"rotated_Gamma_ml",
"(",
"m",
",",
"l",
",",
"phi1",
",",
"phi2",
",",
"theta1",
",",
"theta2",
",",
"gamma_ml",
")",
":",
"rotated_gamma",
"=",
"0",
"for",
"ii",
"in",
"range",
"(",
"2",
"*",
"l",
"+",
"1",
")",
":",
"rotated_gamma",
"+=",
... | 26.538462 | 0.056022 |
def parse_args():
'''Parse command line arguments'''
parser = argparse.ArgumentParser(
description='Morphology fit distribution extractor',
epilog='Note: Outputs json of the optimal distribution \
and corresponding parameters.')
parser.add_argument('datapaths',
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Morphology fit distribution extractor'",
",",
"epilog",
"=",
"'Note: Outputs json of the optimal distribution \\\n and corresponding parameters.'",
")",... | 37.666667 | 0.001727 |
def filter(self, func):
"""Returns a packet list filtered by a truth function"""
return self.__class__(list(filter(func,self.res)),
name="filtered %s"%self.listname) | [
"def",
"filter",
"(",
"self",
",",
"func",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"list",
"(",
"filter",
"(",
"func",
",",
"self",
".",
"res",
")",
")",
",",
"name",
"=",
"\"filtered %s\"",
"%",
"self",
".",
"listname",
")"
] | 52 | 0.018957 |
def load(cls, stream):
"""Load a serialized version of self from text stream.
Expects the format used by mongooplog.
"""
data = json.load(stream)['ts']
return cls(data['time'], data['inc']) | [
"def",
"load",
"(",
"cls",
",",
"stream",
")",
":",
"data",
"=",
"json",
".",
"load",
"(",
"stream",
")",
"[",
"'ts'",
"]",
"return",
"cls",
"(",
"data",
"[",
"'time'",
"]",
",",
"data",
"[",
"'inc'",
"]",
")"
] | 32 | 0.008696 |
def getServerStates(pbclient=None, dc_id=None, serverid=None, servername=None):
''' gets states of a server'''
if pbclient is None:
raise ValueError("argument 'pbclient' must not be None")
if dc_id is None:
raise ValueError("argument 'dc_id' must not be None")
server = None
if server... | [
"def",
"getServerStates",
"(",
"pbclient",
"=",
"None",
",",
"dc_id",
"=",
"None",
",",
"serverid",
"=",
"None",
",",
"servername",
"=",
"None",
")",
":",
"if",
"pbclient",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"argument 'pbclient' must not be None\... | 44.473684 | 0.001158 |
def authentication(self, event):
"""Links the client to the granted account and profile,
then notifies the client"""
try:
self.log("Authorization has been granted by DB check:",
event.username, lvl=debug)
account, profile, clientconfig = event.userd... | [
"def",
"authentication",
"(",
"self",
",",
"event",
")",
":",
"try",
":",
"self",
".",
"log",
"(",
"\"Authorization has been granted by DB check:\"",
",",
"event",
".",
"username",
",",
"lvl",
"=",
"debug",
")",
"account",
",",
"profile",
",",
"clientconfig",
... | 39.454545 | 0.000749 |
def run_query(self, collection_name, query):
""" method runs query on a specified collection and return a list of filtered Job records """
cursor = self.ds.filter(collection_name, query)
return [Job.from_json(document) for document in cursor] | [
"def",
"run_query",
"(",
"self",
",",
"collection_name",
",",
"query",
")",
":",
"cursor",
"=",
"self",
".",
"ds",
".",
"filter",
"(",
"collection_name",
",",
"query",
")",
"return",
"[",
"Job",
".",
"from_json",
"(",
"document",
")",
"for",
"document",
... | 65.75 | 0.011278 |
def msvc_batch_key(action, env, target, source):
"""
Returns a key to identify unique batches of sources for compilation.
If batching is enabled (via the $MSVC_BATCH setting), then all
target+source pairs that use the same action, defined by the same
environment, and have the same target and source... | [
"def",
"msvc_batch_key",
"(",
"action",
",",
"env",
",",
"target",
",",
"source",
")",
":",
"# Fixing MSVC_BATCH mode. Previous if did not work when MSVC_BATCH",
"# was set to False. This new version should work better.",
"# Note we need to do the env.subst so $MSVC_BATCH can be a refere... | 42.25 | 0.002479 |
def spectrogram(samples, fft_length=256, sample_rate=2, hop_length=128):
"""
Compute the spectrogram for a real signal.
The parameters follow the naming convention of
matplotlib.mlab.specgram
Args:
samples (1D array): input audio signal
fft_length (int): number of elements in fft win... | [
"def",
"spectrogram",
"(",
"samples",
",",
"fft_length",
"=",
"256",
",",
"sample_rate",
"=",
"2",
",",
"hop_length",
"=",
"128",
")",
":",
"assert",
"not",
"np",
".",
"iscomplexobj",
"(",
"samples",
")",
",",
"\"Must not pass in complex numbers\"",
"window",
... | 38.557692 | 0.000973 |
def index(objects, attr):
"""
Generate a mapping of a list of objects indexed by the given attr.
Parameters
----------
objects : :class:`list`, iterable
attr : string
The attribute to index the list of objects by
Returns
-------
dictionary : dict
keys are the value ... | [
"def",
"index",
"(",
"objects",
",",
"attr",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"return",
"{",
"getattr",
"(",
"obj",
",",
"attr",
")",
":",
"obj",
"for",
"obj",
... | 24.6 | 0.000978 |
def remove_index(self):
"""Remove Elasticsearch index associated to the campaign"""
self.index_client.close(self.index_name)
self.index_client.delete(self.index_name) | [
"def",
"remove_index",
"(",
"self",
")",
":",
"self",
".",
"index_client",
".",
"close",
"(",
"self",
".",
"index_name",
")",
"self",
".",
"index_client",
".",
"delete",
"(",
"self",
".",
"index_name",
")"
] | 46.75 | 0.010526 |
def make_primitive(cas_coords, window_length=3):
"""Calculates running average of cas_coords with a fixed averaging window_length.
Parameters
----------
cas_coords : list(numpy.array or float or tuple)
Each element of the list must have length 3.
window_length : int, optional
The nu... | [
"def",
"make_primitive",
"(",
"cas_coords",
",",
"window_length",
"=",
"3",
")",
":",
"if",
"len",
"(",
"cas_coords",
")",
">=",
"window_length",
":",
"primitive",
"=",
"[",
"]",
"count",
"=",
"0",
"for",
"_",
"in",
"cas_coords",
"[",
":",
"-",
"(",
... | 34.513514 | 0.002285 |
def _iter_channels(framefile):
"""Yields the name and type of each channel in a GWF file TOC
**Requires:** |LDAStools.frameCPP|_
Parameters
----------
framefile : `str`, `LDAStools.frameCPP.IFrameFStream`
path of GWF file, or open file stream, to read
"""
from LDAStools import fram... | [
"def",
"_iter_channels",
"(",
"framefile",
")",
":",
"from",
"LDAStools",
"import",
"frameCPP",
"if",
"not",
"isinstance",
"(",
"framefile",
",",
"frameCPP",
".",
"IFrameFStream",
")",
":",
"framefile",
"=",
"open_gwf",
"(",
"framefile",
",",
"'r'",
")",
"to... | 33.833333 | 0.001597 |
def sizeClassifier(path, min_size=DEFAULTS['min_size']):
"""Sort a file into a group based on on-disk size.
:param paths: See :func:`fastdupes.groupify`
:param min_size: Files smaller than this size (in bytes) will be ignored.
:type min_size: :class:`__builtins__.int`
:returns: See :func:`fastdup... | [
"def",
"sizeClassifier",
"(",
"path",
",",
"min_size",
"=",
"DEFAULTS",
"[",
"'min_size'",
"]",
")",
":",
"filestat",
"=",
"_stat",
"(",
"path",
")",
"if",
"stat",
".",
"S_ISLNK",
"(",
"filestat",
".",
"st_mode",
")",
":",
"return",
"# Skip symlinks.",
"... | 32.681818 | 0.001351 |
def state(self):
""" Describe the state of a Job.
Returns: A string describing the job's state.
"""
state = 'in progress'
if self.is_complete:
if self.failed:
state = 'failed with error: %s' % str(self._fatal_error)
elif self._errors:
state = 'completed with some non-fat... | [
"def",
"state",
"(",
"self",
")",
":",
"state",
"=",
"'in progress'",
"if",
"self",
".",
"is_complete",
":",
"if",
"self",
".",
"failed",
":",
"state",
"=",
"'failed with error: %s'",
"%",
"str",
"(",
"self",
".",
"_fatal_error",
")",
"elif",
"self",
"."... | 26.714286 | 0.010336 |
def begin(self, total: int, name=None, message=None):
"""Call before starting work on a monitor, specifying name and amount of work"""
self.total = total
message = message or name or "Working..."
self.name = name or "ProgressMonitor"
self.update(0, message) | [
"def",
"begin",
"(",
"self",
",",
"total",
":",
"int",
",",
"name",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"self",
".",
"total",
"=",
"total",
"message",
"=",
"message",
"or",
"name",
"or",
"\"Working...\"",
"self",
".",
"name",
"=",
"... | 48.666667 | 0.010101 |
def element(self):
"""Pymatgen :class:`Element`."""
try:
return Element.from_Z(self.Z)
except (KeyError, IndexError):
return Element.from_Z(int(self.Z)) | [
"def",
"element",
"(",
"self",
")",
":",
"try",
":",
"return",
"Element",
".",
"from_Z",
"(",
"self",
".",
"Z",
")",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"return",
"Element",
".",
"from_Z",
"(",
"int",
"(",
"self",
".",
"Z",
")",... | 32.5 | 0.01 |
def save( self ):
"""
Saves the values from the editor to the system.
"""
schema = self.schema()
if ( not schema ):
self.saved.emit()
return
record = self.record()
if not record:
record = self._model()
... | [
"def",
"save",
"(",
"self",
")",
":",
"schema",
"=",
"self",
".",
"schema",
"(",
")",
"if",
"(",
"not",
"schema",
")",
":",
"self",
".",
"saved",
".",
"emit",
"(",
")",
"return",
"record",
"=",
"self",
".",
"record",
"(",
")",
"if",
"not",
"rec... | 36 | 0.018753 |
def clean_text_by_word(text, language="english", deacc=False, additional_stopwords=None):
""" Tokenizes a given text into words, applying filters and lemmatizing them.
Returns a dict of word -> syntacticUnit. """
init_textcleanner(language, additional_stopwords)
text_without_acronyms = replace_with_sepa... | [
"def",
"clean_text_by_word",
"(",
"text",
",",
"language",
"=",
"\"english\"",
",",
"deacc",
"=",
"False",
",",
"additional_stopwords",
"=",
"None",
")",
":",
"init_textcleanner",
"(",
"language",
",",
"additional_stopwords",
")",
"text_without_acronyms",
"=",
"re... | 57.692308 | 0.011811 |
def receive_id_from_server(self):
"""
Listen for an id from the server.
At the beginning of a game, each client receives an IdFactory from the
server. This factory are used to give id numbers that are guaranteed
to be unique to tokens that created locally. This method checks... | [
"def",
"receive_id_from_server",
"(",
"self",
")",
":",
"for",
"message",
"in",
"self",
".",
"pipe",
".",
"receive",
"(",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"IdFactory",
")",
":",
"self",
".",
"actor_id_factory",
"=",
"message",
"return",
... | 45.941176 | 0.011292 |
def do_POST(self):
"""Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
"""
# Check that the path is legal
if not self.is_rpc_path_valid():
self.re... | [
"def",
"do_POST",
"(",
"self",
")",
":",
"# Check that the path is legal",
"if",
"not",
"self",
".",
"is_rpc_path_valid",
"(",
")",
":",
"self",
".",
"report_404",
"(",
")",
"return",
"try",
":",
"# Get arguments by reading body of request.",
"# We read this in chunks... | 42.071429 | 0.001659 |
def parse(self):
"""Generate a argparse parser and parse the command-line arguments"""
if self.parser is None:
self.makeParser()
self.args = self.parser.parse_args()
self.verbose = self.args.verbose | [
"def",
"parse",
"(",
"self",
")",
":",
"if",
"self",
".",
"parser",
"is",
"None",
":",
"self",
".",
"makeParser",
"(",
")",
"self",
".",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
")",
"self",
".",
"verbose",
"=",
"self",
".",
"a... | 39.5 | 0.008264 |
def get_alias(cls):
"""Returns messenger alias.
:return: str
:rtype: str
"""
if cls.alias is None:
cls.alias = cls.__name__
return cls.alias | [
"def",
"get_alias",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"alias",
"is",
"None",
":",
"cls",
".",
"alias",
"=",
"cls",
".",
"__name__",
"return",
"cls",
".",
"alias"
] | 21.444444 | 0.00995 |
def _google_v2_parse_arguments(args):
"""Validated google-v2 arguments."""
if (args.zones and args.regions) or (not args.zones and not args.regions):
raise ValueError('Exactly one of --regions and --zones must be specified')
if args.machine_type and (args.min_cores or args.min_ram):
raise ValueError(
... | [
"def",
"_google_v2_parse_arguments",
"(",
"args",
")",
":",
"if",
"(",
"args",
".",
"zones",
"and",
"args",
".",
"regions",
")",
"or",
"(",
"not",
"args",
".",
"zones",
"and",
"not",
"args",
".",
"regions",
")",
":",
"raise",
"ValueError",
"(",
"'Exact... | 48.625 | 0.010101 |
def handler(self):
"""gets the security handler for the class"""
if hasNTLM:
if self._handler is None:
passman = request.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, self._parsed_org_url, self._login_username, self._password)
se... | [
"def",
"handler",
"(",
"self",
")",
":",
"if",
"hasNTLM",
":",
"if",
"self",
".",
"_handler",
"is",
"None",
":",
"passman",
"=",
"request",
".",
"HTTPPasswordMgrWithDefaultRealm",
"(",
")",
"passman",
".",
"add_password",
"(",
"None",
",",
"self",
".",
"... | 48 | 0.00818 |
def _parse_programs(self, string, parent, filepath=None):
"""Extracts a PROGRAM from the specified fortran code file."""
#First, get hold of the docstrings for all the modules so that we can
#attach them as we parse them.
moddocs = self.docparser.parse_docs(string)
#Now look for... | [
"def",
"_parse_programs",
"(",
"self",
",",
"string",
",",
"parent",
",",
"filepath",
"=",
"None",
")",
":",
"#First, get hold of the docstrings for all the modules so that we can",
"#attach them as we parse them.",
"moddocs",
"=",
"self",
".",
"docparser",
".",
"parse_d... | 59.210526 | 0.010499 |
def _extract_device_name_from_event(event):
"""Extract device name from a tf.Event proto carrying tensor value."""
plugin_data_content = json.loads(
tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content))
return plugin_data_content['device'] | [
"def",
"_extract_device_name_from_event",
"(",
"event",
")",
":",
"plugin_data_content",
"=",
"json",
".",
"loads",
"(",
"tf",
".",
"compat",
".",
"as_str",
"(",
"event",
".",
"summary",
".",
"value",
"[",
"0",
"]",
".",
"metadata",
".",
"plugin_data",
"."... | 52.8 | 0.014925 |
def _write(self, _new=False):
"""Writes the values of the attributes to the datastore.
This method also creates the indices and saves the lists
associated to the object.
"""
pipeline = self.db.pipeline()
self._create_membership(pipeline)
self._update_indices(pipe... | [
"def",
"_write",
"(",
"self",
",",
"_new",
"=",
"False",
")",
":",
"pipeline",
"=",
"self",
".",
"db",
".",
"pipeline",
"(",
")",
"self",
".",
"_create_membership",
"(",
"pipeline",
")",
"self",
".",
"_update_indices",
"(",
"pipeline",
")",
"h",
"=",
... | 36.156863 | 0.001584 |
async def install_update(filename, loop):
"""
Install the update into the system environment.
"""
log.info("Installing update server into system environment")
log.debug('File {} exists? {}'.format(filename, os.path.exists(filename)))
out, err, returncode = await _install(sys.executable, filename... | [
"async",
"def",
"install_update",
"(",
"filename",
",",
"loop",
")",
":",
"log",
".",
"info",
"(",
"\"Installing update server into system environment\"",
")",
"log",
".",
"debug",
"(",
"'File {} exists? {}'",
".",
"format",
"(",
"filename",
",",
"os",
".",
"pat... | 35.461538 | 0.002114 |
def hascurrent(self, allowempty=False):
"""Does the correction record the current authoritative annotation (needed only in a structural context when suggestions are proposed)"""
for e in self.select(Current,None,False, False):
if not allowempty and len(e) == 0: continue
return Tr... | [
"def",
"hascurrent",
"(",
"self",
",",
"allowempty",
"=",
"False",
")",
":",
"for",
"e",
"in",
"self",
".",
"select",
"(",
"Current",
",",
"None",
",",
"False",
",",
"False",
")",
":",
"if",
"not",
"allowempty",
"and",
"len",
"(",
"e",
")",
"==",
... | 56.333333 | 0.017493 |
def computed_fitting_parameters(self):
"""
A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`,
but in each dictionary, the key `value` is added with the fitted value of the quantity.
The reported value is scaled by the inverse prefix.
"""
fit... | [
"def",
"computed_fitting_parameters",
"(",
"self",
")",
":",
"fitted_parameters",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"v",
")",
"in",
"enumerate",
"(",
"self",
".",
"fitting_parameters",
")",
":",
"param",
"=",
"v",
".",
"copy",
"(",
")",
"param",
"["... | 44.307692 | 0.008503 |
def _finish_disconnection_action(self, action):
"""Finish a disconnection attempt
There are two possible outcomes:
- if we were successful at disconnecting, we transition to disconnected
- if we failed at disconnecting, we transition back to idle
Args:
action (Conne... | [
"def",
"_finish_disconnection_action",
"(",
"self",
",",
"action",
")",
":",
"success",
"=",
"action",
".",
"data",
"[",
"'success'",
"]",
"conn_key",
"=",
"action",
".",
"data",
"[",
"'id'",
"]",
"if",
"self",
".",
"_get_connection_state",
"(",
"conn_key",
... | 37.511628 | 0.001813 |
def check_required_params(self):
""" Check if all required parameters are set"""
for param in self.REQUIRED_FIELDS:
if param not in self.params:
raise ValidationError("Missing parameter: {}".format(param)) | [
"def",
"check_required_params",
"(",
"self",
")",
":",
"for",
"param",
"in",
"self",
".",
"REQUIRED_FIELDS",
":",
"if",
"param",
"not",
"in",
"self",
".",
"params",
":",
"raise",
"ValidationError",
"(",
"\"Missing parameter: {}\"",
".",
"format",
"(",
"param",... | 49 | 0.008032 |
def _variable_type_to_read_fn(vartype, records):
"""Convert variant types into corresponding WDL standard library functions.
"""
fn_map = {"String": "read_string", "Array[String]": "read_lines",
"Array[Array[String]]": "read_tsv",
"Object": "read_object", "Array[Object]": "read_o... | [
"def",
"_variable_type_to_read_fn",
"(",
"vartype",
",",
"records",
")",
":",
"fn_map",
"=",
"{",
"\"String\"",
":",
"\"read_string\"",
",",
"\"Array[String]\"",
":",
"\"read_lines\"",
",",
"\"Array[Array[String]]\"",
":",
"\"read_tsv\"",
",",
"\"Object\"",
":",
"\"... | 49.5 | 0.001101 |
def _post_run_hook(self, runtime):
''' generates a report showing nine slices, three per axis, of an
arbitrary volume of `in_files`, with the resulting segmentation
overlaid '''
self._anat_file = self.inputs.in_files[0]
outputs = self.aggregate_outputs(runtime=runtime)
se... | [
"def",
"_post_run_hook",
"(",
"self",
",",
"runtime",
")",
":",
"self",
".",
"_anat_file",
"=",
"self",
".",
"inputs",
".",
"in_files",
"[",
"0",
"]",
"outputs",
"=",
"self",
".",
"aggregate_outputs",
"(",
"runtime",
"=",
"runtime",
")",
"self",
".",
"... | 48.947368 | 0.00211 |
def svd(a, i=None) -> tuple:
"""Singular Value Decomposition.
Factors the matrix `a` as ``u * np.diag(s) * v``, where `u` and `v`
are unitary and `s` is a 1D array of `a`'s singular values.
Parameters
----------
a : array_like
Input array.
i : int or slice (optional)
What s... | [
"def",
"svd",
"(",
"a",
",",
"i",
"=",
"None",
")",
"->",
"tuple",
":",
"u",
",",
"s",
",",
"v",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"a",
",",
"full_matrices",
"=",
"False",
",",
"compute_uv",
"=",
"True",
")",
"u",
"=",
"u",
".",
"T... | 25.64 | 0.001504 |
def seqres_lines(self):
"""Generate SEQRES lines representing the contents"""
lines = []
for chain in self.keys():
seq = self[chain]
serNum = 1
startidx = 0
while startidx < len(seq):
endidx = min(startidx+13, len(seq))
lines += ["SEQRES %2i %s %4i %s\n" % (se... | [
"def",
"seqres_lines",
"(",
"self",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"chain",
"in",
"self",
".",
"keys",
"(",
")",
":",
"seq",
"=",
"self",
"[",
"chain",
"]",
"serNum",
"=",
"1",
"startidx",
"=",
"0",
"while",
"startidx",
"<",
"len",
"(",... | 26.5625 | 0.020455 |
def dev_ij(i,j,traj_exp,adj_mat): #takes adjacency matrix and raw expression data
'''
Function returns the sum of squared differences in the expression of a gene, per cell
:param i: int representing the index of the cell being processed
:param j: int representing the index of the gene being processed
... | [
"def",
"dev_ij",
"(",
"i",
",",
"j",
",",
"traj_exp",
",",
"adj_mat",
")",
":",
"#takes adjacency matrix and raw expression data",
"t",
"=",
"np",
".",
"asmatrix",
"(",
"traj_exp",
")",
"wh",
"=",
"np",
".",
"where",
"(",
"adj_mat",
"[",
"i",
"]",
">",
... | 57.833333 | 0.028369 |
def get_alert_version(self, id, version, **kwargs): # noqa: E501
"""Get a specific historical version of a specific alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> t... | [
"def",
"get_alert_version",
"(",
"self",
",",
"id",
",",
"version",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
... | 43.681818 | 0.002037 |
def BE_vs_clean_SE(self, delu_dict, delu_default=0, plot_eads=False,
annotate_monolayer=True, JPERM2=False):
"""
For each facet, plot the clean surface energy against the most
stable binding energy.
Args:
delu_dict (Dict): Dictionary of the chemical... | [
"def",
"BE_vs_clean_SE",
"(",
"self",
",",
"delu_dict",
",",
"delu_default",
"=",
"0",
",",
"plot_eads",
"=",
"False",
",",
"annotate_monolayer",
"=",
"True",
",",
"JPERM2",
"=",
"False",
")",
":",
"plt",
"=",
"pretty_plot",
"(",
"width",
"=",
"8",
",",
... | 49.191489 | 0.00212 |
def get_noconflict_metaclass(bases, left_metas, right_metas):
"""
Not intended to be used outside of this module, unless you know what you are doing.
"""
# make tuple of needed metaclasses in specified priority order
metas = left_metas + tuple(map(type, bases)) + right_metas
needed_metas = remov... | [
"def",
"get_noconflict_metaclass",
"(",
"bases",
",",
"left_metas",
",",
"right_metas",
")",
":",
"# make tuple of needed metaclasses in specified priority order",
"metas",
"=",
"left_metas",
"+",
"tuple",
"(",
"map",
"(",
"type",
",",
"bases",
")",
")",
"+",
"right... | 45.958333 | 0.001776 |
def preprocess_D_segs(self, generative_model, genomic_data):
"""Process P(delDl, delDr|D) into Pi arrays.
Sets the attributes PD_nt_pos_vec, PD_2nd_nt_pos_per_aa_vec,
min_delDl_given_DdelDr, max_delDl_given_DdelDr, and zeroD_given_D.
Parameters
----------
g... | [
"def",
"preprocess_D_segs",
"(",
"self",
",",
"generative_model",
",",
"genomic_data",
")",
":",
"cutD_genomic_CDR3_segs",
"=",
"genomic_data",
".",
"cutD_genomic_CDR3_segs",
"nt2num",
"=",
"{",
"'A'",
":",
"0",
",",
"'C'",
":",
"1",
",",
"'G'",
":",
"2",
",... | 49.683544 | 0.008743 |
def history(self, period="1mo", interval="1d",
start=None, end=None, prepost=False,
actions=True, auto_adjust=True):
"""
:Parameters:
period : str
Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
Either Use period parameter... | [
"def",
"history",
"(",
"self",
",",
"period",
"=",
"\"1mo\"",
",",
"interval",
"=",
"\"1d\"",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"prepost",
"=",
"False",
",",
"actions",
"=",
"True",
",",
"auto_adjust",
"=",
"True",
")",
":",
... | 36.286885 | 0.00088 |
def ipv4_reassembly(packet, *, count=NotImplemented):
"""Make data for IPv4 reassembly."""
ipv4 = getattr(packet, 'ip', None)
if ipv4 is not None:
if ipv4.df: # dismiss not fragmented packet
return False, None
data = dict(
bufid=(
ipaddress.ip_addr... | [
"def",
"ipv4_reassembly",
"(",
"packet",
",",
"*",
",",
"count",
"=",
"NotImplemented",
")",
":",
"ipv4",
"=",
"getattr",
"(",
"packet",
",",
"'ip'",
",",
"None",
")",
"if",
"ipv4",
"is",
"not",
"None",
":",
"if",
"ipv4",
".",
"df",
":",
"# dismiss n... | 57.043478 | 0.008996 |
def levinson_1d(r, order):
"""Levinson-Durbin recursion, to efficiently solve symmetric linear systems
with toeplitz structure.
Parameters
---------
r : array-like
input array to invert (since the matrix is symmetric Toeplitz, the
corresponding pxp matrix is defined by p items only)... | [
"def",
"levinson_1d",
"(",
"r",
",",
"order",
")",
":",
"r",
"=",
"np",
".",
"atleast_1d",
"(",
"r",
")",
"if",
"r",
".",
"ndim",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Only rank 1 are supported for now.\"",
")",
"n",
"=",
"r",
".",
"size",
"i... | 30.128571 | 0.000459 |
def register_trigger(when=None, when_not=None, set_flag=None, clear_flag=None):
"""
Register a trigger to set or clear a flag when a given flag is set.
Note: Flag triggers are handled at the same time that the given flag is set.
:param str when: Flag to trigger on when it is set.
:param str when_n... | [
"def",
"register_trigger",
"(",
"when",
"=",
"None",
",",
"when_not",
"=",
"None",
",",
"set_flag",
"=",
"None",
",",
"clear_flag",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"(",
"when",
",",
"when_not",
")",
")",
":",
"raise",
"ValueError",
"(... | 48.115385 | 0.002351 |
def bulkBatch(symbols, fields=None, range_='1m', last=10, token='', version=''):
'''Optimized batch to fetch as much as possible at once
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ (s... | [
"def",
"bulkBatch",
"(",
"symbols",
",",
"fields",
"=",
"None",
",",
"range_",
"=",
"'1m'",
",",
"last",
"=",
"10",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"fields",
"=",
"fields",
"or",
"_BATCH_TYPES",
"args",
"=",
"[",
"]",
... | 27.340426 | 0.001503 |
def _offset_format_timestamp1(src_tstamp_str, src_format, dst_format,
ignore_unparsable_time=True, context=None):
"""
Convert a source timeStamp string into a destination timeStamp string,
attempting to apply the correct offset if both the server and local
timeZone are reco... | [
"def",
"_offset_format_timestamp1",
"(",
"src_tstamp_str",
",",
"src_format",
",",
"dst_format",
",",
"ignore_unparsable_time",
"=",
"True",
",",
"context",
"=",
"None",
")",
":",
"if",
"not",
"src_tstamp_str",
":",
"return",
"False",
"res",
"=",
"src_tstamp_str",... | 48.173913 | 0.000442 |
def create_factories(fs_provider, task_problem_types, hook_manager=None, course_class=Course, task_class=Task):
"""
Shorthand for creating Factories
:param fs_provider: A FileSystemProvider leading to the courses
:param hook_manager: an Hook Manager instance. If None, a new Hook Manager is created
:... | [
"def",
"create_factories",
"(",
"fs_provider",
",",
"task_problem_types",
",",
"hook_manager",
"=",
"None",
",",
"course_class",
"=",
"Course",
",",
"task_class",
"=",
"Task",
")",
":",
"if",
"hook_manager",
"is",
"None",
":",
"hook_manager",
"=",
"HookManager",... | 51.214286 | 0.008219 |
def get_operations(self,
indices: Sequence[LogicalIndex],
qubits: Sequence[ops.Qid]
) -> ops.OP_TREE:
"""Gets the logical operations to apply to qubits.""" | [
"def",
"get_operations",
"(",
"self",
",",
"indices",
":",
"Sequence",
"[",
"LogicalIndex",
"]",
",",
"qubits",
":",
"Sequence",
"[",
"ops",
".",
"Qid",
"]",
")",
"->",
"ops",
".",
"OP_TREE",
":"
] | 45.6 | 0.021552 |
def load_rv_data(filename, indep, dep, indweight=None, dir='./'):
"""
load dictionary with rv data.
"""
if '/' in filename:
path, filename = os.path.split(filename)
else:
path = dir
load_file = os.path.join(path, filename)
rvdata = np.loadtxt(load_file)
d ={}
d['p... | [
"def",
"load_rv_data",
"(",
"filename",
",",
"indep",
",",
"dep",
",",
"indweight",
"=",
"None",
",",
"dir",
"=",
"'./'",
")",
":",
"if",
"'/'",
"in",
"filename",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
... | 29.176471 | 0.010732 |
def check_valid(self, get_params):
"""
see if the if condition for a block is valid
"""
if self.commands._if:
return self.commands._if.check_valid(get_params) | [
"def",
"check_valid",
"(",
"self",
",",
"get_params",
")",
":",
"if",
"self",
".",
"commands",
".",
"_if",
":",
"return",
"self",
".",
"commands",
".",
"_if",
".",
"check_valid",
"(",
"get_params",
")"
] | 32.833333 | 0.009901 |
def urls(order_by: Optional[str] = None):
"""List all URLs registered with the app."""
url_rules: List[Rule] = current_app.url_map._rules
# sort the rules. by default they're sorted by priority,
# ie in the order they were registered with the app
if order_by == 'view':
url_rules = sorted(ur... | [
"def",
"urls",
"(",
"order_by",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"url_rules",
":",
"List",
"[",
"Rule",
"]",
"=",
"current_app",
".",
"url_map",
".",
"_rules",
"# sort the rules. by default they're sorted by priority,",
"# ie in the order t... | 46.545455 | 0.001914 |
def _add_node(self, node, depth):
"""Add a node to the graph, and the stack."""
self._topmost_node.add_child(node, bool(depth[1]))
self._stack.append((depth, node)) | [
"def",
"_add_node",
"(",
"self",
",",
"node",
",",
"depth",
")",
":",
"self",
".",
"_topmost_node",
".",
"add_child",
"(",
"node",
",",
"bool",
"(",
"depth",
"[",
"1",
"]",
")",
")",
"self",
".",
"_stack",
".",
"append",
"(",
"(",
"depth",
",",
"... | 46.25 | 0.010638 |
def getShare(self, shareID):
"""
Retrieve a proxy object for a given shareID, previously shared with
this role or one of its group roles via L{Role.shareItem}.
@return: a L{SharedProxy}. This is a wrapper around the shared item
which only exposes those interfaces explicitly all... | [
"def",
"getShare",
"(",
"self",
",",
"shareID",
")",
":",
"shares",
"=",
"list",
"(",
"self",
".",
"store",
".",
"query",
"(",
"Share",
",",
"AND",
"(",
"Share",
".",
"shareID",
"==",
"shareID",
",",
"Share",
".",
"sharedTo",
".",
"oneOf",
"(",
"se... | 38.583333 | 0.002107 |
def get_variant_genotypes(self, variant):
"""Get the genotypes from a well formed variant instance.
Args:
marker (Variant): A Variant instance.
Returns:
A list of Genotypes instance containing a pointer to the variant as
well as a vector of encoded genotypes... | [
"def",
"get_variant_genotypes",
"(",
"self",
",",
"variant",
")",
":",
"# Find the variant in the bim.",
"try",
":",
"plink_chrom",
"=",
"CHROM_STR_TO_INT",
"[",
"variant",
".",
"chrom",
".",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\... | 29.789474 | 0.001711 |
def merge(constraints):
"""Merge ``constraints``.
It removes dupplicate, pruned and merged constraints.
:param constraints: Current constraints.
:type constraints: Iterable of :class:`.Constraint` objects.
:rtype: :func:`list` of :class:`.Constraint` objects.
:raises: :exc:`.ExclusiveConstrain... | [
"def",
"merge",
"(",
"constraints",
")",
":",
"# Dictionary :class:`Operator`: set of :class:`Version`.",
"operators",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"constraint",
"in",
"constraints",
":",
"operators",
"[",
"constraint",
".",
"operator",
"]",
".",
"add... | 36.706897 | 0.000229 |
def get_cloudformation_client(service_name, environment_name):
"""
Given a service name and an environment name, return a boto CloudFormation
client object.
"""
region = service_registry.service_region(service_name)
if whereami() == 'ec2':
profile = None
else:
profile = get_... | [
"def",
"get_cloudformation_client",
"(",
"service_name",
",",
"environment_name",
")",
":",
"region",
"=",
"service_registry",
".",
"service_region",
"(",
"service_name",
")",
"if",
"whereami",
"(",
")",
"==",
"'ec2'",
":",
"profile",
"=",
"None",
"else",
":",
... | 31.714286 | 0.002188 |
def to_bool(self, value):
""" Converts a sheet string value to a boolean value.
Needed because of utf-8 conversions
"""
try:
value = value.lower()
except:
pass
try:
value = value.encode('utf-8')
except:
pass
... | [
"def",
"to_bool",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"except",
":",
"pass",
"try",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"except",
":",
"pass",
"try",
":",
"va... | 22.333333 | 0.010225 |
def delete(gandi, domain, zone_id, name, type, value):
"""Delete a record entry for a domain"""
if not zone_id:
result = gandi.domain.info(domain)
zone_id = result['zone_id']
if not zone_id:
gandi.echo('No zone records found, domain %s doesn\'t seems to be '
'mana... | [
"def",
"delete",
"(",
"gandi",
",",
"domain",
",",
"zone_id",
",",
"name",
",",
"type",
",",
"value",
")",
":",
"if",
"not",
"zone_id",
":",
"result",
"=",
"gandi",
".",
"domain",
".",
"info",
"(",
"domain",
")",
"zone_id",
"=",
"result",
"[",
"'zo... | 41.55 | 0.001176 |
def cache_last_modified(request, *argz, **kwz):
'''Last modification date for a cached page.
Intended for usage in conditional views (@condition decorator).'''
response, site, cachekey = kwz.get('_view_data') or initview(request)
if not response: return None
return response[1] | [
"def",
"cache_last_modified",
"(",
"request",
",",
"*",
"argz",
",",
"*",
"*",
"kwz",
")",
":",
"response",
",",
"site",
",",
"cachekey",
"=",
"kwz",
".",
"get",
"(",
"'_view_data'",
")",
"or",
"initview",
"(",
"request",
")",
"if",
"not",
"response",
... | 46.333333 | 0.024735 |
def iri_to_str(self, iri_: ShExDocParser.IriContext) -> str:
""" iri: IRIREF | prefixedName
"""
if iri_.IRIREF():
return self.iriref_to_str(iri_.IRIREF())
else:
return self.prefixedname_to_str(iri_.prefixedName()) | [
"def",
"iri_to_str",
"(",
"self",
",",
"iri_",
":",
"ShExDocParser",
".",
"IriContext",
")",
"->",
"str",
":",
"if",
"iri_",
".",
"IRIREF",
"(",
")",
":",
"return",
"self",
".",
"iriref_to_str",
"(",
"iri_",
".",
"IRIREF",
"(",
")",
")",
"else",
":",... | 37.714286 | 0.011111 |
def _get_edge_date(self, date_field, sort):
'''
This method is used to get start and end dates for the collection.
'''
return self._source.query(self._source_coll, {
'q':'*:*',
'rows':1,
'fq':'+{}:*'.format(date_field),
... | [
"def",
"_get_edge_date",
"(",
"self",
",",
"date_field",
",",
"sort",
")",
":",
"return",
"self",
".",
"_source",
".",
"query",
"(",
"self",
".",
"_source_coll",
",",
"{",
"'q'",
":",
"'*:*'",
",",
"'rows'",
":",
"1",
",",
"'fq'",
":",
"'+{}:*'",
"."... | 41.888889 | 0.015584 |
def RNN_step(weights, gates):
"""Create a step model for an RNN, given weights and gates functions."""
def rnn_step_fwd(prevstate_inputs, drop=0.0):
prevstate, inputs = prevstate_inputs
cell_tm1, hidden_tm1 = prevstate
acts, bp_acts = weights.begin_update((inputs, hidden_tm1), drop=dro... | [
"def",
"RNN_step",
"(",
"weights",
",",
"gates",
")",
":",
"def",
"rnn_step_fwd",
"(",
"prevstate_inputs",
",",
"drop",
"=",
"0.0",
")",
":",
"prevstate",
",",
"inputs",
"=",
"prevstate_inputs",
"cell_tm1",
",",
"hidden_tm1",
"=",
"prevstate",
"acts",
",",
... | 38.416667 | 0.002116 |
def sources_add(source_uri, ruby=None, runas=None, gem_bin=None):
'''
Add a gem source.
:param source_uri: string
The source URI to add.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby versi... | [
"def",
"sources_add",
"(",
"source_uri",
",",
"ruby",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"gem_bin",
"=",
"None",
")",
":",
"return",
"_gem",
"(",
"[",
"'sources'",
",",
"'--add'",
",",
"source_uri",
"]",
",",
"ruby",
",",
"gem_bin",
"=",
"g... | 27.833333 | 0.001447 |
def engine(func):
"""Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be
compatible with versions of Tornado older than 3.0 the
`coroutine` decorator is recommended instead.
This decorator is similar to `coroutine`, except it d... | [
"def",
"engine",
"(",
"func",
")",
":",
"func",
"=",
"_make_coroutine_wrapper",
"(",
"func",
",",
"replace_callback",
"=",
"False",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",... | 42.272727 | 0.000701 |
def safe_chmod(path, mode):
"""Set the permissions mode on path, but only if it differs from the current mode.
"""
if stat.S_IMODE(os.stat(path).st_mode) != mode:
os.chmod(path, mode) | [
"def",
"safe_chmod",
"(",
"path",
",",
"mode",
")",
":",
"if",
"stat",
".",
"S_IMODE",
"(",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
")",
"!=",
"mode",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"mode",
")"
] | 39.8 | 0.009852 |
def colfieldnames(self, columnname, keyword=''):
"""Get the names of the fields in a column keyword value.
The value of a keyword can be a struct (python dict). This method
returns the names of the fields in that struct.
Each field in a struct can be a struct in itself. Names of fields ... | [
"def",
"colfieldnames",
"(",
"self",
",",
"columnname",
",",
"keyword",
"=",
"''",
")",
":",
"if",
"isinstance",
"(",
"keyword",
",",
"str",
")",
":",
"return",
"self",
".",
"_getfieldnames",
"(",
"columnname",
",",
"keyword",
",",
"-",
"1",
")",
"else... | 45.190476 | 0.002064 |
def s_res(self, components=None):
"""
Get apparent power in kVA at line(s) and transformer(s).
Parameters
----------
components : :obj:`list`
List of string representatives of :class:`~.grid.components.Line`
or :class:`~.grid.components.Transformer`. If n... | [
"def",
"s_res",
"(",
"self",
",",
"components",
"=",
"None",
")",
":",
"if",
"components",
"is",
"None",
":",
"return",
"self",
".",
"apparent_power",
"else",
":",
"not_included",
"=",
"[",
"_",
"for",
"_",
"in",
"components",
"if",
"_",
"not",
"in",
... | 36.827586 | 0.001825 |
def is_valid_mac(mac):
"""Returns True if the given MAC address is valid.
The given MAC address should be a colon hexadecimal notation string.
Samples:
- valid address: aa:bb:cc:dd:ee:ff, 11:22:33:44:55:66
- invalid address: aa:bb:cc:dd, 11-22-33-44-55-66, etc.
"""
return bool(re.m... | [
"def",
"is_valid_mac",
"(",
"mac",
")",
":",
"return",
"bool",
"(",
"re",
".",
"match",
"(",
"r'^'",
"+",
"r'[\\:\\-]'",
".",
"join",
"(",
"[",
"r'([0-9a-f]{2})'",
"]",
"*",
"6",
")",
"+",
"r'$'",
",",
"mac",
".",
"lower",
"(",
")",
")",
")"
] | 37 | 0.002398 |
def _null_ria(direction, mechanism, purview, repertoire=None, phi=0.0):
"""The irreducibility analysis for a reducible mechanism."""
# TODO Use properties here to infer mechanism and purview from
# partition yet access them with .mechanism and .partition
return RepertoireIrreducibilityAnalysis(
... | [
"def",
"_null_ria",
"(",
"direction",
",",
"mechanism",
",",
"purview",
",",
"repertoire",
"=",
"None",
",",
"phi",
"=",
"0.0",
")",
":",
"# TODO Use properties here to infer mechanism and purview from",
"# partition yet access them with .mechanism and .partition",
"return",
... | 38.153846 | 0.001969 |
def parse_timedelta(value):
"""
Parses a string and return a datetime.timedelta.
:param value: string to parse
:type value: str
:return: timedelta object or None if value is None
:rtype: timedelta/None
:raise: TypeError when value is not string
:raise: ValueError when value is not proper... | [
"def",
"parse_timedelta",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"'value must be a string type'",
")",
"match"... | 31.916667 | 0.001267 |
def _get_soil_depth_term(self, C, z1pt0, vs30):
"""
Compute and return soil depth term. See page 1042.
"""
# Get reference z1pt0
z1ref = self._get_z1pt0ref(vs30)
# Get z1pt0
z10 = copy.deepcopy(z1pt0)
# This is used for the calculation of the motion on re... | [
"def",
"_get_soil_depth_term",
"(",
"self",
",",
"C",
",",
"z1pt0",
",",
"vs30",
")",
":",
"# Get reference z1pt0",
"z1ref",
"=",
"self",
".",
"_get_z1pt0ref",
"(",
"vs30",
")",
"# Get z1pt0",
"z10",
"=",
"copy",
".",
"deepcopy",
"(",
"z1pt0",
")",
"# This... | 43.391304 | 0.001961 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.