repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
bhmm/bhmm | bhmm/estimators/bayesian_sampling.py | https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L329-L335 | def _updateEmissionProbabilities(self):
"""Sample a new set of emission probabilites from the conditional distribution P(E | S, O)
"""
observations_by_state = [self.model.collect_observations_in_state(self.observations, state)
for state in range(self.model.nstat... | [
"def",
"_updateEmissionProbabilities",
"(",
"self",
")",
":",
"observations_by_state",
"=",
"[",
"self",
".",
"model",
".",
"collect_observations_in_state",
"(",
"self",
".",
"observations",
",",
"state",
")",
"for",
"state",
"in",
"range",
"(",
"self",
".",
"... | Sample a new set of emission probabilites from the conditional distribution P(E | S, O) | [
"Sample",
"a",
"new",
"set",
"of",
"emission",
"probabilites",
"from",
"the",
"conditional",
"distribution",
"P",
"(",
"E",
"|",
"S",
"O",
")"
] | python | train | 54.285714 |
openego/ding0 | ding0/flexopt/reinforce_measures.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/flexopt/reinforce_measures.py#L139-L237 | def extend_substation(grid, critical_stations, grid_level):
"""
Reinforce MV or LV substation by exchanging the existing trafo and
installing a parallel one if necessary.
First, all available transformers in a `critical_stations` are extended to
maximum power. If this does not solve all present iss... | [
"def",
"extend_substation",
"(",
"grid",
",",
"critical_stations",
",",
"grid_level",
")",
":",
"load_factor_lv_trans_lc_normal",
"=",
"cfg_ding0",
".",
"get",
"(",
"'assumptions'",
",",
"'load_factor_lv_trans_lc_normal'",
")",
"load_factor_lv_trans_fc_normal",
"=",
"cfg_... | Reinforce MV or LV substation by exchanging the existing trafo and
installing a parallel one if necessary.
First, all available transformers in a `critical_stations` are extended to
maximum power. If this does not solve all present issues, additional
transformers are build.
Parameters
--------... | [
"Reinforce",
"MV",
"or",
"LV",
"substation",
"by",
"exchanging",
"the",
"existing",
"trafo",
"and",
"installing",
"a",
"parallel",
"one",
"if",
"necessary",
"."
] | python | train | 37.343434 |
zhihu/redis-shard | redis_shard/helpers.py | https://github.com/zhihu/redis-shard/blob/57c166ef7d55f7272b50efc1dedc1f6ed4691137/redis_shard/helpers.py#L7-L40 | def format_servers(servers):
"""
:param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':'node3','host':'127.0.0.1','por... | [
"def",
"format_servers",
"(",
"servers",
")",
":",
"configs",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"servers",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"server's config must be list\"",
")",
"_type",
"=",
"type",
"(",
"servers",
"[",
"... | :param servers: server list, element in it can have two kinds of format.
- dict
servers = [
{'name':'node1','host':'127.0.0.1','port':10000,'db':0},
{'name':'node2','host':'127.0.0.1','port':11000,'db':0},
{'name':'node3','host':'127.0.0.1','port':12000,'db':0},
]
- url_s... | [
":",
"param",
"servers",
":",
"server",
"list",
"element",
"in",
"it",
"can",
"have",
"two",
"kinds",
"of",
"format",
"."
] | python | valid | 29.235294 |
TeamHG-Memex/eli5 | eli5/formatters/trees.py | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/trees.py#L7-L49 | def tree2text(tree_obj, indent=4):
# type: (TreeInfo, int) -> str
"""
Return text representation of a decision tree.
"""
parts = []
def _format_node(node, depth=0):
# type: (NodeInfo, int) -> None
def p(*args):
# type: (*str) -> None
parts.append(" " * de... | [
"def",
"tree2text",
"(",
"tree_obj",
",",
"indent",
"=",
"4",
")",
":",
"# type: (TreeInfo, int) -> str",
"parts",
"=",
"[",
"]",
"def",
"_format_node",
"(",
"node",
",",
"depth",
"=",
"0",
")",
":",
"# type: (NodeInfo, int) -> None",
"def",
"p",
"(",
"*",
... | Return text representation of a decision tree. | [
"Return",
"text",
"representation",
"of",
"a",
"decision",
"tree",
"."
] | python | train | 32.651163 |
boriel/zxbasic | arch/zx48k/backend/__array.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__array.py#L81-L94 | def _aload16(ins):
''' Loads a 16 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
'''
output = _addr(ins.quad[2])
output.append('ld e, (hl)')
output.append('inc hl')
output.append('ld d, (hl)')
output.append('ex de, hl')
out... | [
"def",
"_aload16",
"(",
"ins",
")",
":",
"output",
"=",
"_addr",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
")",
"output",
".",
"append",
"(",
"'ld e, (hl)'",
")",
"output",
".",
"append",
"(",
"'inc hl'",
")",
"output",
".",
"append",
"(",
"'ld d, (hl)... | Loads a 16 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value. | [
"Loads",
"a",
"16",
"bit",
"value",
"from",
"a",
"memory",
"address",
"If",
"2nd",
"arg",
".",
"start",
"with",
"*",
"it",
"is",
"always",
"treated",
"as",
"an",
"indirect",
"value",
"."
] | python | train | 24.785714 |
emilydolson/avida-spatial-tools | avidaspatial/transform_data.py | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/transform_data.py#L35-L58 | def do_clustering(types, max_clust):
"""
Helper method for clustering that takes a list of all of the things being
clustered (which are assumed to be binary numbers represented as strings),
and an int representing the maximum number of clusters that are allowed.
Returns: A dictionary mapping cluste... | [
"def",
"do_clustering",
"(",
"types",
",",
"max_clust",
")",
":",
"# Fill in leading zeros to make all numbers same length.",
"ls",
"=",
"[",
"list",
"(",
"t",
"[",
"t",
".",
"find",
"(",
"\"b\"",
")",
"+",
"1",
":",
"]",
")",
"for",
"t",
"in",
"types",
... | Helper method for clustering that takes a list of all of the things being
clustered (which are assumed to be binary numbers represented as strings),
and an int representing the maximum number of clusters that are allowed.
Returns: A dictionary mapping cluster ids to lists of numbers that are part
of th... | [
"Helper",
"method",
"for",
"clustering",
"that",
"takes",
"a",
"list",
"of",
"all",
"of",
"the",
"things",
"being",
"clustered",
"(",
"which",
"are",
"assumed",
"to",
"be",
"binary",
"numbers",
"represented",
"as",
"strings",
")",
"and",
"an",
"int",
"repr... | python | train | 39.666667 |
hydpy-dev/hydpy | hydpy/core/hydpytools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/hydpytools.py#L465-L483 | def numberofnetworks(self):
"""The number of distinct networks defined by the|Node| and
|Element| objects currently handled by the |HydPy| object."""
sels1 = selectiontools.Selections()
sels2 = selectiontools.Selections()
complete = selectiontools.Selection('complete',
... | [
"def",
"numberofnetworks",
"(",
"self",
")",
":",
"sels1",
"=",
"selectiontools",
".",
"Selections",
"(",
")",
"sels2",
"=",
"selectiontools",
".",
"Selections",
"(",
")",
"complete",
"=",
"selectiontools",
".",
"Selection",
"(",
"'complete'",
",",
"self",
"... | The number of distinct networks defined by the|Node| and
|Element| objects currently handled by the |HydPy| object. | [
"The",
"number",
"of",
"distinct",
"networks",
"defined",
"by",
"the|Node|",
"and",
"|Element|",
"objects",
"currently",
"handled",
"by",
"the",
"|HydPy|",
"object",
"."
] | python | train | 41.842105 |
inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/checkers.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/checkers.py#L176-L242 | def check_arguments_compatibility(the_callable, argd):
"""
Check if calling the_callable with the given arguments would be correct
or not.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'})
... | [
"def",
"check_arguments_compatibility",
"(",
"the_callable",
",",
"argd",
")",
":",
"if",
"not",
"argd",
":",
"argd",
"=",
"{",
"}",
"args",
",",
"dummy",
",",
"varkw",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"the_callable",
")",
"tmp_args... | Check if calling the_callable with the given arguments would be correct
or not.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> try: check_arguments_compatibility(foo, {'arg1': 'bla', 'arg2': 'blo'})
... except ValueError as err: print 'failed'
... else: print... | [
"Check",
"if",
"calling",
"the_callable",
"with",
"the",
"given",
"arguments",
"would",
"be",
"correct",
"or",
"not",
"."
] | python | train | 30.776119 |
Gandi/gandi.cli | gandi/cli/commands/dns.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/dns.py#L231-L242 | def keys_delete(gandi, fqdn, key, force):
"""Delete a key for a domain."""
if not force:
proceed = click.confirm('Are you sure you want to delete key %s on '
'domain %s?' % (key, fqdn))
if not proceed:
return
result = gandi.dns.keys_delete(fqdn, ... | [
"def",
"keys_delete",
"(",
"gandi",
",",
"fqdn",
",",
"key",
",",
"force",
")",
":",
"if",
"not",
"force",
":",
"proceed",
"=",
"click",
".",
"confirm",
"(",
"'Are you sure you want to delete key %s on '",
"'domain %s?'",
"%",
"(",
"key",
",",
"fqdn",
")",
... | Delete a key for a domain. | [
"Delete",
"a",
"key",
"for",
"a",
"domain",
"."
] | python | train | 30.666667 |
assamite/creamas | creamas/mp.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L704-L729 | async def spawn(self, agent_cls, *args, addr=None, **kwargs):
"""Spawn a new agent in a slave environment.
:param str agent_cls:
`qualname`` of the agent class.
That is, the name should be in the form ``pkg.mod:cls``, e.g.
``creamas.core.agent:CreativeAgent``.
... | [
"async",
"def",
"spawn",
"(",
"self",
",",
"agent_cls",
",",
"*",
"args",
",",
"addr",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"addr",
"is",
"None",
":",
"addr",
"=",
"await",
"self",
".",
"_get_smallest_env",
"(",
")",
"r_manager",
"... | Spawn a new agent in a slave environment.
:param str agent_cls:
`qualname`` of the agent class.
That is, the name should be in the form ``pkg.mod:cls``, e.g.
``creamas.core.agent:CreativeAgent``.
:param str addr:
Optional. Address for the slave enviroment... | [
"Spawn",
"a",
"new",
"agent",
"in",
"a",
"slave",
"environment",
"."
] | python | train | 40.653846 |
rigetti/pyquil | pyquil/quilatom.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quilatom.py#L516-L531 | def _contained_parameters(expression):
"""
Determine which parameters are contained in this expression.
:param Expression expression: expression involving parameters
:return: set of parameters contained in this expression
:rtype: set
"""
if isinstance(expression, BinaryExp):
return ... | [
"def",
"_contained_parameters",
"(",
"expression",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"BinaryExp",
")",
":",
"return",
"_contained_parameters",
"(",
"expression",
".",
"op1",
")",
"|",
"_contained_parameters",
"(",
"expression",
".",
"op2",
")... | Determine which parameters are contained in this expression.
:param Expression expression: expression involving parameters
:return: set of parameters contained in this expression
:rtype: set | [
"Determine",
"which",
"parameters",
"are",
"contained",
"in",
"this",
"expression",
"."
] | python | train | 36.75 |
MChiciak/django-datatools | django_datatools/data_retriever.py | https://github.com/MChiciak/django-datatools/blob/666cd9fb2693878e8a9b5d27ceaa2e09aaca2f60/django_datatools/data_retriever.py#L42-L68 | def bulk_get_or_create(self, data_list):
"""
data_list is the data to get or create
We generate the query and set all the record keys based on passed in queryset
Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot of time... | [
"def",
"bulk_get_or_create",
"(",
"self",
",",
"data_list",
")",
":",
"items_to_create",
"=",
"dict",
"(",
")",
"for",
"record_key",
",",
"record_config",
"in",
"data_list",
".",
"items",
"(",
")",
":",
"if",
"record_key",
"not",
"in",
"items_to_create",
":"... | data_list is the data to get or create
We generate the query and set all the record keys based on passed in queryset
Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot of time
Use values instead of the whole object, much faster
... | [
"data_list",
"is",
"the",
"data",
"to",
"get",
"or",
"create",
"We",
"generate",
"the",
"query",
"and",
"set",
"all",
"the",
"record",
"keys",
"based",
"on",
"passed",
"in",
"queryset",
"Then",
"we",
"loop",
"over",
"each",
"item",
"in",
"the",
"data_lis... | python | train | 43.740741 |
czepluch/pysecp256k1 | c_secp256k1/__init__.py | https://github.com/czepluch/pysecp256k1/blob/164cb305857c5ba7a26adb6bd85459c5ea32ddd1/c_secp256k1/__init__.py#L213-L233 | def ecdsa_sign_compact(msg32, seckey):
"""
Takes the same message and seckey as _ecdsa_sign_recoverable
Returns an unsigned char array of length 65 containing the signed message
"""
# Assign 65 bytes to output
output64 = ffi.new("unsigned char[65]")
# ffi definition of recid
reci... | [
"def",
"ecdsa_sign_compact",
"(",
"msg32",
",",
"seckey",
")",
":",
"# Assign 65 bytes to output",
"output64",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[65]\"",
")",
"# ffi definition of recid",
"recid",
"=",
"ffi",
".",
"new",
"(",
"\"int *\"",
")",
"lib",
... | Takes the same message and seckey as _ecdsa_sign_recoverable
Returns an unsigned char array of length 65 containing the signed message | [
"Takes",
"the",
"same",
"message",
"and",
"seckey",
"as",
"_ecdsa_sign_recoverable",
"Returns",
"an",
"unsigned",
"char",
"array",
"of",
"length",
"65",
"containing",
"the",
"signed",
"message"
] | python | train | 30.952381 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32_controller.py#L497-L500 | def _stderr_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stderr)
sys.stderr.flush() | [
"def",
"_stderr_raw",
"(",
"self",
",",
"s",
")",
":",
"print",
"(",
"s",
",",
"end",
"=",
"''",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | Writes the string to stdout | [
"Writes",
"the",
"string",
"to",
"stdout"
] | python | test | 33.25 |
pandas-dev/pandas | pandas/io/pytables.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L3743-L3766 | def create_description(self, complib=None, complevel=None,
fletcher32=False, expectedrows=None):
""" create the description of the table from the axes & values """
# provided expected rows if its passed
if expectedrows is None:
expectedrows = max(self.nrow... | [
"def",
"create_description",
"(",
"self",
",",
"complib",
"=",
"None",
",",
"complevel",
"=",
"None",
",",
"fletcher32",
"=",
"False",
",",
"expectedrows",
"=",
"None",
")",
":",
"# provided expected rows if its passed",
"if",
"expectedrows",
"is",
"None",
":",
... | create the description of the table from the axes & values | [
"create",
"the",
"description",
"of",
"the",
"table",
"from",
"the",
"axes",
"&",
"values"
] | python | train | 36.458333 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/widgetdelegate.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L393-L459 | def propagate_event_to_delegate(self, event, eventhandler):
"""Propagate the given Mouse event to the widgetdelegate
Enter edit mode, get the editor widget and issue an event on that widget.
:param event: the mouse event
:type event: :class:`QtGui.QMouseEvent`
:param eventhandl... | [
"def",
"propagate_event_to_delegate",
"(",
"self",
",",
"event",
",",
"eventhandler",
")",
":",
"# if we are recursing because we sent a click event, and it got propagated to the parents",
"# and we recieve it again, terminate",
"if",
"self",
".",
"__recursing",
":",
"return",
"#... | Propagate the given Mouse event to the widgetdelegate
Enter edit mode, get the editor widget and issue an event on that widget.
:param event: the mouse event
:type event: :class:`QtGui.QMouseEvent`
:param eventhandler: the eventhandler to use. E.g. ``"mousePressEvent"``
:type e... | [
"Propagate",
"the",
"given",
"Mouse",
"event",
"to",
"the",
"widgetdelegate"
] | python | train | 41.089552 |
gwastro/pycbc | pycbc/waveform/waveform.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/waveform.py#L694-L730 | def get_sgburst_waveform(template=None, **kwargs):
"""Return the plus and cross polarizations of a time domain
sine-Gaussian burst waveform.
Parameters
----------
template: object
An object that has attached properties. This can be used to subsitute
for keyword arguments. A common e... | [
"def",
"get_sgburst_waveform",
"(",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"input_params",
"=",
"props_sgburst",
"(",
"template",
",",
"*",
"*",
"kwargs",
")",
"for",
"arg",
"in",
"sgburst_required_args",
":",
"if",
"arg",
"not",
"in",... | Return the plus and cross polarizations of a time domain
sine-Gaussian burst waveform.
Parameters
----------
template: object
An object that has attached properties. This can be used to subsitute
for keyword arguments. A common example would be a row in an xml table.
approximant : s... | [
"Return",
"the",
"plus",
"and",
"cross",
"polarizations",
"of",
"a",
"time",
"domain",
"sine",
"-",
"Gaussian",
"burst",
"waveform",
"."
] | python | train | 31.675676 |
WebarchivCZ/WA-KAT | src/wa_kat/rest_api/virtual_fs.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/rest_api/virtual_fs.py#L112-L188 | def conspectus_api():
"""
Virtual ``conspectus.py`` file for brython. This file contains following
variables:
Attributes:
consp_dict (dict): Dictionary with conspects.
cosp_id_pairs (list): List of tuples ``(name, id)`` for conspectus.
subs_by_mdt (dict): Dictionary containing `... | [
"def",
"conspectus_api",
"(",
")",
":",
"def",
"to_json",
"(",
"data",
")",
":",
"\"\"\"\n JSON conversion is used, because brython has BIG performance issues\n when parsing large python sources. It is actually cheaper to just load\n it as JSON objects.\n\n Load tim... | Virtual ``conspectus.py`` file for brython. This file contains following
variables:
Attributes:
consp_dict (dict): Dictionary with conspects.
cosp_id_pairs (list): List of tuples ``(name, id)`` for conspectus.
subs_by_mdt (dict): Dictionary containing ``mdt: sub_dict``.
mdt_by_n... | [
"Virtual",
"conspectus",
".",
"py",
"file",
"for",
"brython",
".",
"This",
"file",
"contains",
"following",
"variables",
":"
] | python | train | 30.766234 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L1104-L1114 | def start(self, n):
"""Start n copies of the process using a batch system."""
self.log.debug("Starting %s: %r", self.__class__.__name__, self.args)
# Here we save profile_dir in the context so they
# can be used in the batch script template as {profile_dir}
self.write_batch_scrip... | [
"def",
"start",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Starting %s: %r\"",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"args",
")",
"# Here we save profile_dir in the context so they",
"# can be used in t... | Start n copies of the process using a batch system. | [
"Start",
"n",
"copies",
"of",
"the",
"process",
"using",
"a",
"batch",
"system",
"."
] | python | test | 42.818182 |
dwavesystems/penaltymodel | penaltymodel_cache/penaltymodel/cache/database_manager.py | https://github.com/dwavesystems/penaltymodel/blob/b9d343233aea8df0f59cea45a07f12d0b3b8d9b3/penaltymodel_cache/penaltymodel/cache/database_manager.py#L517-L583 | def iter_penalty_model_from_specification(cur, specification):
"""Iterate through all penalty models in the cache matching the
given specification.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
specificat... | [
"def",
"iter_penalty_model_from_specification",
"(",
"cur",
",",
"specification",
")",
":",
"encoded_data",
"=",
"{",
"}",
"nodelist",
"=",
"sorted",
"(",
"specification",
".",
"graph",
")",
"edgelist",
"=",
"sorted",
"(",
"sorted",
"(",
"edge",
")",
"for",
... | Iterate through all penalty models in the cache matching the
given specification.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
specification (:class:`penaltymodel.Specification`): A specification
... | [
"Iterate",
"through",
"all",
"penalty",
"models",
"in",
"the",
"cache",
"matching",
"the",
"given",
"specification",
"."
] | python | train | 42.268657 |
inonit/drf-haystack | drf_haystack/query.py | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L266-L318 | def build_query(self, **filters):
"""
Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latit... | [
"def",
"build_query",
"(",
"self",
",",
"*",
"*",
"filters",
")",
":",
"applicable_filters",
"=",
"None",
"filters",
"=",
"dict",
"(",
"(",
"k",
",",
"filters",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"chain",
"(",
"self",
".",
"D",
".",
"UNITS",
"... | Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latitude and longitude.
Example query:
... | [
"Build",
"queries",
"for",
"geo",
"spatial",
"filtering",
"."
] | python | train | 41.660377 |
bitesofcode/projex | projex/security.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/security.py#L157-L191 | def encryptfile(filename, key=None, outfile=None, chunk=64 * 1024):
"""
Encrypts a file using AES (CBC mode) with the given key. If no
file is supplied, then the inputted file will be modified in place.
The chunk value will be the size with which the function uses to
read and encrypt the file. Lar... | [
"def",
"encryptfile",
"(",
"filename",
",",
"key",
"=",
"None",
",",
"outfile",
"=",
"None",
",",
"chunk",
"=",
"64",
"*",
"1024",
")",
":",
"if",
"key",
"is",
"None",
":",
"key",
"=",
"ENCRYPT_KEY",
"if",
"not",
"outfile",
":",
"outfile",
"=",
"fi... | Encrypts a file using AES (CBC mode) with the given key. If no
file is supplied, then the inputted file will be modified in place.
The chunk value will be the size with which the function uses to
read and encrypt the file. Larger chunks can be faster for some files
and machines. The chunk MUST be div... | [
"Encrypts",
"a",
"file",
"using",
"AES",
"(",
"CBC",
"mode",
")",
"with",
"the",
"given",
"key",
".",
"If",
"no",
"file",
"is",
"supplied",
"then",
"the",
"inputted",
"file",
"will",
"be",
"modified",
"in",
"place",
".",
"The",
"chunk",
"value",
"will"... | python | train | 32.514286 |
saltstack/salt | salt/modules/saltcheck.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltcheck.py#L749-L758 | def __assert_less(expected, returned):
'''
Test if a value is less than the returned value
'''
result = "Pass"
try:
assert (expected < returned), "{0} not False".format(returned)
except AssertionError as err:
result = "Fail: " + six.text_type(err)
... | [
"def",
"__assert_less",
"(",
"expected",
",",
"returned",
")",
":",
"result",
"=",
"\"Pass\"",
"try",
":",
"assert",
"(",
"expected",
"<",
"returned",
")",
",",
"\"{0} not False\"",
".",
"format",
"(",
"returned",
")",
"except",
"AssertionError",
"as",
"err"... | Test if a value is less than the returned value | [
"Test",
"if",
"a",
"value",
"is",
"less",
"than",
"the",
"returned",
"value"
] | python | train | 33.2 |
klen/starter | starter/core.py | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L105-L109 | def params(self):
""" Read self params from configuration. """
parser = JinjaInterpolationNamespace()
parser.read(self.configuration)
return dict(parser['params'] or {}) | [
"def",
"params",
"(",
"self",
")",
":",
"parser",
"=",
"JinjaInterpolationNamespace",
"(",
")",
"parser",
".",
"read",
"(",
"self",
".",
"configuration",
")",
"return",
"dict",
"(",
"parser",
"[",
"'params'",
"]",
"or",
"{",
"}",
")"
] | Read self params from configuration. | [
"Read",
"self",
"params",
"from",
"configuration",
"."
] | python | train | 39.4 |
ranaroussi/pywallet | pywallet/utils/bip32.py | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L479-L482 | def serialize_b58(self, private=True):
"""Encode the serialized node in base58."""
return ensure_str(
base58.b58encode_check(unhexlify(self.serialize(private)))) | [
"def",
"serialize_b58",
"(",
"self",
",",
"private",
"=",
"True",
")",
":",
"return",
"ensure_str",
"(",
"base58",
".",
"b58encode_check",
"(",
"unhexlify",
"(",
"self",
".",
"serialize",
"(",
"private",
")",
")",
")",
")"
] | Encode the serialized node in base58. | [
"Encode",
"the",
"serialized",
"node",
"in",
"base58",
"."
] | python | train | 46.5 |
cloud9ers/pylxc | lxc/__init__.py | https://github.com/cloud9ers/pylxc/blob/588961dd37ce6e14fd7c1cc76d1970e48fccba34/lxc/__init__.py#L147-L157 | def all_as_list():
'''
returns a list of all defined containers
'''
as_dict = all_as_dict()
containers = as_dict['Running'] + as_dict['Frozen'] + as_dict['Stopped']
containers_list = []
for i in containers:
i = i.replace(' (auto)', '')
containers_list.append(i)
... | [
"def",
"all_as_list",
"(",
")",
":",
"as_dict",
"=",
"all_as_dict",
"(",
")",
"containers",
"=",
"as_dict",
"[",
"'Running'",
"]",
"+",
"as_dict",
"[",
"'Frozen'",
"]",
"+",
"as_dict",
"[",
"'Stopped'",
"]",
"containers_list",
"=",
"[",
"]",
"for",
"i",
... | returns a list of all defined containers | [
"returns",
"a",
"list",
"of",
"all",
"defined",
"containers"
] | python | train | 30.272727 |
NYUCCL/psiTurk | psiturk/psiturk_shell.py | https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_shell.py#L224-L232 | def _confirm_dialog(self, prompt):
''' Prompts for a 'yes' or 'no' to given prompt. '''
response = raw_input(prompt).strip().lower()
valid = {'y': True, 'ye': True, 'yes': True, 'n': False, 'no': False}
while True:
try:
return valid[response]
excep... | [
"def",
"_confirm_dialog",
"(",
"self",
",",
"prompt",
")",
":",
"response",
"=",
"raw_input",
"(",
"prompt",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"valid",
"=",
"{",
"'y'",
":",
"True",
",",
"'ye'",
":",
"True",
",",
"'yes'",
":",
... | Prompts for a 'yes' or 'no' to given prompt. | [
"Prompts",
"for",
"a",
"yes",
"or",
"no",
"to",
"given",
"prompt",
"."
] | python | train | 44.222222 |
buildbot/buildbot | master/buildbot/process/remotetransfer.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/process/remotetransfer.py#L51-L66 | def remote_write(self, data):
"""
Called from remote worker to write L{data} to L{fp} within boundaries
of L{maxsize}
@type data: C{string}
@param data: String of data to write
"""
data = unicode2bytes(data)
if self.remaining is not None:
if ... | [
"def",
"remote_write",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"unicode2bytes",
"(",
"data",
")",
"if",
"self",
".",
"remaining",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"data",
")",
">",
"self",
".",
"remaining",
":",
"data",
"=",
"da... | Called from remote worker to write L{data} to L{fp} within boundaries
of L{maxsize}
@type data: C{string}
@param data: String of data to write | [
"Called",
"from",
"remote",
"worker",
"to",
"write",
"L",
"{",
"data",
"}",
"to",
"L",
"{",
"fp",
"}",
"within",
"boundaries",
"of",
"L",
"{",
"maxsize",
"}"
] | python | train | 31.9375 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/nose/tools/nontrivial.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/tools/nontrivial.py#L73-L82 | def set_trace():
"""Call pdb.set_trace in the calling frame, first restoring
sys.stdout to the real output stream. Note that sys.stdout is NOT
reset to whatever it was before the call once pdb is done!
"""
import pdb
import sys
stdout = sys.stdout
sys.stdout = sys.__stdout__
pdb.Pdb(... | [
"def",
"set_trace",
"(",
")",
":",
"import",
"pdb",
"import",
"sys",
"stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"sys",
".",
"__stdout__",
"pdb",
".",
"Pdb",
"(",
")",
".",
"set_trace",
"(",
"sys",
".",
"_getframe",
"(",
")",
".... | Call pdb.set_trace in the calling frame, first restoring
sys.stdout to the real output stream. Note that sys.stdout is NOT
reset to whatever it was before the call once pdb is done! | [
"Call",
"pdb",
".",
"set_trace",
"in",
"the",
"calling",
"frame",
"first",
"restoring",
"sys",
".",
"stdout",
"to",
"the",
"real",
"output",
"stream",
".",
"Note",
"that",
"sys",
".",
"stdout",
"is",
"NOT",
"reset",
"to",
"whatever",
"it",
"was",
"before... | python | test | 34.6 |
yamcs/yamcs-python | yamcs-client/yamcs/client.py | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L280-L290 | def stop_service(self, instance, service):
"""
Stops a single service.
:param str instance: A Yamcs instance name.
:param str service: The name of the service.
"""
req = rest_pb2.EditServiceRequest()
req.state = 'stopped'
url = '/services/{}/{}'.format(in... | [
"def",
"stop_service",
"(",
"self",
",",
"instance",
",",
"service",
")",
":",
"req",
"=",
"rest_pb2",
".",
"EditServiceRequest",
"(",
")",
"req",
".",
"state",
"=",
"'stopped'",
"url",
"=",
"'/services/{}/{}'",
".",
"format",
"(",
"instance",
",",
"servic... | Stops a single service.
:param str instance: A Yamcs instance name.
:param str service: The name of the service. | [
"Stops",
"a",
"single",
"service",
"."
] | python | train | 35.090909 |
CalebBell/thermo | thermo/utils.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3485-L3561 | def plot_isotherm(self, T, zs, ws, Pmin=None, Pmax=None, methods=[], pts=50,
only_valid=True): # pragma: no cover
r'''Method to create a plot of the property vs pressure at a specified
temperature and composition according to either a specified list of
methods, or the us... | [
"def",
"plot_isotherm",
"(",
"self",
",",
"T",
",",
"zs",
",",
"ws",
",",
"Pmin",
"=",
"None",
",",
"Pmax",
"=",
"None",
",",
"methods",
"=",
"[",
"]",
",",
"pts",
"=",
"50",
",",
"only_valid",
"=",
"True",
")",
":",
"# pragma: no cover",
"# This f... | r'''Method to create a plot of the property vs pressure at a specified
temperature and composition according to either a specified list of
methods, or the user methods (if set), or all methods. User-selectable
number of points, and pressure range. If only_valid is set,
`test_method_v... | [
"r",
"Method",
"to",
"create",
"a",
"plot",
"of",
"the",
"property",
"vs",
"pressure",
"at",
"a",
"specified",
"temperature",
"and",
"composition",
"according",
"to",
"either",
"a",
"specified",
"list",
"of",
"methods",
"or",
"the",
"user",
"methods",
"(",
... | python | valid | 46.987013 |
crytic/slither | slither/analyses/data_dependency/data_dependency.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/analyses/data_dependency/data_dependency.py#L66-L83 | def is_tainted(variable, context, only_unprotected=False, ignore_generic_taint=False):
'''
Args:
variable
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool
'''
assert isinstance(context, (Contract, Fun... | [
"def",
"is_tainted",
"(",
"variable",
",",
"context",
",",
"only_unprotected",
"=",
"False",
",",
"ignore_generic_taint",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"context",
",",
"(",
"Contract",
",",
"Function",
")",
")",
"assert",
"isinstance",
... | Args:
variable
context (Contract|Function)
only_unprotected (bool): True only unprotected function are considered
Returns:
bool | [
"Args",
":",
"variable",
"context",
"(",
"Contract|Function",
")",
"only_unprotected",
"(",
"bool",
")",
":",
"True",
"only",
"unprotected",
"function",
"are",
"considered",
"Returns",
":",
"bool"
] | python | train | 36.555556 |
aio-libs/aioftp | aioftp/client.py | https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/client.py#L365-L388 | def parse_ls_date(self, s, *, now=None):
"""
Parsing dates from the ls unix utility. For example,
"Nov 18 1958" and "Nov 18 12:29".
:param s: ls date
:type s: :py:class:`str`
:rtype: :py:class:`str`
"""
with setlocale("C"):
try:
... | [
"def",
"parse_ls_date",
"(",
"self",
",",
"s",
",",
"*",
",",
"now",
"=",
"None",
")",
":",
"with",
"setlocale",
"(",
"\"C\"",
")",
":",
"try",
":",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
... | Parsing dates from the ls unix utility. For example,
"Nov 18 1958" and "Nov 18 12:29".
:param s: ls date
:type s: :py:class:`str`
:rtype: :py:class:`str` | [
"Parsing",
"dates",
"from",
"the",
"ls",
"unix",
"utility",
".",
"For",
"example",
"Nov",
"18",
"1958",
"and",
"Nov",
"18",
"12",
":",
"29",
"."
] | python | valid | 36.25 |
HttpRunner/HttpRunner | httprunner/built_in.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/built_in.py#L27-L31 | def gen_random_string(str_len):
""" generate random string with specified length
"""
return ''.join(
random.choice(string.ascii_letters + string.digits) for _ in range(str_len)) | [
"def",
"gen_random_string",
"(",
"str_len",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"for",
"_",
"in",
"range",
"(",
"str_len",
")",
")"
] | generate random string with specified length | [
"generate",
"random",
"string",
"with",
"specified",
"length"
] | python | train | 38.6 |
numenta/nupic | src/nupic/algorithms/backtracking_tm_cpp.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm_cpp.py#L266-L284 | def _initEphemerals(self):
"""
Initialize all ephemeral members after being restored to a pickled state.
"""
BacktrackingTM._initEphemerals(self)
#---------------------------------------------------------------------------------
# cells4 specific initialization
# If True, let C++ allocate m... | [
"def",
"_initEphemerals",
"(",
"self",
")",
":",
"BacktrackingTM",
".",
"_initEphemerals",
"(",
"self",
")",
"#---------------------------------------------------------------------------------",
"# cells4 specific initialization",
"# If True, let C++ allocate memory for activeState, pred... | Initialize all ephemeral members after being restored to a pickled state. | [
"Initialize",
"all",
"ephemeral",
"members",
"after",
"being",
"restored",
"to",
"a",
"pickled",
"state",
"."
] | python | valid | 41.052632 |
biocore/burrito-fillings | bfillings/clustalw.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/clustalw.py#L381-L397 | def alignTwoAlignments(aln1,aln2,outfile,WorkingDir=None,SuppressStderr=None,\
SuppressStdout=None):
"""Aligns two alignments. Individual sequences are not realigned
aln1: string, name of file containing the first alignment
aln2: string, name of file containing the second alignment
outfile: you're ... | [
"def",
"alignTwoAlignments",
"(",
"aln1",
",",
"aln2",
",",
"outfile",
",",
"WorkingDir",
"=",
"None",
",",
"SuppressStderr",
"=",
"None",
",",
"SuppressStdout",
"=",
"None",
")",
":",
"app",
"=",
"Clustalw",
"(",
"{",
"'-profile'",
":",
"None",
",",
"'-... | Aligns two alignments. Individual sequences are not realigned
aln1: string, name of file containing the first alignment
aln2: string, name of file containing the second alignment
outfile: you're forced to specify an outfile name, because if you don't
aln1 will be overwritten. So, if you want aln1 t... | [
"Aligns",
"two",
"alignments",
".",
"Individual",
"sequences",
"are",
"not",
"realigned"
] | python | train | 50.058824 |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/optoanalysis.py | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/optoanalysis.py#L2605-L2651 | def animate_2Dscatter(x, y, NumAnimatedPoints=50, NTrailPoints=20,
xlabel="", ylabel="",
xlims=None, ylims=None, filename="testAnim.mp4",
bitrate=1e5, dpi=5e2, fps=30, figsize = [6, 6]):
"""
Animates x and y - where x and y are 1d arrays of x and y
positions and it plots x[i:i+NTrailPoints] a... | [
"def",
"animate_2Dscatter",
"(",
"x",
",",
"y",
",",
"NumAnimatedPoints",
"=",
"50",
",",
"NTrailPoints",
"=",
"20",
",",
"xlabel",
"=",
"\"\"",
",",
"ylabel",
"=",
"\"\"",
",",
"xlims",
"=",
"None",
",",
"ylims",
"=",
"None",
",",
"filename",
"=",
"... | Animates x and y - where x and y are 1d arrays of x and y
positions and it plots x[i:i+NTrailPoints] and y[i:i+NTrailPoints]
against each other and iterates through i. | [
"Animates",
"x",
"and",
"y",
"-",
"where",
"x",
"and",
"y",
"are",
"1d",
"arrays",
"of",
"x",
"and",
"y",
"positions",
"and",
"it",
"plots",
"x",
"[",
"i",
":",
"i",
"+",
"NTrailPoints",
"]",
"and",
"y",
"[",
"i",
":",
"i",
"+",
"NTrailPoints",
... | python | train | 33.042553 |
flashashen/flange | flange/iterutils.py | https://github.com/flashashen/flange/blob/67ebaf70e39887f65ce1163168d182a8e4c2774a/flange/iterutils.py#L1298-L1341 | def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True):
"""
Query function given to visit method
:param p: visited path in tuple form
:param k: visited key
:param v: visited value
:param accepted_keys: list of keys where one must match k to satisfy query.
:par... | [
"def",
"__query",
"(",
"p",
",",
"k",
",",
"v",
",",
"accepted_keys",
"=",
"None",
",",
"required_values",
"=",
"None",
",",
"path",
"=",
"None",
",",
"exact",
"=",
"True",
")",
":",
"# if not k:",
"# print '__query p k:', p, k",
"# print p, k, accepted_ke... | Query function given to visit method
:param p: visited path in tuple form
:param k: visited key
:param v: visited value
:param accepted_keys: list of keys where one must match k to satisfy query.
:param required_values: list of values where one must match v to satisfy query
:param path: exact p... | [
"Query",
"function",
"given",
"to",
"visit",
"method"
] | python | train | 40.25 |
saltstack/salt | salt/utils/win_update.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L368-L484 | def available(self,
skip_hidden=True,
skip_installed=True,
skip_mandatory=False,
skip_reboot=False,
software=True,
drivers=True,
categories=None,
severities=None):
'''
... | [
"def",
"available",
"(",
"self",
",",
"skip_hidden",
"=",
"True",
",",
"skip_installed",
"=",
"True",
",",
"skip_mandatory",
"=",
"False",
",",
"skip_reboot",
"=",
"False",
",",
"software",
"=",
"True",
",",
"drivers",
"=",
"True",
",",
"categories",
"=",
... | Gets a list of all updates available on the system that match the passed
criteria.
Args:
skip_hidden (bool): Skip hidden updates. Default is True
skip_installed (bool): Skip installed updates. Default is True
skip_mandatory (bool): Skip mandatory updates. Default ... | [
"Gets",
"a",
"list",
"of",
"all",
"updates",
"available",
"on",
"the",
"system",
"that",
"match",
"the",
"passed",
"criteria",
"."
] | python | train | 30.606838 |
quantopian/zipline | zipline/data/treasuries_can.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L122-L128 | def earliest_possible_date():
"""
The earliest date for which we can load data from this module.
"""
today = pd.Timestamp('now', tz='UTC').normalize()
# Bank of Canada only has the last 10 years of data at any given time.
return today.replace(year=today.year - 10) | [
"def",
"earliest_possible_date",
"(",
")",
":",
"today",
"=",
"pd",
".",
"Timestamp",
"(",
"'now'",
",",
"tz",
"=",
"'UTC'",
")",
".",
"normalize",
"(",
")",
"# Bank of Canada only has the last 10 years of data at any given time.",
"return",
"today",
".",
"replace",... | The earliest date for which we can load data from this module. | [
"The",
"earliest",
"date",
"for",
"which",
"we",
"can",
"load",
"data",
"from",
"this",
"module",
"."
] | python | train | 40.285714 |
awacha/sastool | sastool/misc/pathutils.py | https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/misc/pathutils.py#L17-L63 | def findfileindirs(filename, dirs=None, use_pythonpath=True, use_searchpath=True, notfound_is_fatal=True, notfound_val=None):
"""Find file in multiple directories.
Inputs:
filename: the file name to be searched for.
dirs: list of folders or None
use_pythonpath: use the Python module sea... | [
"def",
"findfileindirs",
"(",
"filename",
",",
"dirs",
"=",
"None",
",",
"use_pythonpath",
"=",
"True",
",",
"use_searchpath",
"=",
"True",
",",
"notfound_is_fatal",
"=",
"True",
",",
"notfound_val",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"... | Find file in multiple directories.
Inputs:
filename: the file name to be searched for.
dirs: list of folders or None
use_pythonpath: use the Python module search path
use_searchpath: use the sastool search path.
notfound_is_fatal: if an exception is to be raised if the file ... | [
"Find",
"file",
"in",
"multiple",
"directories",
"."
] | python | train | 39.382979 |
craffel/mir_eval | mir_eval/tempo.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/tempo.py#L54-L74 | def validate(reference_tempi, reference_weight, estimated_tempi):
"""Checks that the input annotations to a metric look like valid tempo
annotations.
Parameters
----------
reference_tempi : np.ndarray
reference tempo values, in bpm
reference_weight : float
perceptual weight of ... | [
"def",
"validate",
"(",
"reference_tempi",
",",
"reference_weight",
",",
"estimated_tempi",
")",
":",
"validate_tempi",
"(",
"reference_tempi",
",",
"reference",
"=",
"True",
")",
"validate_tempi",
"(",
"estimated_tempi",
",",
"reference",
"=",
"False",
")",
"if",... | Checks that the input annotations to a metric look like valid tempo
annotations.
Parameters
----------
reference_tempi : np.ndarray
reference tempo values, in bpm
reference_weight : float
perceptual weight of slow vs fast in reference
estimated_tempi : np.ndarray
estim... | [
"Checks",
"that",
"the",
"input",
"annotations",
"to",
"a",
"metric",
"look",
"like",
"valid",
"tempo",
"annotations",
"."
] | python | train | 30.285714 |
spdx/tools-python | spdx/parsers/rdf.py | https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L195-L200 | def get_extr_lics_xref(self, extr_lic):
"""
Return a list of cross references.
"""
xrefs = list(self.graph.triples((extr_lic, RDFS.seeAlso, None)))
return map(lambda xref_triple: xref_triple[2], xrefs) | [
"def",
"get_extr_lics_xref",
"(",
"self",
",",
"extr_lic",
")",
":",
"xrefs",
"=",
"list",
"(",
"self",
".",
"graph",
".",
"triples",
"(",
"(",
"extr_lic",
",",
"RDFS",
".",
"seeAlso",
",",
"None",
")",
")",
")",
"return",
"map",
"(",
"lambda",
"xref... | Return a list of cross references. | [
"Return",
"a",
"list",
"of",
"cross",
"references",
"."
] | python | valid | 39.333333 |
apache/airflow | airflow/contrib/hooks/sagemaker_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L157-L178 | def configure_s3_resources(self, config):
"""
Extract the S3 operations from the configuration and execute them.
:param config: config of SageMaker operation
:type config: dict
:rtype: dict
"""
s3_operations = config.pop('S3Operations', None)
if s3_opera... | [
"def",
"configure_s3_resources",
"(",
"self",
",",
"config",
")",
":",
"s3_operations",
"=",
"config",
".",
"pop",
"(",
"'S3Operations'",
",",
"None",
")",
"if",
"s3_operations",
"is",
"not",
"None",
":",
"create_bucket_ops",
"=",
"s3_operations",
".",
"get",
... | Extract the S3 operations from the configuration and execute them.
:param config: config of SageMaker operation
:type config: dict
:rtype: dict | [
"Extract",
"the",
"S3",
"operations",
"from",
"the",
"configuration",
"and",
"execute",
"them",
"."
] | python | test | 40.454545 |
apache/incubator-mxnet | python/mxnet/autograd.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/autograd.py#L52-L68 | def set_training(train_mode): #pylint: disable=redefined-outer-name
"""Set status to training/predicting. This affects ctx.is_train in operator
running context. For example, Dropout will drop inputs randomly when
train_mode=True while simply passing through if train_mode=False.
Parameters
---------... | [
"def",
"set_training",
"(",
"train_mode",
")",
":",
"#pylint: disable=redefined-outer-name",
"prev",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXAutogradSetIsTraining",
"(",
"ctypes",
".",
"c_int",
"(",
"train_mode",
")",
",",
"ctyp... | Set status to training/predicting. This affects ctx.is_train in operator
running context. For example, Dropout will drop inputs randomly when
train_mode=True while simply passing through if train_mode=False.
Parameters
----------
train_mode: bool
Returns
-------
previous state before t... | [
"Set",
"status",
"to",
"training",
"/",
"predicting",
".",
"This",
"affects",
"ctx",
".",
"is_train",
"in",
"operator",
"running",
"context",
".",
"For",
"example",
"Dropout",
"will",
"drop",
"inputs",
"randomly",
"when",
"train_mode",
"=",
"True",
"while",
... | python | train | 32.294118 |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L6116-L6122 | def writeString(self, str):
"""Write the content of the string in the output I/O buffer
This routine handle the I18N transcoding from internal
UTF-8 The buffer is lossless, i.e. will store in case of
partial or delayed writes. """
ret = libxml2mod.xmlOutputBufferWriteStrin... | [
"def",
"writeString",
"(",
"self",
",",
"str",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlOutputBufferWriteString",
"(",
"self",
".",
"_o",
",",
"str",
")",
"return",
"ret"
] | Write the content of the string in the output I/O buffer
This routine handle the I18N transcoding from internal
UTF-8 The buffer is lossless, i.e. will store in case of
partial or delayed writes. | [
"Write",
"the",
"content",
"of",
"the",
"string",
"in",
"the",
"output",
"I",
"/",
"O",
"buffer",
"This",
"routine",
"handle",
"the",
"I18N",
"transcoding",
"from",
"internal",
"UTF",
"-",
"8",
"The",
"buffer",
"is",
"lossless",
"i",
".",
"e",
".",
"wi... | python | train | 49.714286 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v20/ualberta.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v20/ualberta.py#L12149-L12160 | def setup_signing_encode(self, target_system, target_component, secret_key, initial_timestamp):
'''
Setup a MAVLink2 signing key. If called with secret_key of all zero
and zero initial_timestamp will disable signing
target_system : system id o... | [
"def",
"setup_signing_encode",
"(",
"self",
",",
"target_system",
",",
"target_component",
",",
"secret_key",
",",
"initial_timestamp",
")",
":",
"return",
"MAVLink_setup_signing_message",
"(",
"target_system",
",",
"target_component",
",",
"secret_key",
",",
"initial_t... | Setup a MAVLink2 signing key. If called with secret_key of all zero
and zero initial_timestamp will disable signing
target_system : system id of the target (uint8_t)
target_component : component ID of the target (uint8_t)
secret_key ... | [
"Setup",
"a",
"MAVLink2",
"signing",
"key",
".",
"If",
"called",
"with",
"secret_key",
"of",
"all",
"zero",
"and",
"zero",
"initial_timestamp",
"will",
"disable",
"signing"
] | python | train | 57.416667 |
mongodb/mongo-python-driver | pymongo/mongo_client.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/mongo_client.py#L1106-L1126 | def close(self):
"""Cleanup client resources and disconnect from MongoDB.
On MongoDB >= 3.6, end all server sessions created by this client by
sending one or more endSessions commands.
Close all sockets in the connection pools and stop the monitor threads.
If this instance is u... | [
"def",
"close",
"(",
"self",
")",
":",
"session_ids",
"=",
"self",
".",
"_topology",
".",
"pop_all_sessions",
"(",
")",
"if",
"session_ids",
":",
"self",
".",
"_end_sessions",
"(",
"session_ids",
")",
"# Stop the periodic task thread and then run _process_periodic_tas... | Cleanup client resources and disconnect from MongoDB.
On MongoDB >= 3.6, end all server sessions created by this client by
sending one or more endSessions commands.
Close all sockets in the connection pools and stop the monitor threads.
If this instance is used again it will be automat... | [
"Cleanup",
"client",
"resources",
"and",
"disconnect",
"from",
"MongoDB",
"."
] | python | train | 41.571429 |
Alveo/pyalveo | pyalveo/pyalveo.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/pyalveo.py#L1341-L1366 | def rename_item_list(self, item_list_url, new_name):
""" Rename an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:type new_name: String
:param new_name: the n... | [
"def",
"rename_item_list",
"(",
"self",
",",
"item_list_url",
",",
"new_name",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'name'",
":",
"new_name",
"}",
")",
"resp",
"=",
"self",
".",
"api_request",
"(",
"str",
"(",
"item_list_url",
")",
"... | Rename an Item List on the server
:type item_list_url: String or ItemList
:param item_list_url: the URL of the list to which to add the items,
or an ItemList object
:type new_name: String
:param new_name: the new name to give the Item List
:rtype: ItemList
:... | [
"Rename",
"an",
"Item",
"List",
"on",
"the",
"server"
] | python | train | 34.769231 |
happyleavesaoc/python-snapcast | snapcast/control/group.py | https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/group.py#L122-L126 | def update_mute(self, data):
"""Update mute."""
self._group['muted'] = data['mute']
self.callback()
_LOGGER.info('updated mute on %s', self.friendly_name) | [
"def",
"update_mute",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_group",
"[",
"'muted'",
"]",
"=",
"data",
"[",
"'mute'",
"]",
"self",
".",
"callback",
"(",
")",
"_LOGGER",
".",
"info",
"(",
"'updated mute on %s'",
",",
"self",
".",
"friendly_n... | Update mute. | [
"Update",
"mute",
"."
] | python | train | 36.4 |
BerkeleyAutomation/perception | perception/camera_intrinsics.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/camera_intrinsics.py#L245-L284 | def project(self, point_cloud, round_px=True):
"""Projects a point cloud onto the camera image plane.
Parameters
----------
point_cloud : :obj:`autolab_core.PointCloud` or :obj:`autolab_core.Point`
A PointCloud or Point to project onto the camera image plane.
round_... | [
"def",
"project",
"(",
"self",
",",
"point_cloud",
",",
"round_px",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"point_cloud",
",",
"PointCloud",
")",
"and",
"not",
"(",
"isinstance",
"(",
"point_cloud",
",",
"Point",
")",
"and",
"point_cloud",
... | Projects a point cloud onto the camera image plane.
Parameters
----------
point_cloud : :obj:`autolab_core.PointCloud` or :obj:`autolab_core.Point`
A PointCloud or Point to project onto the camera image plane.
round_px : bool
If True, projections are rounded to ... | [
"Projects",
"a",
"point",
"cloud",
"onto",
"the",
"camera",
"image",
"plane",
"."
] | python | train | 44.575 |
PredixDev/predixpy | predix/admin/service.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/service.py#L96-L108 | def create(self, parameters={}, create_keys=True, **kwargs):
"""
Create the service.
"""
# Create the service
cs = self._create_service(parameters=parameters, **kwargs)
# Create the service key to get config details and
# store in local cache file.
if cre... | [
"def",
"create",
"(",
"self",
",",
"parameters",
"=",
"{",
"}",
",",
"create_keys",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create the service",
"cs",
"=",
"self",
".",
"_create_service",
"(",
"parameters",
"=",
"parameters",
",",
"*",
"*",
... | Create the service. | [
"Create",
"the",
"service",
"."
] | python | train | 33.307692 |
goshuirc/irc | girc/client.py | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L330-L335 | def action(self, target, message, formatted=True, tags=None):
"""Send an action to the given target."""
if formatted:
message = unescape(message)
self.ctcp(target, 'ACTION', message) | [
"def",
"action",
"(",
"self",
",",
"target",
",",
"message",
",",
"formatted",
"=",
"True",
",",
"tags",
"=",
"None",
")",
":",
"if",
"formatted",
":",
"message",
"=",
"unescape",
"(",
"message",
")",
"self",
".",
"ctcp",
"(",
"target",
",",
"'ACTION... | Send an action to the given target. | [
"Send",
"an",
"action",
"to",
"the",
"given",
"target",
"."
] | python | train | 35.666667 |
abilian/abilian-core | abilian/services/auth/views.py | https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/auth/views.py#L284-L291 | def generate_reset_password_token(user):
# type: (User) -> Any
"""Generate a unique reset password token for the specified user.
:param user: The user to work with
"""
data = [str(user.id), md5(user.password)]
return get_serializer("reset").dumps(data) | [
"def",
"generate_reset_password_token",
"(",
"user",
")",
":",
"# type: (User) -> Any",
"data",
"=",
"[",
"str",
"(",
"user",
".",
"id",
")",
",",
"md5",
"(",
"user",
".",
"password",
")",
"]",
"return",
"get_serializer",
"(",
"\"reset\"",
")",
".",
"dumps... | Generate a unique reset password token for the specified user.
:param user: The user to work with | [
"Generate",
"a",
"unique",
"reset",
"password",
"token",
"for",
"the",
"specified",
"user",
"."
] | python | train | 33.75 |
gpennington/PyMarvel | marvel/character.py | https://github.com/gpennington/PyMarvel/blob/2617162836f2b7c525ed6c4ff6f1e86a07284fd1/marvel/character.py#L15-L21 | def next(self):
"""
Returns new CharacterDataWrapper
TODO: Don't raise offset past count - limit
"""
self.params['offset'] = str(int(self.params['offset']) + int(self.params['limit']))
return self.marvel.get_characters(self.marvel, (), **self.params) | [
"def",
"next",
"(",
"self",
")",
":",
"self",
".",
"params",
"[",
"'offset'",
"]",
"=",
"str",
"(",
"int",
"(",
"self",
".",
"params",
"[",
"'offset'",
"]",
")",
"+",
"int",
"(",
"self",
".",
"params",
"[",
"'limit'",
"]",
")",
")",
"return",
"... | Returns new CharacterDataWrapper
TODO: Don't raise offset past count - limit | [
"Returns",
"new",
"CharacterDataWrapper",
"TODO",
":",
"Don",
"t",
"raise",
"offset",
"past",
"count",
"-",
"limit"
] | python | train | 41.714286 |
mitsei/dlkit | dlkit/authz_adapter/repository/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/authz_adapter/repository/managers.py#L230-L234 | def get_asset_content_lookup_session_for_repository(self, repository_id):
"""Pass through to provider get_asset_content_lookup_session_for_repository"""
return getattr(sessions, 'AssetContentLookupSession')(
provider_session=self._provider_manager.get_asset_content_lookup_session_for_reposit... | [
"def",
"get_asset_content_lookup_session_for_repository",
"(",
"self",
",",
"repository_id",
")",
":",
"return",
"getattr",
"(",
"sessions",
",",
"'AssetContentLookupSession'",
")",
"(",
"provider_session",
"=",
"self",
".",
"_provider_manager",
".",
"get_asset_content_lo... | Pass through to provider get_asset_content_lookup_session_for_repository | [
"Pass",
"through",
"to",
"provider",
"get_asset_content_lookup_session_for_repository"
] | python | train | 76.4 |
TomAugspurger/DSADD | dsadd/checks.py | https://github.com/TomAugspurger/DSADD/blob/d5a754449e0b6dc1a7bb201f8c9031e065f792c7/dsadd/checks.py#L79-L94 | def within_set(df, items=None):
"""
Assert that df is a subset of items
Parameters
==========
df : DataFrame
items : dict
mapping of columns (k) to array-like of values (v) that
``df[k]`` is expected to be a subset of
"""
for k, v in items.items():
if not df[k].... | [
"def",
"within_set",
"(",
"df",
",",
"items",
"=",
"None",
")",
":",
"for",
"k",
",",
"v",
"in",
"items",
".",
"items",
"(",
")",
":",
"if",
"not",
"df",
"[",
"k",
"]",
".",
"isin",
"(",
"v",
")",
".",
"all",
"(",
")",
":",
"raise",
"Assert... | Assert that df is a subset of items
Parameters
==========
df : DataFrame
items : dict
mapping of columns (k) to array-like of values (v) that
``df[k]`` is expected to be a subset of | [
"Assert",
"that",
"df",
"is",
"a",
"subset",
"of",
"items"
] | python | train | 22.875 |
bertrandvidal/parse_this | parse_this/core.py | https://github.com/bertrandvidal/parse_this/blob/aa2e3737f19642300ef1ca65cae21c90049718a2/parse_this/core.py#L302-L311 | def _get_args_name_from_parser(parser):
"""Retrieve the name of the function argument linked to the given parser.
Args:
parser: a function parser
"""
# Retrieve the 'action' destination of the method parser i.e. its
# argument name. The HelpAction is ignored.
return [action.dest for act... | [
"def",
"_get_args_name_from_parser",
"(",
"parser",
")",
":",
"# Retrieve the 'action' destination of the method parser i.e. its",
"# argument name. The HelpAction is ignored.",
"return",
"[",
"action",
".",
"dest",
"for",
"action",
"in",
"parser",
".",
"_actions",
"if",
"not... | Retrieve the name of the function argument linked to the given parser.
Args:
parser: a function parser | [
"Retrieve",
"the",
"name",
"of",
"the",
"function",
"argument",
"linked",
"to",
"the",
"given",
"parser",
"."
] | python | train | 39.4 |
toumorokoshi/sprinter | sprinter/formula/eggscript.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/eggscript.py#L116-L125 | def __install_eggs(self, config):
""" Install eggs for a particular configuration """
egg_carton = (self.directory.install_directory(self.feature_name),
'requirements.txt')
eggs = self.__gather_eggs(config)
self.logger.debug("Installing eggs %s..." % eggs)
... | [
"def",
"__install_eggs",
"(",
"self",
",",
"config",
")",
":",
"egg_carton",
"=",
"(",
"self",
".",
"directory",
".",
"install_directory",
"(",
"self",
".",
"feature_name",
")",
",",
"'requirements.txt'",
")",
"eggs",
"=",
"self",
".",
"__gather_eggs",
"(",
... | Install eggs for a particular configuration | [
"Install",
"eggs",
"for",
"a",
"particular",
"configuration"
] | python | train | 39.6 |
CalebBell/fluids | fluids/geometry.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L272-L318 | def V_horiz_guppy(D, L, a, h, headonly=False):
r'''Calculates volume of a tank with guppy heads, according to [1]_.
.. math::
V_f = A_fL + \frac{2aR^2}{3}\cos^{-1}\left(1 - \frac{h}{R}\right)
+\frac{2a}{9R}\sqrt{2Rh - h^2}(2h-3R)(h+R)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h... | [
"def",
"V_horiz_guppy",
"(",
"D",
",",
"L",
",",
"a",
",",
"h",
",",
"headonly",
"=",
"False",
")",
":",
"R",
"=",
"0.5",
"*",
"D",
"Af",
"=",
"R",
"*",
"R",
"*",
"acos",
"(",
"(",
"R",
"-",
"h",
")",
"/",
"R",
")",
"-",
"(",
"R",
"-",
... | r'''Calculates volume of a tank with guppy heads, according to [1]_.
.. math::
V_f = A_fL + \frac{2aR^2}{3}\cos^{-1}\left(1 - \frac{h}{R}\right)
+\frac{2a}{9R}\sqrt{2Rh - h^2}(2h-3R)(h+R)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h)\sqrt{2Rh - h^2}
Parameters
----------
... | [
"r",
"Calculates",
"volume",
"of",
"a",
"tank",
"with",
"guppy",
"heads",
"according",
"to",
"[",
"1",
"]",
"_",
"."
] | python | train | 28.765957 |
agile-geoscience/welly | welly/location.py | https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/location.py#L171-L250 | def compute_position_log(self,
td=None,
method='mc',
update_deviation=True):
"""
Args:
deviation (ndarray): A deviation survey with rows like MD, INC, AZI
td (Number): The TD of the well, if no... | [
"def",
"compute_position_log",
"(",
"self",
",",
"td",
"=",
"None",
",",
"method",
"=",
"'mc'",
",",
"update_deviation",
"=",
"True",
")",
":",
"deviation",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"deviation",
")",
"# Adjust to TD.",
"if",
"td",
"is",
... | Args:
deviation (ndarray): A deviation survey with rows like MD, INC, AZI
td (Number): The TD of the well, if not the end of the deviation
survey you're passing.
method (str):
'aa': average angle
'bt': balanced tangential
... | [
"Args",
":",
"deviation",
"(",
"ndarray",
")",
":",
"A",
"deviation",
"survey",
"with",
"rows",
"like",
"MD",
"INC",
"AZI",
"td",
"(",
"Number",
")",
":",
"The",
"TD",
"of",
"the",
"well",
"if",
"not",
"the",
"end",
"of",
"the",
"deviation",
"survey"... | python | train | 36.3875 |
eonpatapon/contrail-api-cli | contrail_api_cli/utils.py | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/utils.py#L307-L342 | def format_table(rows, sep=' '):
"""Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
[1, 2, 3],
['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],
['foo'... | [
"def",
"format_table",
"(",
"rows",
",",
"sep",
"=",
"' '",
")",
":",
"max_col_length",
"=",
"[",
"0",
"]",
"*",
"100",
"# calculate max length for each col",
"for",
"row",
"in",
"rows",
":",
"for",
"index",
",",
"(",
"col",
",",
"length",
")",
"in",
... | Format table
:param sep: separator between columns
:type sep: unicode on python2 | str on python3
Given the table::
table = [
['foo', 'bar', 'foo'],
[1, 2, 3],
['54a5a05d-c83b-4bb5-bd95-d90d6ea4a878'],
['foo', 45, 'bar', 2345]
]
`format... | [
"Format",
"table"
] | python | train | 31.638889 |
inspirehep/harvesting-kit | harvestingkit/elsevier_package.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/elsevier_package.py#L632-L665 | def get_publication_date(self, xml_doc):
"""Return the best effort start_date."""
start_date = get_value_in_tag(xml_doc, "prism:coverDate")
if not start_date:
start_date = get_value_in_tag(xml_doc, "prism:coverDisplayDate")
if not start_date:
start_date = ... | [
"def",
"get_publication_date",
"(",
"self",
",",
"xml_doc",
")",
":",
"start_date",
"=",
"get_value_in_tag",
"(",
"xml_doc",
",",
"\"prism:coverDate\"",
")",
"if",
"not",
"start_date",
":",
"start_date",
"=",
"get_value_in_tag",
"(",
"xml_doc",
",",
"\"prism:cover... | Return the best effort start_date. | [
"Return",
"the",
"best",
"effort",
"start_date",
"."
] | python | valid | 46.235294 |
PyCQA/pylint | pylint/checkers/exceptions.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/exceptions.py#L64-L69 | def _is_raising(body: typing.List) -> bool:
"""Return true if the given statement node raise an exception"""
for node in body:
if isinstance(node, astroid.Raise):
return True
return False | [
"def",
"_is_raising",
"(",
"body",
":",
"typing",
".",
"List",
")",
"->",
"bool",
":",
"for",
"node",
"in",
"body",
":",
"if",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"Raise",
")",
":",
"return",
"True",
"return",
"False"
] | Return true if the given statement node raise an exception | [
"Return",
"true",
"if",
"the",
"given",
"statement",
"node",
"raise",
"an",
"exception"
] | python | test | 35.666667 |
chapel-lang/sphinxcontrib-chapeldomain | sphinxcontrib/chapeldomain.py | https://github.com/chapel-lang/sphinxcontrib-chapeldomain/blob/00970fe1b3aed5deb1186bec19bf0912d2f92853/sphinxcontrib/chapeldomain.py#L576-L591 | def get_index_text(self, modname, name_cls):
"""Return text for index entry based on object type."""
if self.objtype.endswith('function'):
if not modname:
return _('%s() (built-in %s)') % \
(name_cls[0], self.chpl_type_name)
return _('%s() (in ... | [
"def",
"get_index_text",
"(",
"self",
",",
"modname",
",",
"name_cls",
")",
":",
"if",
"self",
".",
"objtype",
".",
"endswith",
"(",
"'function'",
")",
":",
"if",
"not",
"modname",
":",
"return",
"_",
"(",
"'%s() (built-in %s)'",
")",
"%",
"(",
"name_cls... | Return text for index entry based on object type. | [
"Return",
"text",
"for",
"index",
"entry",
"based",
"on",
"object",
"type",
"."
] | python | train | 45.25 |
chrislim2888/IP2Location-Python | IP2Location.py | https://github.com/chrislim2888/IP2Location-Python/blob/6b2a7d3a5e61c9f8efda5ae96c7064f9a7714621/IP2Location.py#L181-L184 | def get_weather_code(self, ip):
''' Get weather_code '''
rec = self.get_all(ip)
return rec and rec.weather_code | [
"def",
"get_weather_code",
"(",
"self",
",",
"ip",
")",
":",
"rec",
"=",
"self",
".",
"get_all",
"(",
"ip",
")",
"return",
"rec",
"and",
"rec",
".",
"weather_code"
] | Get weather_code | [
"Get",
"weather_code"
] | python | train | 33 |
arcus-io/puppetdb-python | puppetdb/v2/nodes.py | https://github.com/arcus-io/puppetdb-python/blob/d772eb80a1dfb1154a1f421c7ecdc1ac951b5ea2/puppetdb/v2/nodes.py#L25-L32 | def get_nodes(api_url=None, verify=False, cert=list()):
"""
Returns info for all Nodes
:param api_url: Base PuppetDB API url
"""
return utils._make_api_request(api_url, '/nodes', verify, cert) | [
"def",
"get_nodes",
"(",
"api_url",
"=",
"None",
",",
"verify",
"=",
"False",
",",
"cert",
"=",
"list",
"(",
")",
")",
":",
"return",
"utils",
".",
"_make_api_request",
"(",
"api_url",
",",
"'/nodes'",
",",
"verify",
",",
"cert",
")"
] | Returns info for all Nodes
:param api_url: Base PuppetDB API url | [
"Returns",
"info",
"for",
"all",
"Nodes"
] | python | train | 25.875 |
keans/lmnotify | lmnotify/session.py | https://github.com/keans/lmnotify/blob/b0a5282a582e5090852dc20fea8a135ca258d0d3/lmnotify/session.py#L98-L119 | def init_session(self, get_token=True):
"""
init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created
"""
if (self._client_id is None) or (self._clien... | [
"def",
"init_session",
"(",
"self",
",",
"get_token",
"=",
"True",
")",
":",
"if",
"(",
"self",
".",
"_client_id",
"is",
"None",
")",
"or",
"(",
"self",
".",
"_client_secret",
"is",
"None",
")",
":",
"sys",
".",
"exit",
"(",
"\"Please make sure to set th... | init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created | [
"init",
"a",
"new",
"oauth2",
"session",
"that",
"is",
"required",
"to",
"access",
"the",
"cloud"
] | python | train | 37.227273 |
base4sistemas/satcfe | satcfe/clientesathub.py | https://github.com/base4sistemas/satcfe/blob/cb8e8815f4133d3e3d94cf526fa86767b4521ed9/satcfe/clientesathub.py#L271-L284 | def trocar_codigo_de_ativacao(self, novo_codigo_ativacao,
opcao=constantes.CODIGO_ATIVACAO_REGULAR,
codigo_emergencia=None):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSA... | [
"def",
"trocar_codigo_de_ativacao",
"(",
"self",
",",
"novo_codigo_ativacao",
",",
"opcao",
"=",
"constantes",
".",
"CODIGO_ATIVACAO_REGULAR",
",",
"codigo_emergencia",
"=",
"None",
")",
":",
"resp",
"=",
"self",
".",
"_http_post",
"(",
"'trocarcodigodeativacao'",
"... | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT | [
"Sobrepõe",
":",
"meth",
":",
"~satcfe",
".",
"base",
".",
"FuncoesSAT",
".",
"trocar_codigo_de_ativacao",
"."
] | python | train | 44.785714 |
iotile/coretools | iotilecore/iotile/core/dev/semver.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/semver.py#L342-L356 | def check(self, version):
"""Check that a version is inside this SemanticVersionRange
Args:
version (SemanticVersion): The version to check
Returns:
bool: True if the version is included in the range, False if not
"""
for disjunct in self._disjuncts:
... | [
"def",
"check",
"(",
"self",
",",
"version",
")",
":",
"for",
"disjunct",
"in",
"self",
".",
"_disjuncts",
":",
"if",
"self",
".",
"_check_insersection",
"(",
"version",
",",
"disjunct",
")",
":",
"return",
"True",
"return",
"False"
] | Check that a version is inside this SemanticVersionRange
Args:
version (SemanticVersion): The version to check
Returns:
bool: True if the version is included in the range, False if not | [
"Check",
"that",
"a",
"version",
"is",
"inside",
"this",
"SemanticVersionRange"
] | python | train | 27.533333 |
guaix-ucm/numina | numina/array/stats.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/stats.py#L17-L48 | def robust_std(x, debug=False):
"""Compute a robust estimator of the standard deviation
See Eq. 3.36 (page 84) in Statistics, Data Mining, and Machine
in Astronomy, by Ivezic, Connolly, VanderPlas & Gray
Parameters
----------
x : 1d numpy array, float
Array of input values which standa... | [
"def",
"robust_std",
"(",
"x",
",",
"debug",
"=",
"False",
")",
":",
"x",
"=",
"numpy",
".",
"asarray",
"(",
"x",
")",
"# compute percentiles and robust estimator",
"q25",
"=",
"numpy",
".",
"percentile",
"(",
"x",
",",
"25",
")",
"q75",
"=",
"numpy",
... | Compute a robust estimator of the standard deviation
See Eq. 3.36 (page 84) in Statistics, Data Mining, and Machine
in Astronomy, by Ivezic, Connolly, VanderPlas & Gray
Parameters
----------
x : 1d numpy array, float
Array of input values which standard deviation is requested.
debug : ... | [
"Compute",
"a",
"robust",
"estimator",
"of",
"the",
"standard",
"deviation"
] | python | train | 27.53125 |
sorgerlab/indra | indra/explanation/model_checker.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/explanation/model_checker.py#L554-L640 | def _find_im_paths(self, subj_mp, obs_name, target_polarity,
max_paths=1, max_path_length=5):
"""Check for a source/target path in the influence map.
Parameters
----------
subj_mp : pysb.MonomerPattern
MonomerPattern corresponding to the subject of the... | [
"def",
"_find_im_paths",
"(",
"self",
",",
"subj_mp",
",",
"obs_name",
",",
"target_polarity",
",",
"max_paths",
"=",
"1",
",",
"max_path_length",
"=",
"5",
")",
":",
"logger",
".",
"info",
"(",
"(",
"'Running path finding with max_paths=%d,'",
"' max_path_length=... | Check for a source/target path in the influence map.
Parameters
----------
subj_mp : pysb.MonomerPattern
MonomerPattern corresponding to the subject of the Statement
being checked.
obs_name : str
Name of the PySB model Observable corresponding to the
... | [
"Check",
"for",
"a",
"source",
"/",
"target",
"path",
"in",
"the",
"influence",
"map",
"."
] | python | train | 43.37931 |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/decour.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/decour.py#L151-L154 | def _add_spanning_relation(self, source, target):
"""add a spanning relation to this docgraph"""
self.add_edge(source, target, layers={self.ns, self.ns+':unit'},
edge_type=EdgeTypes.spanning_relation) | [
"def",
"_add_spanning_relation",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"self",
".",
"add_edge",
"(",
"source",
",",
"target",
",",
"layers",
"=",
"{",
"self",
".",
"ns",
",",
"self",
".",
"ns",
"+",
"':unit'",
"}",
",",
"edge_type",
"=... | add a spanning relation to this docgraph | [
"add",
"a",
"spanning",
"relation",
"to",
"this",
"docgraph"
] | python | train | 58.75 |
CalebBell/thermo | thermo/chemical.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L2370-L2391 | def Prl(self):
r'''Prandtl number of the liquid phase of the chemical at its
current temperature and pressure, [dimensionless].
.. math::
Pr = \frac{C_p \mu}{k}
Utilizes the temperature and pressure dependent object oriented
interfaces :obj:`thermo.viscosity.Viscosi... | [
"def",
"Prl",
"(",
"self",
")",
":",
"Cpl",
",",
"mul",
",",
"kl",
"=",
"self",
".",
"Cpl",
",",
"self",
".",
"mul",
",",
"self",
".",
"kl",
"if",
"all",
"(",
"[",
"Cpl",
",",
"mul",
",",
"kl",
"]",
")",
":",
"return",
"Prandtl",
"(",
"Cp",... | r'''Prandtl number of the liquid phase of the chemical at its
current temperature and pressure, [dimensionless].
.. math::
Pr = \frac{C_p \mu}{k}
Utilizes the temperature and pressure dependent object oriented
interfaces :obj:`thermo.viscosity.ViscosityLiquid`,
:obj... | [
"r",
"Prandtl",
"number",
"of",
"the",
"liquid",
"phase",
"of",
"the",
"chemical",
"at",
"its",
"current",
"temperature",
"and",
"pressure",
"[",
"dimensionless",
"]",
"."
] | python | valid | 34.136364 |
sorgerlab/indra | indra/sources/reach/api.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/reach/api.py#L190-L261 | def process_nxml_str(nxml_str, citation=None, offline=False,
output_fname=default_output_fname):
"""Return a ReachProcessor by processing the given NXML string.
NXML is the format used by PubmedCentral for papers in the open
access subset.
Parameters
----------
nxml_str : ... | [
"def",
"process_nxml_str",
"(",
"nxml_str",
",",
"citation",
"=",
"None",
",",
"offline",
"=",
"False",
",",
"output_fname",
"=",
"default_output_fname",
")",
":",
"if",
"offline",
":",
"if",
"not",
"try_offline",
":",
"logger",
".",
"error",
"(",
"'Offline ... | Return a ReachProcessor by processing the given NXML string.
NXML is the format used by PubmedCentral for papers in the open
access subset.
Parameters
----------
nxml_str : str
The NXML string to be processed.
citation : Optional[str]
A PubMed ID passed to be used in the eviden... | [
"Return",
"a",
"ReachProcessor",
"by",
"processing",
"the",
"given",
"NXML",
"string",
"."
] | python | train | 36.444444 |
jcrist/skein | skein/core.py | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L541-L580 | def connect(self, app_id, wait=True, security=None):
"""Connect to a running application.
Parameters
----------
app_id : str
The id of the application.
wait : bool, optional
If true [default], blocks until the application starts. If False,
wil... | [
"def",
"connect",
"(",
"self",
",",
"app_id",
",",
"wait",
"=",
"True",
",",
"security",
"=",
"None",
")",
":",
"if",
"wait",
":",
"resp",
"=",
"self",
".",
"_call",
"(",
"'waitForStart'",
",",
"proto",
".",
"Application",
"(",
"id",
"=",
"app_id",
... | Connect to a running application.
Parameters
----------
app_id : str
The id of the application.
wait : bool, optional
If true [default], blocks until the application starts. If False,
will raise a ``ApplicationNotRunningError`` immediately if the
... | [
"Connect",
"to",
"a",
"running",
"application",
"."
] | python | train | 35.675 |
gmr/infoblox | infoblox/record.py | https://github.com/gmr/infoblox/blob/163dd9cff5f77c08751936c56aa8428acfd2d208/infoblox/record.py#L104-L148 | def save(self):
"""Update the infoblox with new values for the specified object, or add
the values if it's a new object all together.
:raises: AssertionError
:raises: infoblox.exceptions.ProtocolError
"""
if 'save' not in self._supports:
raise AssertionError... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"'save'",
"not",
"in",
"self",
".",
"_supports",
":",
"raise",
"AssertionError",
"(",
"'Can not save this object type'",
")",
"values",
"=",
"{",
"}",
"for",
"key",
"in",
"[",
"key",
"for",
"key",
"in",
"self",... | Update the infoblox with new values for the specified object, or add
the values if it's a new object all together.
:raises: AssertionError
:raises: infoblox.exceptions.ProtocolError | [
"Update",
"the",
"infoblox",
"with",
"new",
"values",
"for",
"the",
"specified",
"object",
"or",
"add",
"the",
"values",
"if",
"it",
"s",
"a",
"new",
"object",
"all",
"together",
"."
] | python | train | 40.022222 |
captin411/ofxclient | ofxclient/client.py | https://github.com/captin411/ofxclient/blob/4da2719f0ecbbf5eee62fb82c1b3b34ec955ee5e/ofxclient/client.py#L111-L115 | def bank_account_query(self, number, date, account_type, bank_id):
"""Bank account statement request"""
return self.authenticated_query(
self._bareq(number, date, account_type, bank_id)
) | [
"def",
"bank_account_query",
"(",
"self",
",",
"number",
",",
"date",
",",
"account_type",
",",
"bank_id",
")",
":",
"return",
"self",
".",
"authenticated_query",
"(",
"self",
".",
"_bareq",
"(",
"number",
",",
"date",
",",
"account_type",
",",
"bank_id",
... | Bank account statement request | [
"Bank",
"account",
"statement",
"request"
] | python | train | 43.8 |
hotdoc/hotdoc | hotdoc/core/formatter.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/formatter.py#L99-L110 | def _download_progress_cb(blocknum, blocksize, totalsize):
"""Banana Banana"""
readsofar = blocknum * blocksize
if totalsize > 0:
percent = readsofar * 1e2 / totalsize
msg = "\r%5.1f%% %*d / %d" % (
percent, len(str(totalsize)), readsofar, totalsize)
print(msg)
if... | [
"def",
"_download_progress_cb",
"(",
"blocknum",
",",
"blocksize",
",",
"totalsize",
")",
":",
"readsofar",
"=",
"blocknum",
"*",
"blocksize",
"if",
"totalsize",
">",
"0",
":",
"percent",
"=",
"readsofar",
"*",
"1e2",
"/",
"totalsize",
"msg",
"=",
"\"\\r%5.1... | Banana Banana | [
"Banana",
"Banana"
] | python | train | 37.5 |
zblz/naima | naima/radiative.py | https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L1673-L1699 | def _Fgamma(self, x, Ep):
"""
KAB06 Eq.58
Note: Quantities are not used in this function
Parameters
----------
x : float
Egamma/Eprot
Ep : float
Eprot [TeV]
"""
L = np.log(Ep)
B = 1.30 + 0.14 * L + 0.011 * L ** 2 ... | [
"def",
"_Fgamma",
"(",
"self",
",",
"x",
",",
"Ep",
")",
":",
"L",
"=",
"np",
".",
"log",
"(",
"Ep",
")",
"B",
"=",
"1.30",
"+",
"0.14",
"*",
"L",
"+",
"0.011",
"*",
"L",
"**",
"2",
"# Eq59",
"beta",
"=",
"(",
"1.79",
"+",
"0.11",
"*",
"L... | KAB06 Eq.58
Note: Quantities are not used in this function
Parameters
----------
x : float
Egamma/Eprot
Ep : float
Eprot [TeV] | [
"KAB06",
"Eq",
".",
"58"
] | python | train | 26.703704 |
blueset/ehForwarderBot | ehforwarderbot/channel.py | https://github.com/blueset/ehForwarderBot/blob/62e8fcfe77b2993aba91623f538f404a90f59f1d/ehforwarderbot/channel.py#L58-L72 | def get_extra_functions(self) -> Dict[str, Callable]:
"""Get a list of additional features
Returns:
Dict[str, Callable]: A dict of methods marked as additional features.
Method can be called with ``get_extra_functions()["methodName"]()``.
"""
if self.channel_type... | [
"def",
"get_extra_functions",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Callable",
"]",
":",
"if",
"self",
".",
"channel_type",
"==",
"ChannelType",
".",
"Master",
":",
"raise",
"NameError",
"(",
"\"get_extra_function is not available on master channels.\"",... | Get a list of additional features
Returns:
Dict[str, Callable]: A dict of methods marked as additional features.
Method can be called with ``get_extra_functions()["methodName"]()``. | [
"Get",
"a",
"list",
"of",
"additional",
"features"
] | python | train | 41.733333 |
johnnoone/json-spec | src/jsonspec/pointer/bases.py | https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/bases.py#L190-L205 | def extract(self, obj, bypass_ref=False):
"""
Extract parent of obj, according to current token.
:param obj: the object source
:param bypass_ref: not used
"""
for i in range(0, self.stages):
try:
obj = obj.parent_obj
except Attribu... | [
"def",
"extract",
"(",
"self",
",",
"obj",
",",
"bypass_ref",
"=",
"False",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"stages",
")",
":",
"try",
":",
"obj",
"=",
"obj",
".",
"parent_obj",
"except",
"AttributeError",
":",
"rai... | Extract parent of obj, according to current token.
:param obj: the object source
:param bypass_ref: not used | [
"Extract",
"parent",
"of",
"obj",
"according",
"to",
"current",
"token",
"."
] | python | train | 33.875 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L163-L202 | def get_package_formats():
"""Get the list of available package formats and parameters."""
# pylint: disable=fixme
# HACK: This obviously isn't great, and it is subject to change as
# the API changes, but it'll do for now as a interim method of
# introspection to get the parameters we need.
def ... | [
"def",
"get_package_formats",
"(",
")",
":",
"# pylint: disable=fixme",
"# HACK: This obviously isn't great, and it is subject to change as",
"# the API changes, but it'll do for now as a interim method of",
"# introspection to get the parameters we need.",
"def",
"get_parameters",
"(",
"cls... | Get the list of available package formats and parameters. | [
"Get",
"the",
"list",
"of",
"available",
"package",
"formats",
"and",
"parameters",
"."
] | python | train | 36.175 |
OpenGov/carpenter | carpenter/blocks/cellanalyzer.py | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/cellanalyzer.py#L109-L151 | def auto_convert_string_cell(flagable, cell_str, position, worksheet, flags,
units, parens_as_neg=True):
'''
Handles the string case of cell and attempts auto-conversion
for auto_convert_cell.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative v... | [
"def",
"auto_convert_string_cell",
"(",
"flagable",
",",
"cell_str",
",",
"position",
",",
"worksheet",
",",
"flags",
",",
"units",
",",
"parens_as_neg",
"=",
"True",
")",
":",
"conversion",
"=",
"cell_str",
".",
"strip",
"(",
")",
"# Wrapped?",
"if",
"re",
... | Handles the string case of cell and attempts auto-conversion
for auto_convert_cell.
Args:
parens_as_neg: Converts numerics surrounded by parens to negative values | [
"Handles",
"the",
"string",
"case",
"of",
"cell",
"and",
"attempts",
"auto",
"-",
"conversion",
"for",
"auto_convert_cell",
"."
] | python | train | 49.906977 |
python-bugzilla/python-bugzilla | bugzilla/base.py | https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L181-L212 | def url_to_query(url):
"""
Given a big huge bugzilla query URL, returns a query dict that can
be passed along to the Bugzilla.query() method.
"""
q = {}
# pylint: disable=unpacking-non-sequence
(ignore, ignore, path,
ignore, query, ignore) = urlparse(url... | [
"def",
"url_to_query",
"(",
"url",
")",
":",
"q",
"=",
"{",
"}",
"# pylint: disable=unpacking-non-sequence",
"(",
"ignore",
",",
"ignore",
",",
"path",
",",
"ignore",
",",
"query",
",",
"ignore",
")",
"=",
"urlparse",
"(",
"url",
")",
"base",
"=",
"os",
... | Given a big huge bugzilla query URL, returns a query dict that can
be passed along to the Bugzilla.query() method. | [
"Given",
"a",
"big",
"huge",
"bugzilla",
"query",
"URL",
"returns",
"a",
"query",
"dict",
"that",
"can",
"be",
"passed",
"along",
"to",
"the",
"Bugzilla",
".",
"query",
"()",
"method",
"."
] | python | train | 28.03125 |
etingof/pyasn1 | pyasn1/codec/cer/encoder.py | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/codec/cer/encoder.py#L85-L101 | def _componentSortKey(componentAndType):
"""Sort SET components by tag
Sort regardless of the Choice value (static sort)
"""
component, asn1Spec = componentAndType
if asn1Spec is None:
asn1Spec = component
if asn1Spec.typeId == univ.Choice.typeId and not as... | [
"def",
"_componentSortKey",
"(",
"componentAndType",
")",
":",
"component",
",",
"asn1Spec",
"=",
"componentAndType",
"if",
"asn1Spec",
"is",
"None",
":",
"asn1Spec",
"=",
"component",
"if",
"asn1Spec",
".",
"typeId",
"==",
"univ",
".",
"Choice",
".",
"typeId"... | Sort SET components by tag
Sort regardless of the Choice value (static sort) | [
"Sort",
"SET",
"components",
"by",
"tag"
] | python | train | 30.117647 |
nerdvegas/rez | src/rezgui/objects/Config.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/Config.py#L38-L47 | def get_string_list(self, key):
"""Get a list of strings."""
strings = []
size = self.beginReadArray(key)
for i in range(size):
self.setArrayIndex(i)
entry = str(self._value("entry"))
strings.append(entry)
self.endArray()
return strings | [
"def",
"get_string_list",
"(",
"self",
",",
"key",
")",
":",
"strings",
"=",
"[",
"]",
"size",
"=",
"self",
".",
"beginReadArray",
"(",
"key",
")",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"self",
".",
"setArrayIndex",
"(",
"i",
")",
"entr... | Get a list of strings. | [
"Get",
"a",
"list",
"of",
"strings",
"."
] | python | train | 31.1 |
Dallinger/Dallinger | dallinger/db.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/db.py#L88-L101 | def scoped_session_decorator(func):
"""Manage contexts and add debugging to db sessions."""
@wraps(func)
def wrapper(*args, **kwargs):
with sessions_scope(session):
# The session used in func comes from the funcs globals, but
# it will be a proxied thread local var from the ... | [
"def",
"scoped_session_decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"sessions_scope",
"(",
"session",
")",
":",
"# The session used in func comes from the func... | Manage contexts and add debugging to db sessions. | [
"Manage",
"contexts",
"and",
"add",
"debugging",
"to",
"db",
"sessions",
"."
] | python | train | 41.214286 |
google/grr | grr/client/grr_response_client/client_actions/searching.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/searching.py#L195-L198 | def FindRegex(self, regex, data):
"""Search the data for a hit."""
for match in re.finditer(regex, data, flags=re.I | re.S | re.M):
yield (match.start(), match.end()) | [
"def",
"FindRegex",
"(",
"self",
",",
"regex",
",",
"data",
")",
":",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"regex",
",",
"data",
",",
"flags",
"=",
"re",
".",
"I",
"|",
"re",
".",
"S",
"|",
"re",
".",
"M",
")",
":",
"yield",
"(",... | Search the data for a hit. | [
"Search",
"the",
"data",
"for",
"a",
"hit",
"."
] | python | train | 44.25 |
CalebBell/fpi | fpi/drag.py | https://github.com/CalebBell/fpi/blob/6e6da3b9d0c17e10cc0886c97bc1bb8aeba2cca5/fpi/drag.py#L720-L783 | def Clift(Re):
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\
\frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < ... | [
"def",
"Clift",
"(",
"Re",
")",
":",
"if",
"Re",
"<",
"0.01",
":",
"Cd",
"=",
"24.",
"/",
"Re",
"+",
"3",
"/",
"16.",
"elif",
"Re",
"<",
"20",
":",
"Cd",
"=",
"24.",
"/",
"Re",
"*",
"(",
"1",
"+",
"0.1315",
"*",
"Re",
"**",
"(",
"0.82",
... | r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\
\frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < 20$}\\
\fra... | [
"r",
"Calculates",
"drag",
"coefficient",
"of",
"a",
"smooth",
"sphere",
"using",
"the",
"method",
"in",
"[",
"1",
"]",
"_",
"as",
"described",
"in",
"[",
"2",
"]",
"_",
"."
] | python | train | 36.125 |
jantman/awslimitchecker | awslimitchecker/services/efs.py | https://github.com/jantman/awslimitchecker/blob/e50197f70f3d0abcc5cfc7fde6336f548b790e34/awslimitchecker/services/efs.py#L116-L131 | def _update_limits_from_api(self):
"""
Call :py:meth:`~.connect` and then check what region we're running in;
adjust default limits as required for regions that differ (us-east-1).
"""
region_limits = {
'us-east-1': 70
}
self.connect()
rname = ... | [
"def",
"_update_limits_from_api",
"(",
"self",
")",
":",
"region_limits",
"=",
"{",
"'us-east-1'",
":",
"70",
"}",
"self",
".",
"connect",
"(",
")",
"rname",
"=",
"self",
".",
"conn",
".",
"_client_config",
".",
"region_name",
"if",
"rname",
"in",
"region_... | Call :py:meth:`~.connect` and then check what region we're running in;
adjust default limits as required for regions that differ (us-east-1). | [
"Call",
":",
"py",
":",
"meth",
":",
"~",
".",
"connect",
"and",
"then",
"check",
"what",
"region",
"we",
"re",
"running",
"in",
";",
"adjust",
"default",
"limits",
"as",
"required",
"for",
"regions",
"that",
"differ",
"(",
"us",
"-",
"east",
"-",
"1... | python | train | 39.6875 |
briney/abutils | abutils/utils/phylogeny.py | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/phylogeny.py#L452-L493 | def igphyml(input_file=None, tree_file=None, root=None, verbose=False):
'''
Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multip... | [
"def",
"igphyml",
"(",
"input_file",
"=",
"None",
",",
"tree_file",
"=",
"None",
",",
"root",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"shutil",
".",
"which",
"(",
"'igphyml'",
")",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"... | Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required.
tree_file (str): Path to the output tree f... | [
"Computes",
"a",
"phylogenetic",
"tree",
"using",
"IgPhyML",
"."
] | python | train | 41.238095 |
googleapis/google-cloud-python | bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_datatransfer/google/cloud/bigquery_datatransfer_v1/gapic/data_transfer_service_client.py#L113-L120 | def project_run_path(cls, project, transfer_config, run):
"""Return a fully-qualified project_run string."""
return google.api_core.path_template.expand(
"projects/{project}/transferConfigs/{transfer_config}/runs/{run}",
project=project,
transfer_config=transfer_confi... | [
"def",
"project_run_path",
"(",
"cls",
",",
"project",
",",
"transfer_config",
",",
"run",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/transferConfigs/{transfer_config}/runs/{run}\"",
",",
"project",
"... | Return a fully-qualified project_run string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project_run",
"string",
"."
] | python | train | 43.25 |
gem/oq-engine | openquake/baselib/node.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L623-L636 | def node_from_elem(elem, nodefactory=Node, lazy=()):
"""
Convert (recursively) an ElementTree object into a Node object.
"""
children = list(elem)
lineno = getattr(elem, 'lineno', None)
if not children:
return nodefactory(elem.tag, dict(elem.attrib), elem.text,
... | [
"def",
"node_from_elem",
"(",
"elem",
",",
"nodefactory",
"=",
"Node",
",",
"lazy",
"=",
"(",
")",
")",
":",
"children",
"=",
"list",
"(",
"elem",
")",
"lineno",
"=",
"getattr",
"(",
"elem",
",",
"'lineno'",
",",
"None",
")",
"if",
"not",
"children",... | Convert (recursively) an ElementTree object into a Node object. | [
"Convert",
"(",
"recursively",
")",
"an",
"ElementTree",
"object",
"into",
"a",
"Node",
"object",
"."
] | python | train | 42.642857 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/formatters.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/formatters.py#L48-L64 | def _formatters_default(self):
"""Activate the default formatters."""
formatter_classes = [
PlainTextFormatter,
HTMLFormatter,
SVGFormatter,
PNGFormatter,
JPEGFormatter,
LatexFormatter,
JSONFormatter,
Javascr... | [
"def",
"_formatters_default",
"(",
"self",
")",
":",
"formatter_classes",
"=",
"[",
"PlainTextFormatter",
",",
"HTMLFormatter",
",",
"SVGFormatter",
",",
"PNGFormatter",
",",
"JPEGFormatter",
",",
"LatexFormatter",
",",
"JSONFormatter",
",",
"JavascriptFormatter",
"]"... | Activate the default formatters. | [
"Activate",
"the",
"default",
"formatters",
"."
] | python | test | 27.588235 |
skylander86/uriutils | uriutils/uriutils.py | https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/uriutils.py#L28-L48 | def get_uri_obj(uri, storage_args={}):
"""
Retrieve the underlying storage object based on the URI (i.e., scheme).
:param str uri: URI to get storage object for
:param dict storage_args: Keyword arguments to pass to the underlying storage object
"""
if isinstance(uri, BaseURI): return uri
... | [
"def",
"get_uri_obj",
"(",
"uri",
",",
"storage_args",
"=",
"{",
"}",
")",
":",
"if",
"isinstance",
"(",
"uri",
",",
"BaseURI",
")",
":",
"return",
"uri",
"uri_obj",
"=",
"None",
"o",
"=",
"urlparse",
"(",
"uri",
")",
"for",
"storage",
"in",
"STORAGE... | Retrieve the underlying storage object based on the URI (i.e., scheme).
:param str uri: URI to get storage object for
:param dict storage_args: Keyword arguments to pass to the underlying storage object | [
"Retrieve",
"the",
"underlying",
"storage",
"object",
"based",
"on",
"the",
"URI",
"(",
"i",
".",
"e",
".",
"scheme",
")",
"."
] | python | train | 28.857143 |
KelSolaar/Manager | manager/components_manager.py | https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/components_manager.py#L509-L520 | def author(self, value):
"""
Setter for **self.__author** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"author"... | [
"def",
"author",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"unicode",
",",
"\"'{0}' attribute: '{1}' type is not 'unicode'!\"",
".",
"format",
"(",
"\"author\"",
",",
"value",
")"... | Setter for **self.__author** attribute.
:param value: Attribute value.
:type value: unicode | [
"Setter",
"for",
"**",
"self",
".",
"__author",
"**",
"attribute",
"."
] | python | train | 28.916667 |
chrisrink10/basilisp | src/basilisp/lang/runtime.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L1152-L1156 | def _collect_args(args) -> ISeq:
"""Collect Python starred arguments into a Basilisp list."""
if isinstance(args, tuple):
return llist.list(args)
raise TypeError("Python variadic arguments should always be a tuple") | [
"def",
"_collect_args",
"(",
"args",
")",
"->",
"ISeq",
":",
"if",
"isinstance",
"(",
"args",
",",
"tuple",
")",
":",
"return",
"llist",
".",
"list",
"(",
"args",
")",
"raise",
"TypeError",
"(",
"\"Python variadic arguments should always be a tuple\"",
")"
] | Collect Python starred arguments into a Basilisp list. | [
"Collect",
"Python",
"starred",
"arguments",
"into",
"a",
"Basilisp",
"list",
"."
] | python | test | 46.2 |
django-treebeard/django-treebeard | treebeard/mp_tree.py | https://github.com/django-treebeard/django-treebeard/blob/8042ee939cb45394909237da447f8925e3cc6aa3/treebeard/mp_tree.py#L958-L963 | def get_descendants(self):
"""
:returns: A queryset of all the node's descendants as DFS, doesn't
include the node itself
"""
return self.__class__.get_tree(self).exclude(pk=self.pk) | [
"def",
"get_descendants",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
".",
"get_tree",
"(",
"self",
")",
".",
"exclude",
"(",
"pk",
"=",
"self",
".",
"pk",
")"
] | :returns: A queryset of all the node's descendants as DFS, doesn't
include the node itself | [
":",
"returns",
":",
"A",
"queryset",
"of",
"all",
"the",
"node",
"s",
"descendants",
"as",
"DFS",
"doesn",
"t",
"include",
"the",
"node",
"itself"
] | python | train | 36.833333 |
hydpy-dev/hydpy | hydpy/auxs/armatools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L715-L723 | def moments(self):
"""The first two time delay weighted statistical moments of the
ARMA response."""
timepoints = self.ma.delays
response = self.response
moment1 = statstools.calc_mean_time(timepoints, response)
moment2 = statstools.calc_mean_time_deviation(
t... | [
"def",
"moments",
"(",
"self",
")",
":",
"timepoints",
"=",
"self",
".",
"ma",
".",
"delays",
"response",
"=",
"self",
".",
"response",
"moment1",
"=",
"statstools",
".",
"calc_mean_time",
"(",
"timepoints",
",",
"response",
")",
"moment2",
"=",
"statstool... | The first two time delay weighted statistical moments of the
ARMA response. | [
"The",
"first",
"two",
"time",
"delay",
"weighted",
"statistical",
"moments",
"of",
"the",
"ARMA",
"response",
"."
] | python | train | 43.111111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.