text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def camelcase_underscore(name):
""" Convert camelcase names to underscore """
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | [
"def",
"camelcase_underscore",
"(",
"name",
")",
":",
"s1",
"=",
"re",
".",
"sub",
"(",
"'(.)([A-Z][a-z]+)'",
",",
"r'\\1_\\2'",
",",
"name",
")",
"return",
"re",
".",
"sub",
"(",
"'([a-z0-9])([A-Z])'",
",",
"r'\\1_\\2'",
",",
"s1",
")",
".",
"lower",
"(... | 47.75 | 10 |
def nextprefix(self):
"""
Get the next available prefix. This means a prefix starting with 'ns'
with a number appended as (ns0, ns1, ..) that is not already defined
on the wsdl document.
"""
used = [ns[0] for ns in self.prefixes]
used += [ns[0] for ns in self.wsd... | [
"def",
"nextprefix",
"(",
"self",
")",
":",
"used",
"=",
"[",
"ns",
"[",
"0",
"]",
"for",
"ns",
"in",
"self",
".",
"prefixes",
"]",
"used",
"+=",
"[",
"ns",
"[",
"0",
"]",
"for",
"ns",
"in",
"self",
".",
"wsdl",
".",
"root",
".",
"nsprefixes",
... | 38.076923 | 14.692308 |
def main(unused_argv):
"""Run an agent."""
stopwatch.sw.enabled = FLAGS.profile or FLAGS.trace
stopwatch.sw.trace = FLAGS.trace
map_inst = maps.get(FLAGS.map)
agent_classes = []
players = []
agent_module, agent_name = FLAGS.agent.rsplit(".", 1)
agent_cls = getattr(importlib.import_module(agent_module... | [
"def",
"main",
"(",
"unused_argv",
")",
":",
"stopwatch",
".",
"sw",
".",
"enabled",
"=",
"FLAGS",
".",
"profile",
"or",
"FLAGS",
".",
"trace",
"stopwatch",
".",
"sw",
".",
"trace",
"=",
"FLAGS",
".",
"trace",
"map_inst",
"=",
"maps",
".",
"get",
"("... | 32.317073 | 23.268293 |
def train_local(self, closest_point, label_vector_description=None, N=None,
pivot=True, **kwargs):
"""
Train the model in a Cannon-like fashion using the grid points as labels
and the intensities as normalsied rest-frame fluxes within some local
regime.
"""
lv = ... | [
"def",
"train_local",
"(",
"self",
",",
"closest_point",
",",
"label_vector_description",
"=",
"None",
",",
"N",
"=",
"None",
",",
"pivot",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"lv",
"=",
"self",
".",
"_cannon_label_vector",
"if",
"label_vector_... | 43.242424 | 26.030303 |
def phone_numbers(self):
"""
Access the phone_numbers
:returns: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList
:rtype: twilio.rest.proxy.v1.service.phone_number.PhoneNumberList
"""
if self._phone_numbers is None:
self._phone_numbers = PhoneNumberLi... | [
"def",
"phone_numbers",
"(",
"self",
")",
":",
"if",
"self",
".",
"_phone_numbers",
"is",
"None",
":",
"self",
".",
"_phone_numbers",
"=",
"PhoneNumberList",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]"... | 40 | 20 |
def calculate_avg_score(res):
"""
private function
Calculate the avg score of reviews present in res
:param res: tuple of tuple returned from query_retrieve_comments_or_remarks
:return: a float of the average score rounded to the closest 0.5
"""
c_star_score = 6
avg_score = 0.0
nb_re... | [
"def",
"calculate_avg_score",
"(",
"res",
")",
":",
"c_star_score",
"=",
"6",
"avg_score",
"=",
"0.0",
"nb_reviews",
"=",
"0",
"for",
"comment",
"in",
"res",
":",
"if",
"comment",
"[",
"c_star_score",
"]",
">",
"0",
":",
"avg_score",
"+=",
"comment",
"["... | 31.555556 | 14.37037 |
def as_property_description(self):
"""
Get the property description.
Returns a dictionary describing the property.
"""
description = deepcopy(self.metadata)
if 'links' not in description:
description['links'] = []
description['links'].append(
... | [
"def",
"as_property_description",
"(",
"self",
")",
":",
"description",
"=",
"deepcopy",
"(",
"self",
".",
"metadata",
")",
"if",
"'links'",
"not",
"in",
"description",
":",
"description",
"[",
"'links'",
"]",
"=",
"[",
"]",
"description",
"[",
"'links'",
... | 25 | 15.222222 |
def geometry_point(lat, lon, elev):
"""
GeoJSON point. Latitude and Longitude only have one value each
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter geometry_point")
coordinates = []
... | [
"def",
"geometry_point",
"(",
"lat",
",",
"lon",
",",
"elev",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter geometry_point\"",
")",
"coordinates",
"=",
"[",
"]",
"point_dict",
"=",
"OrderedDict",
"(",
")",
"for",
"idx",
",",
"val",
"in",
"enumerate"... | 34.041667 | 12.458333 |
def isdir(path, **kwargs):
"""Check if *path* is a directory"""
import os.path
return os.path.isdir(path, **kwargs) | [
"def",
"isdir",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"os",
".",
"path",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
",",
"*",
"*",
"kwargs",
")"
] | 31 | 9 |
def write(self, data):
"""Write string data to current process input stream."""
data = data.encode('utf-8')
data_p = ctypes.create_string_buffer(data)
num_bytes = PLARGE_INTEGER(LARGE_INTEGER(0))
bytes_to_write = len(data)
success = WriteFile(self.conin_pipe, data_p,
... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"'utf-8'",
")",
"data_p",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"data",
")",
"num_bytes",
"=",
"PLARGE_INTEGER",
"(",
"LARGE_INTEGER",
"(",
"0",
")",
... | 45 | 9.666667 |
def export():
r'''
Restores the trained variables into a simpler graph that will be exported for serving.
'''
log_info('Exporting the model...')
from tensorflow.python.framework.ops import Tensor, Operation
inputs, outputs, _ = create_inference_graph(batch_size=FLAGS.export_batch_size, n_steps=... | [
"def",
"export",
"(",
")",
":",
"log_info",
"(",
"'Exporting the model...'",
")",
"from",
"tensorflow",
".",
"python",
".",
"framework",
".",
"ops",
"import",
"Tensor",
",",
"Operation",
"inputs",
",",
"outputs",
",",
"_",
"=",
"create_inference_graph",
"(",
... | 47.103448 | 27.724138 |
def configure(self, args):
"""Configure the set of plugins with the given args.
After configuration, disabled plugins are removed from the plugins list.
"""
for plug in self._plugins:
plug_name = self.plugin_name(plug)
plug.enabled = getattr(args, "plugin_%s" % p... | [
"def",
"configure",
"(",
"self",
",",
"args",
")",
":",
"for",
"plug",
"in",
"self",
".",
"_plugins",
":",
"plug_name",
"=",
"self",
".",
"plugin_name",
"(",
"plug",
")",
"plug",
".",
"enabled",
"=",
"getattr",
"(",
"args",
",",
"\"plugin_%s\"",
"%",
... | 50.214286 | 19.428571 |
def list_permissions(self, group_name=None, resource=None):
"""List permission sets associated filtering by group and/or resource.
Args:
group_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data model object to operate on.
Retur... | [
"def",
"list_permissions",
"(",
"self",
",",
"group_name",
"=",
"None",
",",
"resource",
"=",
"None",
")",
":",
"return",
"self",
".",
"service",
".",
"list_permissions",
"(",
"group_name",
",",
"resource",
",",
"self",
".",
"url_prefix",
",",
"self",
".",... | 40 | 25.533333 |
def received(self, limit=None):
"""
Returns all the events that have been received (excluding sent events), until a limit if defined
Args:
limit (int, optional): the max length of the events to return (Default value = None)
Returns:
list: a list of received events
... | [
"def",
"received",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"return",
"list",
"(",
"itertools",
".",
"islice",
"(",
"(",
"itertools",
".",
"filterfalse",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
".",
"sent",
",",
"self",
".",
"store",
... | 35.75 | 30.583333 |
def _add_genes_to_bed(in_file, gene_file, fai_file, out_file, data, max_distance=10000):
"""Re-usable subcomponent that annotates BED file genes from another BED
"""
try:
input_rec = next(iter(pybedtools.BedTool(in_file)))
except StopIteration: # empty file
utils.copy_plus(in_file, out_... | [
"def",
"_add_genes_to_bed",
"(",
"in_file",
",",
"gene_file",
",",
"fai_file",
",",
"out_file",
",",
"data",
",",
"max_distance",
"=",
"10000",
")",
":",
"try",
":",
"input_rec",
"=",
"next",
"(",
"iter",
"(",
"pybedtools",
".",
"BedTool",
"(",
"in_file",
... | 59.394737 | 22.210526 |
def p_print_list_expr(p):
""" print_elem : expr
| print_at
| print_tab
| attr
| BOLD expr
| ITALIC expr
"""
if p[1] in ('BOLD', 'ITALIC'):
p[0] = make_sentence(p[1] + '_TMP',
m... | [
"def",
"p_print_list_expr",
"(",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
"in",
"(",
"'BOLD'",
",",
"'ITALIC'",
")",
":",
"p",
"[",
"0",
"]",
"=",
"make_sentence",
"(",
"p",
"[",
"1",
"]",
"+",
"'_TMP'",
",",
"make_typecast",
"(",
"TYPE",
".",
... | 29.384615 | 12.615385 |
def main():
"""Main entry point"""
# Quit when interrupted
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Arguments:
# --separator STRING/REGEX - how to split a row into cells (only relevant for CSV parser)
# --flatten - flatten item hashes. {'a':{'b':'c'}} --> {'a_b':'c'}
... | [
"def",
"main",
"(",
")",
":",
"# Quit when interrupted",
"import",
"signal",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_DFL",
")",
"# Arguments:",
"# --separator STRING/REGEX - how to split a row into cells (only relevant for CSV parser)... | 41.97619 | 27.928571 |
def print(self, *args, **kwargs):
'''
Utility function that behaves identically to 'print' except it only
prints if verbose
'''
if self._last_args and self._last_args.verbose:
print(*args, **kwargs) | [
"def",
"print",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_last_args",
"and",
"self",
".",
"_last_args",
".",
"verbose",
":",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 34.857143 | 19.428571 |
def run_pod(self, pod, startup_timeout=120, get_logs=True):
# type: (Pod, int, bool) -> Tuple[State, Optional[str]]
"""
Launches the pod synchronously and waits for completion.
Args:
pod (Pod):
startup_timeout (int): Timeout for startup of the pod (if pod is pendi... | [
"def",
"run_pod",
"(",
"self",
",",
"pod",
",",
"startup_timeout",
"=",
"120",
",",
"get_logs",
"=",
"True",
")",
":",
"# type: (Pod, int, bool) -> Tuple[State, Optional[str]]",
"resp",
"=",
"self",
".",
"run_pod_async",
"(",
"pod",
")",
"curr_time",
"=",
"dt",
... | 41.15 | 15.05 |
def get(self, sid):
"""
Constructs a CredentialListContext
:param sid: Fetch by unique credential list Sid
:returns: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext
:rtype: twilio.rest.api.v2010.account.sip.credential_list.CredentialListContext
"... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"CredentialListContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 41.9 | 27.9 |
def grant_db_access(conn, schema, table, role):
r"""Gives access to database users/ groups
Parameters
----------
conn : sqlalchemy connection object
A valid connection to a database
schema : str
The database schema
table : str
The database table
role : str
da... | [
"def",
"grant_db_access",
"(",
"conn",
",",
"schema",
",",
"table",
",",
"role",
")",
":",
"grant_str",
"=",
"\"\"\"GRANT ALL ON TABLE {schema}.{table}\n TO {role} WITH GRANT OPTION;\"\"\"",
".",
"format",
"(",
"schema",
"=",
"schema",
",",
"table",
"=",
"table",
... | 27.8 | 15.75 |
def get(self, collection_id, content=None, **kwargs):
"""Syntactic sugar around to make it easier to get fine-grained access
to the parts of a file without composing a PhyloSchema object.
Possible invocations include:
w.get('pg_10')
w.get('pg_10', 'trees')
w.g... | [
"def",
"get",
"(",
"self",
",",
"collection_id",
",",
"content",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"COLLECTION_ID_PATTERN",
".",
"match",
"(",
"collection_id",
")",
"r",
"=",
"self",
".",
"get_collection",
"(",
"collection_id",
")",... | 40.8 | 11.666667 |
def clone(self, forced_version_date=None, in_bulk=False):
"""
Clones a Versionable and returns a fresh copy of the original object.
Original source: ClonableMixin snippet
(http://djangosnippets.org/snippets/1271), with the pk/id change
suggested in the comments
:param fo... | [
"def",
"clone",
"(",
"self",
",",
"forced_version_date",
"=",
"None",
",",
"in_bulk",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"pk",
":",
"raise",
"ValueError",
"(",
"'Instance must be saved before it can be cloned'",
")",
"if",
"self",
".",
"version_... | 43.059701 | 21.716418 |
def _set_attribute(self, attribute, name, value):
"""Device attribute setter"""
try:
if attribute is None:
attribute = self._attribute_file_open( name )
else:
attribute.seek(0)
if isinstance(value, str):
value = value.e... | [
"def",
"_set_attribute",
"(",
"self",
",",
"attribute",
",",
"name",
",",
"value",
")",
":",
"try",
":",
"if",
"attribute",
"is",
"None",
":",
"attribute",
"=",
"self",
".",
"_attribute_file_open",
"(",
"name",
")",
"else",
":",
"attribute",
".",
"seek",... | 32.733333 | 13.066667 |
def make_success_response(self, result):
"""
Makes the python dict corresponding to the
JSON that needs to be sent for a successful
response. Result is the actual payload
that gets sent.
"""
response = self.make_response(constants.RESPONSE_STATUS_SUCCESS)
response[constants.RESPONSE_KEY_... | [
"def",
"make_success_response",
"(",
"self",
",",
"result",
")",
":",
"response",
"=",
"self",
".",
"make_response",
"(",
"constants",
".",
"RESPONSE_STATUS_SUCCESS",
")",
"response",
"[",
"constants",
".",
"RESPONSE_KEY_RESULT",
"]",
"=",
"result",
"return",
"r... | 34.7 | 9.7 |
def funcFindPrfMltpPrdXVal(idxPrc,
aryFuncChnkTrn,
aryFuncChnkTst,
aryPrfMdlsTrnConv,
aryPrfMdlsTstConv,
aryMdls,
queOut):
"""
Function for finding be... | [
"def",
"funcFindPrfMltpPrdXVal",
"(",
"idxPrc",
",",
"aryFuncChnkTrn",
",",
"aryFuncChnkTst",
",",
"aryPrfMdlsTrnConv",
",",
"aryPrfMdlsTstConv",
",",
"aryMdls",
",",
"queOut",
")",
":",
"# Number of voxels to be fitted in this chunk:",
"varNumVoxChnk",
"=",
"aryFuncChnkTrn... | 36.24026 | 18.487013 |
def standard(target, mol_weight='pore.molecular_weight',
density='pore.density'):
r"""
Calculates the molar density from the molecular weight and mass density
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
con... | [
"def",
"standard",
"(",
"target",
",",
"mol_weight",
"=",
"'pore.molecular_weight'",
",",
"density",
"=",
"'pore.density'",
")",
":",
"MW",
"=",
"target",
"[",
"mol_weight",
"]",
"rho",
"=",
"target",
"[",
"density",
"]",
"value",
"=",
"rho",
"/",
"MW",
... | 31.590909 | 21.181818 |
def autocorrelation(x, lag):
"""
Calculates the autocorrelation of the specified lag, according to the formula [1]
.. math::
\\frac{1}{(n-l)\sigma^{2}} \\sum_{t=1}^{n-l}(X_{t}-\\mu )(X_{t+l}-\\mu)
where :math:`n` is the length of the time series :math:`X_i`, :math:`\sigma^2` its variance and ... | [
"def",
"autocorrelation",
"(",
"x",
",",
"lag",
")",
":",
"# This is important: If a series is passed, the product below is calculated",
"# based on the index, which corresponds to squaring the series.",
"if",
"type",
"(",
"x",
")",
"is",
"pd",
".",
"Series",
":",
"x",
"=",... | 32.04878 | 22.487805 |
def run_decider_state(self, decider_state, child_errors, final_outcomes_dict):
""" Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the
barrier concurrency is left.
:param decider_state: the decider state of the barrier concurrency state
... | [
"def",
"run_decider_state",
"(",
"self",
",",
"decider_state",
",",
"child_errors",
",",
"final_outcomes_dict",
")",
":",
"decider_state",
".",
"state_execution_status",
"=",
"StateExecutionStatus",
".",
"ACTIVE",
"# forward the decider specific data",
"decider_state",
".",... | 57.884615 | 23.653846 |
def build_ml_phyml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with PhyML
"""
phy_file = op.join(work_dir, "work", "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
phyml_cl = PhymlCommandline(cmd=PHYML_BIN("phyml"), input=... | [
"def",
"build_ml_phyml",
"(",
"alignment",
",",
"outfile",
",",
"work_dir",
"=",
"\".\"",
",",
"*",
"*",
"kwargs",
")",
":",
"phy_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"work\"",
",",
"\"aln.phy\"",
")",
"AlignIO",
".",
"write",
"(",
"a... | 35.5 | 19.8 |
def search_engine(query, top=5, service="google", license=None,
cache=os.path.join(DEFAULT_CACHE, "google")):
"""
Return a color aggregate from colors and ranges parsed from the web.
T. De Smedt, http://nodebox.net/code/index.php/Prism
"""
# Check if we have cached information firs... | [
"def",
"search_engine",
"(",
"query",
",",
"top",
"=",
"5",
",",
"service",
"=",
"\"google\"",
",",
"license",
"=",
"None",
",",
"cache",
"=",
"os",
".",
"path",
".",
"join",
"(",
"DEFAULT_CACHE",
",",
"\"google\"",
")",
")",
":",
"# Check if we have cac... | 30.188679 | 18.188679 |
def getPaths(roots, ignores=None):
"""
Recursively walk a set of paths and return a listing of contained files.
:param roots: Relative or absolute paths to files or folders.
:type roots: :class:`~__builtins__.list` of :class:`~__builtins__.str`
:param ignores: A list of :py:mod:`fnmatch` globs to ... | [
"def",
"getPaths",
"(",
"roots",
",",
"ignores",
"=",
"None",
")",
":",
"paths",
",",
"count",
",",
"ignores",
"=",
"[",
"]",
",",
"0",
",",
"ignores",
"or",
"[",
"]",
"# Prepare the ignores list for most efficient use",
"ignore_re",
"=",
"multiglob_compile",
... | 36.037037 | 21.555556 |
def errorReceived(self, merr):
"""
Called when an error message is received
"""
d, timeout = self._pendingCalls.get(merr.reply_serial, (None, None))
if timeout:
timeout.cancel()
if d:
del self._pendingCalls[merr.reply_serial]
e = error.... | [
"def",
"errorReceived",
"(",
"self",
",",
"merr",
")",
":",
"d",
",",
"timeout",
"=",
"self",
".",
"_pendingCalls",
".",
"get",
"(",
"merr",
".",
"reply_serial",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"timeout",
":",
"timeout",
".",
"cancel",... | 34.176471 | 13.352941 |
def get_runnable_effects(self) -> List[Effect]:
"""
Returns all runnable effects in the project.
:return: List of all runnable effects
"""
return [effect for name, effect in self._effects.items() if effect.runnable] | [
"def",
"get_runnable_effects",
"(",
"self",
")",
"->",
"List",
"[",
"Effect",
"]",
":",
"return",
"[",
"effect",
"for",
"name",
",",
"effect",
"in",
"self",
".",
"_effects",
".",
"items",
"(",
")",
"if",
"effect",
".",
"runnable",
"]"
] | 36.571429 | 15.714286 |
def _GetUtf8Contents(self, file_name):
"""Check for errors in file_name and return a string for csv reader."""
contents = self._FileContents(file_name)
if not contents: # Missing file
return
# Check for errors that will prevent csv.reader from working
if len(contents) >= 2 and contents[0:2] ... | [
"def",
"_GetUtf8Contents",
"(",
"self",
",",
"file_name",
")",
":",
"contents",
"=",
"self",
".",
"_FileContents",
"(",
"file_name",
")",
"if",
"not",
"contents",
":",
"# Missing file",
"return",
"# Check for errors that will prevent csv.reader from working",
"if",
"l... | 42.071429 | 21.035714 |
def patch_namespaced_resource_quota(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_resource_quota # noqa: E501
partially update the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP req... | [
"def",
"patch_namespaced_resource_quota",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
... | 62.32 | 35.24 |
def env(self):
"""
Dict of all environment variables that will be run with this command.
"""
env_vars = os.environ.copy()
env_vars.update(self._env)
new_path = ":".join(
self._paths + [env_vars["PATH"]] if "PATH" in env_vars else [] + self._paths
)
... | [
"def",
"env",
"(",
"self",
")",
":",
"env_vars",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env_vars",
".",
"update",
"(",
"self",
".",
"_env",
")",
"new_path",
"=",
"\":\"",
".",
"join",
"(",
"self",
".",
"_paths",
"+",
"[",
"env_vars",
... | 34 | 14 |
def derivatives(self, x, y, Rs, theta_Rs, e1, e2, center_x=0, center_y=0):
"""
returns df/dx and df/dy of the function (integral of NFW)
"""
phi_G, q = param_util.ellipticity2phi_q(e1, e2)
x_shift = x - center_x
y_shift = y - center_y
cos_phi = np.cos(phi_G)
... | [
"def",
"derivatives",
"(",
"self",
",",
"x",
",",
"y",
",",
"Rs",
",",
"theta_Rs",
",",
"e1",
",",
"e2",
",",
"center_x",
"=",
"0",
",",
"center_y",
"=",
"0",
")",
":",
"phi_G",
",",
"q",
"=",
"param_util",
".",
"ellipticity2phi_q",
"(",
"e1",
",... | 41.545455 | 13.636364 |
def UpsertUserDefinedFunction(self, collection_link, udf, options=None):
"""Upserts a user defined function in a collection.
:param str collection_link:
The link to the collection.
:param str udf:
:param dict options:
The request options for the request.
... | [
"def",
"UpsertUserDefinedFunction",
"(",
"self",
",",
"collection_link",
",",
"udf",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"collection_id",
",",
"path",
",",
"udf",
"=",
"self",
".",
"_GetCon... | 29.52 | 17.44 |
def search(self, **kwargs):
"""
Query using ElasticSearch, returning an elasticsearch queryset.
:param kwargs: keyword arguments (optional)
* query : ES Query spec
* tags : content tags
* types : content types
* feature_types : featured types
* publi... | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"search_query",
"=",
"super",
"(",
"ContentManager",
",",
"self",
")",
".",
"search",
"(",
")",
"if",
"\"query\"",
"in",
"kwargs",
":",
"search_query",
"=",
"search_query",
".",
"query",
... | 40.62 | 22.66 |
def convert_sum(node, **kwargs):
"""Map MXNet's sum operator attributes to onnx's ReduceSum operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
mx_axis = attrs.get("axis", None)
axes = convert_string_to_list(str(mx_axis)) if mx_axis is not None else Non... | [
"def",
"convert_sum",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"mx_axis",
"=",
"attrs",
".",
"get",
"(",
"\"axis\"",
",",
"None",
")",
"axes",
"=",
... | 27.344828 | 17.827586 |
def first(self):
"""
Return the first element.
"""
if self.mode == 'local':
return self.values[0]
if self.mode == 'spark':
return self.values.first().toarray() | [
"def",
"first",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"'local'",
":",
"return",
"self",
".",
"values",
"[",
"0",
"]",
"if",
"self",
".",
"mode",
"==",
"'spark'",
":",
"return",
"self",
".",
"values",
".",
"first",
"(",
")",
".",... | 24 | 11.333333 |
def update(self, symbol, data, metadata=None, upsert=True, as_of=None, **kwargs):
""" Append 'data' under the specified 'symbol' name to this library.
Parameters
----------
symbol : `str`
symbol name for the item
data : `pd.DataFrame`
to be persisted
... | [
"def",
"update",
"(",
"self",
",",
"symbol",
",",
"data",
",",
"metadata",
"=",
"None",
",",
"upsert",
"=",
"True",
",",
"as_of",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"local_tz",
"=",
"mktz",
"(",
")",
"if",
"not",
"as_of",
":",
"as_of... | 41.483871 | 19 |
def close(self):
"""Set some objects to None to hopefully free up some memory."""
self._target_context_errors = None
self._query_context_errors = None
self._general_errors = None
for ae in self._alignment_errors:
ae.close()
self._alignment_errors = None | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_target_context_errors",
"=",
"None",
"self",
".",
"_query_context_errors",
"=",
"None",
"self",
".",
"_general_errors",
"=",
"None",
"for",
"ae",
"in",
"self",
".",
"_alignment_errors",
":",
"ae",
".",
... | 34.5 | 9 |
def build(self, root, schema):
""" Build the syntax tree for kubectl command line """
if schema.get("subcommands") and schema["subcommands"]:
for subcmd, childSchema in schema["subcommands"].items():
child = CommandTree(node=subcmd)
child = self.build(child, c... | [
"def",
"build",
"(",
"self",
",",
"root",
",",
"schema",
")",
":",
"if",
"schema",
".",
"get",
"(",
"\"subcommands\"",
")",
"and",
"schema",
"[",
"\"subcommands\"",
"]",
":",
"for",
"subcmd",
",",
"childSchema",
"in",
"schema",
"[",
"\"subcommands\"",
"]... | 49 | 12.058824 |
def web_agent(self, reactor, socks_endpoint, pool=None):
"""
:param socks_endpoint: create one with
:meth:`txtorcon.TorConfig.create_socks_endpoint`. Can be a
Deferred.
:param pool: passed on to the Agent (as ``pool=``)
"""
# local import because there is... | [
"def",
"web_agent",
"(",
"self",
",",
"reactor",
",",
"socks_endpoint",
",",
"pool",
"=",
"None",
")",
":",
"# local import because there isn't Agent stuff on some",
"# platforms we support, so this will only error if you try",
"# this on the wrong platform (pypy [??] and old-twisted... | 34.944444 | 17.611111 |
def insert_weave_option_group(parser):
"""
Adds the options used to specify weave options.
Parameters
----------
parser : object
OptionParser instance
"""
optimization_group = parser.add_argument_group("Options for controlling "
"weave")
optim... | [
"def",
"insert_weave_option_group",
"(",
"parser",
")",
":",
"optimization_group",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Options for controlling \"",
"\"weave\"",
")",
"optimization_group",
".",
"add_argument",
"(",
"\"--per-process-weave-cache\"",
",",
"action"... | 40.72973 | 18.108108 |
def conjugate(self):
"""Quaternion conjugate, encapsulated in a new instance.
For a unit quaternion, this is the same as the inverse.
Returns:
A new Quaternion object clone with its vector part negated
"""
return self.__class__(scalar=self.scalar, vector= -self.vect... | [
"def",
"conjugate",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"scalar",
"=",
"self",
".",
"scalar",
",",
"vector",
"=",
"-",
"self",
".",
"vector",
")"
] | 35 | 23.111111 |
def parse_dimension(self, node):
"""
Parses <Dimension>
@param node: Node containing the <Dimension> element
@type node: xml.etree.Element
@raise ParseError: When the name is not a string or if the
dimension is not a signed integer.
"""
try:
... | [
"def",
"parse_dimension",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"name",
"=",
"node",
".",
"lattrib",
"[",
"'name'",
"]",
"except",
":",
"self",
".",
"raise_error",
"(",
"'<Dimension> must specify a name'",
")",
"description",
"=",
"node",
".",
"l... | 28.73913 | 20.73913 |
def export_tour(tour_steps, name=None, filename="my_tour.js", url=None):
""" Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs. "... | [
"def",
"export_tour",
"(",
"tour_steps",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"\"my_tour.js\"",
",",
"url",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"\"default\"",
"if",
"name",
"not",
"in",
"tour_steps",
":",
"raise",
"... | 41.242775 | 15.306358 |
def _save_potentials(self, directory):
"""save potentials to a directory
"""
print('saving potentials')
digits = int(np.ceil(np.log10(self.configs.configs.shape[0])))
for i in range(0, self.configs.configs.shape[0]):
pot_data = self.get_potential(i)
filena... | [
"def",
"_save_potentials",
"(",
"self",
",",
"directory",
")",
":",
"print",
"(",
"'saving potentials'",
")",
"digits",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"log10",
"(",
"self",
".",
"configs",
".",
"configs",
".",
"shape",
"[",
"0",
... | 40.5 | 12.944444 |
def _try_weakref(arg, remove_callback):
"""Return a weak reference to arg if possible, or arg itself if not."""
try:
arg = weakref.ref(arg, remove_callback)
except TypeError:
# Not all types can have a weakref. That includes strings
# and floats and such, so just pass them through di... | [
"def",
"_try_weakref",
"(",
"arg",
",",
"remove_callback",
")",
":",
"try",
":",
"arg",
"=",
"weakref",
".",
"ref",
"(",
"arg",
",",
"remove_callback",
")",
"except",
"TypeError",
":",
"# Not all types can have a weakref. That includes strings",
"# and floats and such... | 38.555556 | 18.222222 |
def Input_setIgnoreInputEvents(self, ignore):
"""
Function path: Input.setIgnoreInputEvents
Domain: Input
Method name: setIgnoreInputEvents
Parameters:
Required arguments:
'ignore' (type: boolean) -> Ignores input events processing when set to true.
No return value.
Description: Ignore... | [
"def",
"Input_setIgnoreInputEvents",
"(",
"self",
",",
"ignore",
")",
":",
"assert",
"isinstance",
"(",
"ignore",
",",
"(",
"bool",
",",
")",
")",
",",
"\"Argument 'ignore' must be of type '['bool']'. Received type: '%s'\"",
"%",
"type",
"(",
"ignore",
")",
"subdom_... | 31.684211 | 20.526316 |
def usnjrnl_timeline(self):
"""Iterates over the changes occurred within the filesystem.
Yields UsnJrnlEvent namedtuples containing:
file_reference_number: known in Unix FS as inode.
path: full path of the file.
size: size of the file in bytes if recoverable.
... | [
"def",
"usnjrnl_timeline",
"(",
"self",
")",
":",
"filesystem_content",
"=",
"defaultdict",
"(",
"list",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Extracting Update Sequence Number journal.\"",
")",
"journal",
"=",
"self",
".",
"_read_journal",
"(",
")",
... | 36.56 | 20.2 |
def register(self, job):
"""Takes a job (unencoded) and adorns it with a unique key; this makes
an entry in the database without any further specification."""
with self.lock:
self.cur.execute(
'insert into "jobs" ("name", "session", "status") '
'values... | [
"def",
"register",
"(",
"self",
",",
"job",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"'insert into \"jobs\" (\"name\", \"session\", \"status\") '",
"'values (?, ?, ?)'",
",",
"(",
"job",
".",
"name",
",",
"self",
"."... | 52.777778 | 15 |
def reject(self, *, requeue=True):
"""
Reject the message.
:keyword bool requeue: if true, the broker will attempt to requeue the
message and deliver it to an alternate consumer.
"""
self.sender.send_BasicReject(self.delivery_tag, requeue) | [
"def",
"reject",
"(",
"self",
",",
"*",
",",
"requeue",
"=",
"True",
")",
":",
"self",
".",
"sender",
".",
"send_BasicReject",
"(",
"self",
".",
"delivery_tag",
",",
"requeue",
")"
] | 35.625 | 17.625 |
def _iter_frequencies(q, frange, mismatch, dur):
"""Iterate over the frequencies of this 'QPlane'
Parameters
----------
q:
q value
frange: 'list'
upper and lower bounds of frequency range
mismatch:
percentage of desired fractional mismatch
dur:
duration of ti... | [
"def",
"_iter_frequencies",
"(",
"q",
",",
"frange",
",",
"mismatch",
",",
"dur",
")",
":",
"# work out how many frequencies we need",
"minf",
",",
"maxf",
"=",
"frange",
"fcum_mismatch",
"=",
"log",
"(",
"float",
"(",
"maxf",
")",
"/",
"minf",
")",
"*",
"... | 28.064516 | 18.225806 |
def subplot(self, index_x, index_y):
"""
Sets the active subplot.
Parameters
----------
index_x : int
Index of the subplot to activate in the x direction.
index_y : int
Index of the subplot to activate in the y direction.
"""
sel... | [
"def",
"subplot",
"(",
"self",
",",
"index_x",
",",
"index_y",
")",
":",
"self",
".",
"_active_renderer_index",
"=",
"self",
".",
"loc_to_index",
"(",
"(",
"index_x",
",",
"index_y",
")",
")"
] | 26.5 | 21.214286 |
def create_tmp_rootdir(self):
"""
create a rootdir that we can destroy later again
Returns
-------
"""
if self.rootdir:
tmp_rootdir = tempfile.mkdtemp(prefix='bcolz-')
self._dir_clean_list.append(tmp_rootdir)
else:
tmp_rootdir... | [
"def",
"create_tmp_rootdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"rootdir",
":",
"tmp_rootdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'bcolz-'",
")",
"self",
".",
"_dir_clean_list",
".",
"append",
"(",
"tmp_rootdir",
")",
"else",
":",... | 24.357143 | 18.214286 |
def preserve_channel_dim(func):
"""Preserve dummy channel dim."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expand_dims(resul... | [
"def",
"preserve_channel_dim",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_function",
"(",
"img",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"img",
".",
"shape",
"result",
"=",
"func",
"(",
"img",
... | 33.818182 | 15.909091 |
def _pack3(obj, fp, **options):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
fp: a .write()-supporting file-like object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable ... | [
"def",
"_pack3",
"(",
"obj",
",",
"fp",
",",
"*",
"*",
"options",
")",
":",
"global",
"compatibility",
"ext_handlers",
"=",
"options",
".",
"get",
"(",
"\"ext_handlers\"",
")",
"if",
"obj",
"is",
"None",
":",
"_pack_nil",
"(",
"obj",
",",
"fp",
",",
... | 34.628571 | 16.914286 |
def session_exists(self, username):
"""
:param username:
:type username: str
:return:
:rtype:
"""
logger.debug("session_exists(%s)?" % username)
return self._store.containsSession(username, 1) | [
"def",
"session_exists",
"(",
"self",
",",
"username",
")",
":",
"logger",
".",
"debug",
"(",
"\"session_exists(%s)?\"",
"%",
"username",
")",
"return",
"self",
".",
"_store",
".",
"containsSession",
"(",
"username",
",",
"1",
")"
] | 27.555556 | 12.444444 |
async def query(
self,
q: AnyStr,
*,
epoch: str = 'ns',
chunked: bool = False,
chunk_size: Optional[int] = None,
db: Optional[str] = None,
use_cache: bool = False,
) -> Union[AsyncGenerator[ResultType, None], ResultType]:
"""Sends a query to In... | [
"async",
"def",
"query",
"(",
"self",
",",
"q",
":",
"AnyStr",
",",
"*",
",",
"epoch",
":",
"str",
"=",
"'ns'",
",",
"chunked",
":",
"bool",
"=",
"False",
",",
"chunk_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"db",
":",
"Optional... | 44.22619 | 19.797619 |
def write_metadata(self, handler):
""" set the meta data """
if self.metadata is not None:
handler.write_metadata(self.cname, self.metadata) | [
"def",
"write_metadata",
"(",
"self",
",",
"handler",
")",
":",
"if",
"self",
".",
"metadata",
"is",
"not",
"None",
":",
"handler",
".",
"write_metadata",
"(",
"self",
".",
"cname",
",",
"self",
".",
"metadata",
")"
] | 41.25 | 7.5 |
def assign_default_log_values(self, fpath, line, formatter):
'''
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> from pprint import pprint
>>> formatter = 'logagg.formatters.mongodb'
>>> fpath = '/var/log/mongodb/mongodb.log'
... | [
"def",
"assign_default_log_values",
"(",
"self",
",",
"fpath",
",",
"line",
",",
"formatter",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"None",
",",
"file",
"=",
"fpath",
",",
"host",
"=",
"self",
".",
"HOST",
",",
"formatter",
"=",
"formatter",
",",... | 31.526316 | 18.526316 |
def find_unused_port(start_port, end_port, host="127.0.0.1", socket_type="TCP", ignore_ports=None):
"""
Finds an unused port in a range.
:param start_port: first port in the range
:param end_port: last port in the range
:param host: host/address for bind()
:param socket_... | [
"def",
"find_unused_port",
"(",
"start_port",
",",
"end_port",
",",
"host",
"=",
"\"127.0.0.1\"",
",",
"socket_type",
"=",
"\"TCP\"",
",",
"ignore_ports",
"=",
"None",
")",
":",
"if",
"end_port",
"<",
"start_port",
":",
"raise",
"HTTPConflict",
"(",
"text",
... | 46.657143 | 27.4 |
def estimate_augmented_markov_model(dtrajs, ftrajs, lag, m, sigmas,
count_mode='sliding', connectivity='largest',
dt_traj='1 step', maxiter=1000000, eps=0.05, maxcache=3000):
r""" Estimates an Augmented Markov model from discrete trajectories and experimental dat... | [
"def",
"estimate_augmented_markov_model",
"(",
"dtrajs",
",",
"ftrajs",
",",
"lag",
",",
"m",
",",
"sigmas",
",",
"count_mode",
"=",
"'sliding'",
",",
"connectivity",
"=",
"'largest'",
",",
"dt_traj",
"=",
"'1 step'",
",",
"maxiter",
"=",
"1000000",
",",
"ep... | 42.453947 | 27.006579 |
def run(self):
""" Append version number to lsqfit/__init__.py """
with open('src/lsqfit/__init__.py', 'a') as lsfile:
lsfile.write("\n__version__ = '%s'\n" % LSQFIT_VERSION)
_build_py.run(self) | [
"def",
"run",
"(",
"self",
")",
":",
"with",
"open",
"(",
"'src/lsqfit/__init__.py'",
",",
"'a'",
")",
"as",
"lsfile",
":",
"lsfile",
".",
"write",
"(",
"\"\\n__version__ = '%s'\\n\"",
"%",
"LSQFIT_VERSION",
")",
"_build_py",
".",
"run",
"(",
"self",
")"
] | 45.2 | 17 |
def _get_build_type(fnames, samples, caller):
"""Confirm we should build a gemini database: need gemini in tools_on.
Checks for valid conditions for running a database and gemini or gemini_orig
configured in tools on.
"""
build_type = set()
if any(vcfutils.vcf_has_variants(f) for f in fnames) a... | [
"def",
"_get_build_type",
"(",
"fnames",
",",
"samples",
",",
"caller",
")",
":",
"build_type",
"=",
"set",
"(",
")",
"if",
"any",
"(",
"vcfutils",
".",
"vcf_has_variants",
"(",
"f",
")",
"for",
"f",
"in",
"fnames",
")",
"and",
"caller",
"not",
"in",
... | 52.47619 | 29.095238 |
def apply(self):
"""Apply the rules of the context to its occurrences.
This method executes all the functions defined in
self.tasks in the order they are listed.
Every function that acts as a context task receives the
Context object itself as its only argument.
The con... | [
"def",
"apply",
"(",
"self",
")",
":",
"raw_operations",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"occurrences",
")",
"for",
"task",
"in",
"self",
".",
"tasks",
":",
"task",
"(",
"self",
")",
"self",
".",
"occurrences",
"=",
"raw_operations"
] | 33.555556 | 18.444444 |
def _add_dot_key(self, section, key=None):
"""
:param str section: Config section
:param str key: Config key
"""
if key:
self._dot_keys[self._to_dot_key(section, key)] = (section, key)
else:
self._dot_keys[self._to_dot_key(section)] = section | [
"def",
"_add_dot_key",
"(",
"self",
",",
"section",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
":",
"self",
".",
"_dot_keys",
"[",
"self",
".",
"_to_dot_key",
"(",
"section",
",",
"key",
")",
"]",
"=",
"(",
"section",
",",
"key",
")",
"else",
... | 34 | 13.333333 |
def triangle_areas(p1,p2,p3):
"""Compute an array of triangle areas given three arrays of triangle pts
p1,p2,p3 - three Nx2 arrays of points
"""
v1 = (p2 - p1).astype(np.float)
v2 = (p3 - p1).astype(np.float)
# Original:
# cross1 = v1[:,1] * v2[:,0]
# cross2 = v2[:,1] * v1[:,0]
... | [
"def",
"triangle_areas",
"(",
"p1",
",",
"p2",
",",
"p3",
")",
":",
"v1",
"=",
"(",
"p2",
"-",
"p1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"v2",
"=",
"(",
"p3",
"-",
"p1",
")",
".",
"astype",
"(",
"np",
".",
"float",
")",
"# Ori... | 25.481481 | 16.037037 |
def get_all_groups(path_prefix='/', region=None, key=None, keyid=None,
profile=None):
'''
Get and return all IAM group details, starting at the optional path.
.. versionadded:: 2016.3.0
CLI Example:
salt-call boto_iam.get_all_groups
'''
conn = _get_conn(region=region,... | [
"def",
"get_all_groups",
"(",
"path_prefix",
"=",
"'/'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | 34.807692 | 27.115385 |
def fire_event(self, event_name, wait=False, *args, **kwargs):
"""
Fire an event to plugins.
PluginManager schedule @asyncio.coroutinecalls for each plugin on method called "on_" + event_name
For example, on_connect will be called on event 'connect'
Method calls are schedule in t... | [
"def",
"fire_event",
"(",
"self",
",",
"event_name",
",",
"wait",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tasks",
"=",
"[",
"]",
"event_method_name",
"=",
"\"on_\"",
"+",
"event_name",
"for",
"plugin",
"in",
"self",
".",
"... | 42.27027 | 22.108108 |
def from_definition(self, table: Table, version: int):
"""Add all columns from the table added in the specified version"""
self.table(table)
self.add_columns(*table.columns.get_with_version(version))
return self | [
"def",
"from_definition",
"(",
"self",
",",
"table",
":",
"Table",
",",
"version",
":",
"int",
")",
":",
"self",
".",
"table",
"(",
"table",
")",
"self",
".",
"add_columns",
"(",
"*",
"table",
".",
"columns",
".",
"get_with_version",
"(",
"version",
")... | 47.8 | 15.2 |
def restbase(self, endpoint, title):
"""
Returns RESTBase query string
"""
if not endpoint:
raise ValueError("invalid endpoint: %s" % endpoint)
route = endpoint
if title and endpoint != '/page/':
route = endpoint + safequote_restbase(title)
... | [
"def",
"restbase",
"(",
"self",
",",
"endpoint",
",",
"title",
")",
":",
"if",
"not",
"endpoint",
":",
"raise",
"ValueError",
"(",
"\"invalid endpoint: %s\"",
"%",
"endpoint",
")",
"route",
"=",
"endpoint",
"if",
"title",
"and",
"endpoint",
"!=",
"'/page/'",... | 28.857143 | 15.714286 |
def validate_event(payload: bytes, *, signature: str, secret: str) -> None:
"""Validate the signature of a webhook event."""
# https://developer.github.com/webhooks/securing/#validating-payloads-from-github
signature_prefix = "sha1="
if not signature.startswith(signature_prefix):
raise Validatio... | [
"def",
"validate_event",
"(",
"payload",
":",
"bytes",
",",
"*",
",",
"signature",
":",
"str",
",",
"secret",
":",
"str",
")",
"->",
"None",
":",
"# https://developer.github.com/webhooks/securing/#validating-payloads-from-github",
"signature_prefix",
"=",
"\"sha1=\"",
... | 62.25 | 22.916667 |
def format_title(self, format='html5', deparagraph=True, mathjax=False,
smart=True, extra_args=None):
"""Get the document title in the specified markup format.
Parameters
----------
format : `str`, optional
Output format (such as ``'html5'`` or ``'plain'... | [
"def",
"format_title",
"(",
"self",
",",
"format",
"=",
"'html5'",
",",
"deparagraph",
"=",
"True",
",",
"mathjax",
"=",
"False",
",",
"smart",
"=",
"True",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"self",
".",
"title",
"is",
"None",
":",
"ret... | 35.352941 | 16.470588 |
def is_training_name(name):
"""
**Guess** if this variable is only used in training.
Only used internally to avoid too many logging. Do not use it.
"""
# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?
# TODO or use get_slot_names()
name = get_op_tensor_name(name)[0... | [
"def",
"is_training_name",
"(",
"name",
")",
":",
"# TODO: maybe simply check against TRAINABLE_VARIABLES and MODEL_VARIABLES?",
"# TODO or use get_slot_names()",
"name",
"=",
"get_op_tensor_name",
"(",
"name",
")",
"[",
"0",
"]",
"if",
"name",
".",
"endswith",
"(",
"'/Ad... | 37.28 | 18 |
def sync_required(func):
"""Decorate methods when synchronizing repository is required."""
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self._keepSynchronized:
r = func(self, *args, **kwargs)
else:
state = self._load_state()
#print("----------->... | [
"def",
"sync_required",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_keepSynchronized",
":",
"r",
"=",
"func",
"(",
"self",
... | 38.166667 | 15.555556 |
def nodes_with_tag(tag):
"""Sets a list of nodes that have the given tag assigned and calls node()"""
nodes = lib.get_nodes_with_tag(tag, env.chef_environment,
littlechef.include_guests)
nodes = [n['name'] for n in nodes]
if not len(nodes):
print("No nodes foun... | [
"def",
"nodes_with_tag",
"(",
"tag",
")",
":",
"nodes",
"=",
"lib",
".",
"get_nodes_with_tag",
"(",
"tag",
",",
"env",
".",
"chef_environment",
",",
"littlechef",
".",
"include_guests",
")",
"nodes",
"=",
"[",
"n",
"[",
"'name'",
"]",
"for",
"n",
"in",
... | 42.888889 | 14.888889 |
def distribute_libs(self, arch, src_dirs, wildcard='*', dest_dir="libs"):
'''Copy existing arch libs from build dirs to current dist dir.'''
info('Copying libs')
tgt_dir = join(dest_dir, arch.arch)
ensure_dir(tgt_dir)
for src_dir in src_dirs:
for lib in glob.glob(join... | [
"def",
"distribute_libs",
"(",
"self",
",",
"arch",
",",
"src_dirs",
",",
"wildcard",
"=",
"'*'",
",",
"dest_dir",
"=",
"\"libs\"",
")",
":",
"info",
"(",
"'Copying libs'",
")",
"tgt_dir",
"=",
"join",
"(",
"dest_dir",
",",
"arch",
".",
"arch",
")",
"e... | 48.125 | 16.375 |
def alias(name, class_object):
"""
Create an alias of a class object
The objective of this method is to have
an alias that is Registered. i.e If we have
class_b = class_a
Makes `class_b` an alias of `class_a`, but if
`class_a` is registered by its metaclass,
`class_b` is not. The ... | [
"def",
"alias",
"(",
"name",
",",
"class_object",
")",
":",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"class_object",
")",
"module",
".",
"__dict__",
"[",
"name",
"]",
"=",
"class_object",
"if",
"isinstance",
"(",
"class_object",
",",
"Registry",
")... | 25.125 | 14.625 |
def part_channel(self, channel, reason=None, tags=None):
"""Part the given channel."""
params = [channel]
if reason:
params.append(reason)
self.send('PART', params=params, tags=tags) | [
"def",
"part_channel",
"(",
"self",
",",
"channel",
",",
"reason",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"params",
"=",
"[",
"channel",
"]",
"if",
"reason",
":",
"params",
".",
"append",
"(",
"reason",
")",
"self",
".",
"send",
"(",
"'PA... | 36.833333 | 11.666667 |
def envars_to_markdown(envars, title = "Environment"):
'''generate a markdown list of a list of environment variable tuples
Parameters
==========
title: A title for the section (defaults to "Environment"
envars: a list of tuples for the environment, e.g.:
[('TERM', 'xterm-2... | [
"def",
"envars_to_markdown",
"(",
"envars",
",",
"title",
"=",
"\"Environment\"",
")",
":",
"markdown",
"=",
"''",
"if",
"envars",
"not",
"in",
"[",
"None",
",",
"''",
",",
"[",
"]",
"]",
":",
"markdown",
"+=",
"'\\n## %s\\n'",
"%",
"title",
"for",
"en... | 32.7 | 19.8 |
def _validate_json_for_regular_workflow(json_spec, args):
"""
Validates fields used only for building a regular, project-based workflow.
"""
validated = {}
override_project_id, override_folder, override_workflow_name = \
dxpy.executable_builder.get_parsed_destination(args.destination)
va... | [
"def",
"_validate_json_for_regular_workflow",
"(",
"json_spec",
",",
"args",
")",
":",
"validated",
"=",
"{",
"}",
"override_project_id",
",",
"override_folder",
",",
"override_workflow_name",
"=",
"dxpy",
".",
"executable_builder",
".",
"get_parsed_destination",
"(",
... | 43.5625 | 23.6875 |
def inheritdoc(parent):
"""Inherit documentation from a parent
Parameters
----------
parent : callable
The parent function or class that contains the sought-after
docstring. If it doesn't have a docstring, this might behave
in unexpected ways.
Examples
--------
... | [
"def",
"inheritdoc",
"(",
"parent",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"# Assign the parent docstring to the child",
"func",
".",
"__doc__",
"=",
"parent",
".",
"__doc__",
"@",
"wraps",
"(",
"func",
")",
"def",
"caller",
"(",
"*",
"args",
"... | 22.571429 | 20.257143 |
def iam_configuration(self):
"""Retrieve IAM configuration for this bucket.
:rtype: :class:`IAMConfiguration`
:returns: an instance for managing the bucket's IAM configuration.
"""
info = self._properties.get("iamConfiguration", {})
return IAMConfiguration.from_api_repr(... | [
"def",
"iam_configuration",
"(",
"self",
")",
":",
"info",
"=",
"self",
".",
"_properties",
".",
"get",
"(",
"\"iamConfiguration\"",
",",
"{",
"}",
")",
"return",
"IAMConfiguration",
".",
"from_api_repr",
"(",
"info",
",",
"self",
")"
] | 40.5 | 15.375 |
def _ParseEntry(self, key, val):
"""Adds an entry for a configuration setting.
Args:
key: The name of the setting.
val: The value of the setting.
"""
if key in self._repeated:
setting = self.section.setdefault(key, [])
setting.extend(val)
else:
self.section.setdefault(... | [
"def",
"_ParseEntry",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"if",
"key",
"in",
"self",
".",
"_repeated",
":",
"setting",
"=",
"self",
".",
"section",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
"setting",
".",
"extend",
"(",
"val",
... | 26.5 | 12.833333 |
def _readFile(self, sldir, fileName, sep):
'''
Private method that reads in the header and column data.
'''
if sldir.endswith(os.sep):
fileName = str(sldir)+str(fileName)
else:
fileName = str(sldir)+os.sep+str(fileName)
fileLines=[] #list of li... | [
"def",
"_readFile",
"(",
"self",
",",
"sldir",
",",
"fileName",
",",
"sep",
")",
":",
"if",
"sldir",
".",
"endswith",
"(",
"os",
".",
"sep",
")",
":",
"fileName",
"=",
"str",
"(",
"sldir",
")",
"+",
"str",
"(",
"fileName",
")",
"else",
":",
"file... | 31 | 15.505051 |
def proxy_protocol(self, error='raise', default=None, limit=None, authenticate=False):
"""
Parses, and optionally authenticates, proxy protocol information from
request. Note that ``self.request`` is wrapped by ``SocketBuffer``.
:param error:
How read (``exc.ReadError``) and... | [
"def",
"proxy_protocol",
"(",
"self",
",",
"error",
"=",
"'raise'",
",",
"default",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"authenticate",
"=",
"False",
")",
":",
"if",
"error",
"not",
"in",
"(",
"'raise'",
",",
"'unread'",
")",
":",
"raise",
"... | 37.938776 | 18.755102 |
def receive(self, event_type, signature, data_str):
"""Receive a web hook for the event and signature.
Args:
event_type (str): Name of the event that was received (from the
request ``X-HelpScout-Event`` header).
signature (str): The signature that was received, w... | [
"def",
"receive",
"(",
"self",
",",
"event_type",
",",
"signature",
",",
"data_str",
")",
":",
"if",
"not",
"self",
".",
"validate_signature",
"(",
"signature",
",",
"data_str",
")",
":",
"raise",
"HelpScoutSecurityException",
"(",
"'The signature provided by this... | 39.875 | 23.84375 |
def explore(node):
""" Given a node, explores on relatives, siblings and children
:param node: GraphNode from which to explore
:return: set of explored GraphNodes
"""
explored = set()
explored.add(node)
dfs(node, callback=lambda n: explored.add(n))
return explored | [
"def",
"explore",
"(",
"node",
")",
":",
"explored",
"=",
"set",
"(",
")",
"explored",
".",
"add",
"(",
"node",
")",
"dfs",
"(",
"node",
",",
"callback",
"=",
"lambda",
"n",
":",
"explored",
".",
"add",
"(",
"n",
")",
")",
"return",
"explored"
] | 32 | 11 |
def scale(self, center=True, scale=True):
"""
Center and/or scale the columns of the current frame.
:param center: If True, then demean the data. If False, no shifting is done. If ``center`` is a list of
numbers then shift each column by the corresponding amount.
:param scal... | [
"def",
"scale",
"(",
"self",
",",
"center",
"=",
"True",
",",
"scale",
"=",
"True",
")",
":",
"return",
"H2OFrame",
".",
"_expr",
"(",
"expr",
"=",
"ExprNode",
"(",
"\"scale\"",
",",
"self",
",",
"center",
",",
"scale",
")",
",",
"cache",
"=",
"sel... | 62.363636 | 34.909091 |
def check_api_response(self, response):
"""Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check
"""
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400... | [
"def",
"check_api_response",
"(",
"self",
",",
"response",
")",
":",
"# check response",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
"elif",
"response",
".",
"status_code",
">=",
"400",
":",
"logging",
".",
"error",
"(",
"\"{}: ... | 34.944444 | 11.277778 |
def pass_time(self, t):
"""Non-blocking time-out for ``t`` seconds."""
cont = time.time() + t
while time.time() < cont:
time.sleep(0) | [
"def",
"pass_time",
"(",
"self",
",",
"t",
")",
":",
"cont",
"=",
"time",
".",
"time",
"(",
")",
"+",
"t",
"while",
"time",
".",
"time",
"(",
")",
"<",
"cont",
":",
"time",
".",
"sleep",
"(",
"0",
")"
] | 33 | 9.8 |
def generate_pages_by_file():
"""Generates custom pages of 'file' storage type."""
from veripress import app
from veripress.model import storage
from veripress.model.parsers import get_standard_format_name
from veripress.helpers import traverse_directory
deploy_dir = get_deploy_dir()
def c... | [
"def",
"generate_pages_by_file",
"(",
")",
":",
"from",
"veripress",
"import",
"app",
"from",
"veripress",
".",
"model",
"import",
"storage",
"from",
"veripress",
".",
"model",
".",
"parsers",
"import",
"get_standard_format_name",
"from",
"veripress",
".",
"helper... | 46.702703 | 17.189189 |
def _patch_expand_paths(self, settings, name, value):
"""
Apply ``SettingsPostProcessor._patch_expand_path`` to each element in
list.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (list): List of paths to patch.
Ret... | [
"def",
"_patch_expand_paths",
"(",
"self",
",",
"settings",
",",
"name",
",",
"value",
")",
":",
"return",
"[",
"self",
".",
"_patch_expand_path",
"(",
"settings",
",",
"name",
",",
"item",
")",
"for",
"item",
"in",
"value",
"]"
] | 29.8125 | 19.3125 |
def send_job_and_wait(self, message, body_params=None, timeout=None, raises=False):
""".. versionchanged:: 0.8.4
Send a message as a job and wait for the response.
.. note::
Not all messages are jobs, you'll have to find out which are which
:param message: a message instanc... | [
"def",
"send_job_and_wait",
"(",
"self",
",",
"message",
",",
"body_params",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"raises",
"=",
"False",
")",
":",
"job_id",
"=",
"self",
".",
"send_job",
"(",
"message",
",",
"body_params",
")",
"response",
"="... | 43.458333 | 18.666667 |
def correlation(df, cm=cm.PuOr_r, vmin=None, vmax=None, labels=None, show_scatter=False):
"""
Generate a column-wise correlation plot from the provided data.
The columns of the supplied dataframes will be correlated (using `analysis.correlation`) to
generate a Pearson correlation plot heatmap. Scatter ... | [
"def",
"correlation",
"(",
"df",
",",
"cm",
"=",
"cm",
".",
"PuOr_r",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"show_scatter",
"=",
"False",
")",
":",
"data",
"=",
"analysis",
".",
"correlation",
"(",
"df... | 32.212766 | 24.87234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.