repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
PixelwarStudio/PyTree | Tree/core.py | https://github.com/PixelwarStudio/PyTree/blob/f14b25ea145da6b00d836e34251d2a4c823766dc/Tree/core.py#L92-L101 | def get_node_age_sum(self, age=None):
"""Get the sum of branches grown in an specific age.
Returns:
int: The sum of all nodes grown in an age.
"""
if age is None:
age = self.age
return pow(self.comp, age) | [
"def",
"get_node_age_sum",
"(",
"self",
",",
"age",
"=",
"None",
")",
":",
"if",
"age",
"is",
"None",
":",
"age",
"=",
"self",
".",
"age",
"return",
"pow",
"(",
"self",
".",
"comp",
",",
"age",
")"
] | Get the sum of branches grown in an specific age.
Returns:
int: The sum of all nodes grown in an age. | [
"Get",
"the",
"sum",
"of",
"branches",
"grown",
"in",
"an",
"specific",
"age",
"."
] | python | train |
evhub/coconut | coconut/command/util.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/command/util.py#L493-L512 | def run(self, code, use_eval=None, path=None, all_errors_exit=False, store=True):
"""Execute Python code."""
if use_eval is None:
run_func = interpret
elif use_eval is True:
run_func = eval
else:
run_func = exec_func
with self.handling_errors(a... | [
"def",
"run",
"(",
"self",
",",
"code",
",",
"use_eval",
"=",
"None",
",",
"path",
"=",
"None",
",",
"all_errors_exit",
"=",
"False",
",",
"store",
"=",
"True",
")",
":",
"if",
"use_eval",
"is",
"None",
":",
"run_func",
"=",
"interpret",
"elif",
"use... | Execute Python code. | [
"Execute",
"Python",
"code",
"."
] | python | train |
google-research/batch-ppo | agents/tools/loop.py | https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/tools/loop.py#L170-L187 | def _find_current_phase(self, global_step):
"""Determine the current phase based on the global step.
This ensures continuing the correct phase after restoring checkoints.
Args:
global_step: The global number of steps performed across all phases.
Returns:
Tuple of phase object, epoch numbe... | [
"def",
"_find_current_phase",
"(",
"self",
",",
"global_step",
")",
":",
"epoch_size",
"=",
"sum",
"(",
"phase",
".",
"steps",
"for",
"phase",
"in",
"self",
".",
"_phases",
")",
"epoch",
"=",
"int",
"(",
"global_step",
"//",
"epoch_size",
")",
"steps_in",
... | Determine the current phase based on the global step.
This ensures continuing the correct phase after restoring checkoints.
Args:
global_step: The global number of steps performed across all phases.
Returns:
Tuple of phase object, epoch number, and phase steps within the epoch. | [
"Determine",
"the",
"current",
"phase",
"based",
"on",
"the",
"global",
"step",
"."
] | python | train |
kobejohn/PQHelper | pqhelper/easy.py | https://github.com/kobejohn/PQHelper/blob/d2b78a22dcb631794295e6a159b06f39c3f10db6/pqhelper/easy.py#L8-L56 | def versus_summaries(turns=2, sims_to_average=2, async_results_q=None):
"""Return summaries of the likely resutls of each available action..
Arguments:
- turns: how many turns to simulate.
- in 2013, 1 is fast (seconds), 2 is slow (seconds), 3 who knows
- sims_to_average: how many times to run ... | [
"def",
"versus_summaries",
"(",
"turns",
"=",
"2",
",",
"sims_to_average",
"=",
"2",
",",
"async_results_q",
"=",
"None",
")",
":",
"board",
",",
"player",
",",
"opponent",
",",
"extra_actions",
"=",
"_state_investigator",
".",
"get_versus",
"(",
")",
"if",
... | Return summaries of the likely resutls of each available action..
Arguments:
- turns: how many turns to simulate.
- in 2013, 1 is fast (seconds), 2 is slow (seconds), 3 who knows
- sims_to_average: how many times to run the simulation
to get more representative average results of each actio... | [
"Return",
"summaries",
"of",
"the",
"likely",
"resutls",
"of",
"each",
"available",
"action",
".."
] | python | train |
ellmetha/django-machina | machina/apps/forum_conversation/abstract_models.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L269-L271 | def is_topic_head(self):
""" Returns ``True`` if the post is the first post of the topic. """
return self.topic.first_post.id == self.id if self.topic.first_post else False | [
"def",
"is_topic_head",
"(",
"self",
")",
":",
"return",
"self",
".",
"topic",
".",
"first_post",
".",
"id",
"==",
"self",
".",
"id",
"if",
"self",
".",
"topic",
".",
"first_post",
"else",
"False"
] | Returns ``True`` if the post is the first post of the topic. | [
"Returns",
"True",
"if",
"the",
"post",
"is",
"the",
"first",
"post",
"of",
"the",
"topic",
"."
] | python | train |
f213/rumetr-client | rumetr/roometr.py | https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L61-L70 | def appt_exists(self, complex: str, house: str, appt: str) -> bool:
"""
Shortcut to check if appt exists in our database.
"""
try:
self.check_appt(complex, house, appt)
except exceptions.RumetrApptNotFound:
return False
return True | [
"def",
"appt_exists",
"(",
"self",
",",
"complex",
":",
"str",
",",
"house",
":",
"str",
",",
"appt",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"self",
".",
"check_appt",
"(",
"complex",
",",
"house",
",",
"appt",
")",
"except",
"exceptions",
... | Shortcut to check if appt exists in our database. | [
"Shortcut",
"to",
"check",
"if",
"appt",
"exists",
"in",
"our",
"database",
"."
] | python | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/custom_collections.py | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/custom_collections.py#L36-L58 | def _convert(self, dictlike):
"""Validate and convert a dict-like object into values for set()ing.
This is called behind the scenes when a MappedCollection is replaced
entirely by another collection, as in::
myobj.mappedcollection = {'a':obj1, 'b': obj2} # ...
Raises a TypeE... | [
"def",
"_convert",
"(",
"self",
",",
"dictlike",
")",
":",
"for",
"incoming_key",
",",
"valuelist",
"in",
"util",
".",
"dictlike_iteritems",
"(",
"dictlike",
")",
":",
"for",
"value",
"in",
"valuelist",
":",
"new_key",
"=",
"self",
".",
"keyfunc",
"(",
"... | Validate and convert a dict-like object into values for set()ing.
This is called behind the scenes when a MappedCollection is replaced
entirely by another collection, as in::
myobj.mappedcollection = {'a':obj1, 'b': obj2} # ...
Raises a TypeError if the key in any (key, value) pair ... | [
"Validate",
"and",
"convert",
"a",
"dict",
"-",
"like",
"object",
"into",
"values",
"for",
"set",
"()",
"ing",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/data_generators/video_utils.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/video_utils.py#L573-L630 | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this function to
get other encoding... | [
"def",
"generate_encoded_samples",
"(",
"self",
",",
"data_dir",
",",
"tmp_dir",
",",
"dataset_split",
")",
":",
"writer",
"=",
"None",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"image_t",
"=",
"tf",
".",
"placeholder",
"(",... | Generate samples of the encoded frames with possible extra data.
By default this function just encodes the numpy array returned as "frame"
from `self.generate_samples` into a PNG image. Override this function to
get other encodings on disk.
Args:
data_dir: final data directory. Typically only us... | [
"Generate",
"samples",
"of",
"the",
"encoded",
"frames",
"with",
"possible",
"extra",
"data",
"."
] | python | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L580-L615 | def find_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
... | [
"def",
"find_or_create",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"keys",
"=",
"kwargs",
".",
"pop",
"(",
"'keys'",
")",
"if",
"'keys'",
"in",
"kwargs",
"else",
"[",
"]",
"return",
"cls",
".",
"first",
"(",
"*",
"*",
"subdict",
"(",
"kwargs",... | Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys(list, ... | [
"Checks",
"if",
"an",
"instance",
"already",
"exists",
"by",
"filtering",
"with",
"the",
"kwargs",
".",
"If",
"yes",
"returns",
"that",
"instance",
".",
"If",
"not",
"creates",
"a",
"new",
"instance",
"with",
"kwargs",
"and",
"returns",
"it"
] | python | train |
hawkular/hawkular-client-python | hawkular/alerts/triggers.py | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/triggers.py#L301-L309 | def conditions(self, trigger_id):
"""
Get all conditions for a specific trigger.
:param trigger_id: Trigger definition id to be retrieved
:return: list of condition objects
"""
response = self._get(self._service_url(['triggers', trigger_id, 'conditions']))
return... | [
"def",
"conditions",
"(",
"self",
",",
"trigger_id",
")",
":",
"response",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_service_url",
"(",
"[",
"'triggers'",
",",
"trigger_id",
",",
"'conditions'",
"]",
")",
")",
"return",
"Condition",
".",
"list_to_objec... | Get all conditions for a specific trigger.
:param trigger_id: Trigger definition id to be retrieved
:return: list of condition objects | [
"Get",
"all",
"conditions",
"for",
"a",
"specific",
"trigger",
"."
] | python | train |
kiwi0fruit/sugartex | sugartex/sugartex_pandoc_filter.py | https://github.com/kiwi0fruit/sugartex/blob/9eb13703cb02d3e2163c9c5f29df280f6bf49cec/sugartex/sugartex_pandoc_filter.py#L25-L43 | def cli():
"""
Usage: sugartex [OPTIONS] [TO]
Reads from stdin and writes to stdout. Can have single argument/option only.
When no args or the arg is not from options then run Pandoc SugarTeX filter
that iterates over math blocks.
Options:
--kiwi Same as above but with kiwi flavo... | [
"def",
"cli",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
":",
"if",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"'--kiwi'",
":",
"kiwi_hack",
"(",
")",
"elif",
"sys",
".",
"argv",
"[",
"1",
"]",
".",
"lower",
"(",
")",... | Usage: sugartex [OPTIONS] [TO]
Reads from stdin and writes to stdout. Can have single argument/option only.
When no args or the arg is not from options then run Pandoc SugarTeX filter
that iterates over math blocks.
Options:
--kiwi Same as above but with kiwi flavor,
--help Show ... | [
"Usage",
":",
"sugartex",
"[",
"OPTIONS",
"]",
"[",
"TO",
"]"
] | python | train |
sorgerlab/indra | indra/assemblers/pysb/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/assembler.py#L650-L694 | def set_expression(self, expression_dict):
"""Set protein expression amounts as initial conditions
Parameters
----------
expression_dict : dict
A dictionary in which the keys are gene names and the
values are numbers representing the absolute amount
(... | [
"def",
"set_expression",
"(",
"self",
",",
"expression_dict",
")",
":",
"if",
"self",
".",
"model",
"is",
"None",
":",
"return",
"monomers_found",
"=",
"[",
"]",
"monomers_notfound",
"=",
"[",
"]",
"# Iterate over all the monomers",
"for",
"m",
"in",
"self",
... | Set protein expression amounts as initial conditions
Parameters
----------
expression_dict : dict
A dictionary in which the keys are gene names and the
values are numbers representing the absolute amount
(count per cell) of proteins expressed. Proteins that
... | [
"Set",
"protein",
"expression",
"amounts",
"as",
"initial",
"conditions"
] | python | train |
jim-easterbrook/pywws | src/pywws/filedata.py | https://github.com/jim-easterbrook/pywws/blob/4e4d74cee5a3ac5bf42286feaa251cd2ffcaf02c/src/pywws/filedata.py#L282-L298 | def before(self, idx):
"""Return datetime of newest existing data record whose
datetime is < idx.
Might not even be in the same year! If no such record exists,
return None."""
if not isinstance(idx, datetime):
raise TypeError("'%s' is not %s" % (idx, datetime))
... | [
"def",
"before",
"(",
"self",
",",
"idx",
")",
":",
"if",
"not",
"isinstance",
"(",
"idx",
",",
"datetime",
")",
":",
"raise",
"TypeError",
"(",
"\"'%s' is not %s\"",
"%",
"(",
"idx",
",",
"datetime",
")",
")",
"day",
"=",
"min",
"(",
"idx",
".",
"... | Return datetime of newest existing data record whose
datetime is < idx.
Might not even be in the same year! If no such record exists,
return None. | [
"Return",
"datetime",
"of",
"newest",
"existing",
"data",
"record",
"whose",
"datetime",
"is",
"<",
"idx",
"."
] | python | train |
alorence/pysvg-py3 | pysvg/shape.py | https://github.com/alorence/pysvg-py3/blob/ce217a4da3ada44a71d3e2f391d37c67d95c724e/pysvg/shape.py#L145-L150 | def getBottomLeft(self):
"""
Retrieves a tuple with the x,y coordinates of the lower left point of the circle.
Requires the radius and the coordinates to be numbers
"""
return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) - float(self.get_r())) | [
"def",
"getBottomLeft",
"(",
"self",
")",
":",
"return",
"(",
"float",
"(",
"self",
".",
"get_cx",
"(",
")",
")",
"-",
"float",
"(",
"self",
".",
"get_r",
"(",
")",
")",
",",
"float",
"(",
"self",
".",
"get_cy",
"(",
")",
")",
"-",
"float",
"("... | Retrieves a tuple with the x,y coordinates of the lower left point of the circle.
Requires the radius and the coordinates to be numbers | [
"Retrieves",
"a",
"tuple",
"with",
"the",
"x",
"y",
"coordinates",
"of",
"the",
"lower",
"left",
"point",
"of",
"the",
"circle",
".",
"Requires",
"the",
"radius",
"and",
"the",
"coordinates",
"to",
"be",
"numbers"
] | python | train |
eddyxu/cpp-coveralls | cpp_coveralls/coverage.py | https://github.com/eddyxu/cpp-coveralls/blob/ff7af7eea2a23828f6ab2541667ea04f94344dce/cpp_coveralls/coverage.py#L101-L107 | def exclude_paths(args):
"""Returns the absolute paths for excluded path."""
results = []
if args.exclude:
for excl_path in args.exclude:
results.append(os.path.abspath(os.path.join(args.root, excl_path)))
return results | [
"def",
"exclude_paths",
"(",
"args",
")",
":",
"results",
"=",
"[",
"]",
"if",
"args",
".",
"exclude",
":",
"for",
"excl_path",
"in",
"args",
".",
"exclude",
":",
"results",
".",
"append",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"pa... | Returns the absolute paths for excluded path. | [
"Returns",
"the",
"absolute",
"paths",
"for",
"excluded",
"path",
"."
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/visuals/visual.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/visual.py#L338-L349 | def set_gl_state(self, preset=None, **kwargs):
"""Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`.
"""
self._vshare.gl_state ... | [
"def",
"set_gl_state",
"(",
"self",
",",
"preset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_vshare",
".",
"gl_state",
"=",
"kwargs",
"self",
".",
"_vshare",
".",
"gl_state",
"[",
"'preset'",
"]",
"=",
"preset"
] | Define the set of GL state parameters to use when drawing
Parameters
----------
preset : str
Preset to use.
**kwargs : dict
Keyword arguments to `gloo.set_state`. | [
"Define",
"the",
"set",
"of",
"GL",
"state",
"parameters",
"to",
"use",
"when",
"drawing"
] | python | train |
AguaClara/aguaclara | aguaclara/design/sed_tank.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L505-L524 | def n_tanks(Q_plant, sed_inputs=sed_dict):
"""Return the number of sedimentation tanks required for a given flow rate.
Parameters
----------
Q_plant : float
Total plant flow rate
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calcul... | [
"def",
"n_tanks",
"(",
"Q_plant",
",",
"sed_inputs",
"=",
"sed_dict",
")",
":",
"q",
"=",
"q_tank",
"(",
"sed_inputs",
")",
".",
"magnitude",
"return",
"(",
"int",
"(",
"np",
".",
"ceil",
"(",
"Q_plant",
"/",
"q",
")",
")",
")"
] | Return the number of sedimentation tanks required for a given flow rate.
Parameters
----------
Q_plant : float
Total plant flow rate
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
--... | [
"Return",
"the",
"number",
"of",
"sedimentation",
"tanks",
"required",
"for",
"a",
"given",
"flow",
"rate",
".",
"Parameters",
"----------",
"Q_plant",
":",
"float",
"Total",
"plant",
"flow",
"rate",
"sed_inputs",
":",
"dict",
"A",
"dictionary",
"of",
"all",
... | python | train |
mozilla-b2g/fxos-certsuite | mcts/certsuite/cert.py | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/certsuite/cert.py#L572-L590 | def set_permission(permission, value, app):
"""Set a permission for the specified app
Value should be 'deny' or 'allow'
"""
# The object created to wrap PermissionSettingsModule is to work around
# an intermittent bug where it will sometimes be undefined.
script = """
const {classes: Cc... | [
"def",
"set_permission",
"(",
"permission",
",",
"value",
",",
"app",
")",
":",
"# The object created to wrap PermissionSettingsModule is to work around",
"# an intermittent bug where it will sometimes be undefined.",
"script",
"=",
"\"\"\"\n const {classes: Cc, interfaces: Ci, util... | Set a permission for the specified app
Value should be 'deny' or 'allow' | [
"Set",
"a",
"permission",
"for",
"the",
"specified",
"app",
"Value",
"should",
"be",
"deny",
"or",
"allow"
] | python | train |
saltstack/salt | salt/modules/win_groupadd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_groupadd.py#L203-L238 | def getent(refresh=False):
'''
Return info on all groups
Args:
refresh (bool):
Refresh the info for all groups in ``__context__``. If False only
the groups in ``__context__`` will be returned. If True the
``__context__`` will be refreshed with current data and r... | [
"def",
"getent",
"(",
"refresh",
"=",
"False",
")",
":",
"if",
"'group.getent'",
"in",
"__context__",
"and",
"not",
"refresh",
":",
"return",
"__context__",
"[",
"'group.getent'",
"]",
"ret",
"=",
"[",
"]",
"results",
"=",
"_get_all_groups",
"(",
")",
"for... | Return info on all groups
Args:
refresh (bool):
Refresh the info for all groups in ``__context__``. If False only
the groups in ``__context__`` will be returned. If True the
``__context__`` will be refreshed with current data and returned.
Default is False
... | [
"Return",
"info",
"on",
"all",
"groups"
] | python | train |
tarbell-project/tarbell | tarbell/cli.py | https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/cli.py#L448-L465 | def tarbell_switch(command, args):
"""
Switch to a project.
"""
with ensure_settings(command, args) as settings:
projects_path = settings.config.get("projects_path")
if not projects_path:
show_error("{0} does not exist".format(projects_path))
sys.exit()
pr... | [
"def",
"tarbell_switch",
"(",
"command",
",",
"args",
")",
":",
"with",
"ensure_settings",
"(",
"command",
",",
"args",
")",
"as",
"settings",
":",
"projects_path",
"=",
"settings",
".",
"config",
".",
"get",
"(",
"\"projects_path\"",
")",
"if",
"not",
"pr... | Switch to a project. | [
"Switch",
"to",
"a",
"project",
"."
] | python | train |
nwilming/ocupy | ocupy/fixmat.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/fixmat.py#L283-L325 | def FixmatFactory(fixmatfile, categories = None, var_name = 'fixmat', field_name='x'):
"""
Loads a single fixmat (fixmatfile).
Parameters:
fixmatfile : string
The matlab fixmat that should be loaded.
categories : instance of stimuli.Categories, optional
Links dat... | [
"def",
"FixmatFactory",
"(",
"fixmatfile",
",",
"categories",
"=",
"None",
",",
"var_name",
"=",
"'fixmat'",
",",
"field_name",
"=",
"'x'",
")",
":",
"try",
":",
"data",
"=",
"loadmat",
"(",
"fixmatfile",
",",
"struct_as_record",
"=",
"False",
")",
"keys",... | Loads a single fixmat (fixmatfile).
Parameters:
fixmatfile : string
The matlab fixmat that should be loaded.
categories : instance of stimuli.Categories, optional
Links data in categories to data in fixmat. | [
"Loads",
"a",
"single",
"fixmat",
"(",
"fixmatfile",
")",
".",
"Parameters",
":",
"fixmatfile",
":",
"string",
"The",
"matlab",
"fixmat",
"that",
"should",
"be",
"loaded",
".",
"categories",
":",
"instance",
"of",
"stimuli",
".",
"Categories",
"optional",
"L... | python | train |
jessevdk/cldoc | cldoc/clang/cindex.py | https://github.com/jessevdk/cldoc/blob/fc7f59405c4a891b8367c80a700f5aa3c5c9230c/cldoc/clang/cindex.py#L1528-L1533 | def spelling(self):
"""Return the spelling of the entity pointed at by the cursor."""
if not hasattr(self, '_spelling'):
self._spelling = conf.lib.clang_getCursorSpelling(self)
return self._spelling | [
"def",
"spelling",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_spelling'",
")",
":",
"self",
".",
"_spelling",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorSpelling",
"(",
"self",
")",
"return",
"self",
".",
"_spelling"
] | Return the spelling of the entity pointed at by the cursor. | [
"Return",
"the",
"spelling",
"of",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor",
"."
] | python | train |
shoebot/shoebot | shoebot/gui/gtk_drawingarea.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/gui/gtk_drawingarea.py#L78-L98 | def scale_context_and_center(self, cr):
"""
Scale context based on difference between bot size and widget
"""
bot_width, bot_height = self.bot_size
if self.width != bot_width or self.height != bot_height:
# Scale up by largest dimension
if self.width < sel... | [
"def",
"scale_context_and_center",
"(",
"self",
",",
"cr",
")",
":",
"bot_width",
",",
"bot_height",
"=",
"self",
".",
"bot_size",
"if",
"self",
".",
"width",
"!=",
"bot_width",
"or",
"self",
".",
"height",
"!=",
"bot_height",
":",
"# Scale up by largest dimen... | Scale context based on difference between bot size and widget | [
"Scale",
"context",
"based",
"on",
"difference",
"between",
"bot",
"size",
"and",
"widget"
] | python | valid |
pallets/werkzeug | src/werkzeug/filesystem.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/filesystem.py#L42-L64 | def get_filesystem_encoding():
"""Returns the filesystem encoding that should be used. Note that this is
different from the Python understanding of the filesystem encoding which
might be deeply flawed. Do not use this value against Python's unicode APIs
because it might be different. See :ref:`filesyste... | [
"def",
"get_filesystem_encoding",
"(",
")",
":",
"global",
"_warned_about_filesystem_encoding",
"rv",
"=",
"sys",
".",
"getfilesystemencoding",
"(",
")",
"if",
"has_likely_buggy_unicode_filesystem",
"and",
"not",
"rv",
"or",
"_is_ascii_encoding",
"(",
"rv",
")",
":",
... | Returns the filesystem encoding that should be used. Note that this is
different from the Python understanding of the filesystem encoding which
might be deeply flawed. Do not use this value against Python's unicode APIs
because it might be different. See :ref:`filesystem-encoding` for the exact
behavior... | [
"Returns",
"the",
"filesystem",
"encoding",
"that",
"should",
"be",
"used",
".",
"Note",
"that",
"this",
"is",
"different",
"from",
"the",
"Python",
"understanding",
"of",
"the",
"filesystem",
"encoding",
"which",
"might",
"be",
"deeply",
"flawed",
".",
"Do",
... | python | train |
PmagPy/PmagPy | pmagpy/pmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/pmag.py#L5222-L5242 | def vfunc(pars_1, pars_2):
"""
Calculate the Watson Vw test statistic. Calculated as 2*(Sw-Rw)
Parameters
----------
pars_1 : dictionary of Fisher statistics from population 1
pars_2 : dictionary of Fisher statistics from population 2
Returns
-------
Vw : Watson's Vw statistic
... | [
"def",
"vfunc",
"(",
"pars_1",
",",
"pars_2",
")",
":",
"cart_1",
"=",
"dir2cart",
"(",
"[",
"pars_1",
"[",
"\"dec\"",
"]",
",",
"pars_1",
"[",
"\"inc\"",
"]",
",",
"pars_1",
"[",
"\"r\"",
"]",
"]",
")",
"cart_2",
"=",
"dir2cart",
"(",
"[",
"pars_2... | Calculate the Watson Vw test statistic. Calculated as 2*(Sw-Rw)
Parameters
----------
pars_1 : dictionary of Fisher statistics from population 1
pars_2 : dictionary of Fisher statistics from population 2
Returns
-------
Vw : Watson's Vw statistic | [
"Calculate",
"the",
"Watson",
"Vw",
"test",
"statistic",
".",
"Calculated",
"as",
"2",
"*",
"(",
"Sw",
"-",
"Rw",
")"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/trax/layers/attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L97-L111 | def _positional_encoding_new_params(input_shape, rng, max_len=2048): # pylint: disable=invalid-name
"""Helper: create positional encoding parameters."""
del rng
# Check if we are operating on chunked inputs by checking if the first
# shape is a list/tuple of shapes (otherwise it's an int or numpy array).
is_... | [
"def",
"_positional_encoding_new_params",
"(",
"input_shape",
",",
"rng",
",",
"max_len",
"=",
"2048",
")",
":",
"# pylint: disable=invalid-name",
"del",
"rng",
"# Check if we are operating on chunked inputs by checking if the first",
"# shape is a list/tuple of shapes (otherwise it'... | Helper: create positional encoding parameters. | [
"Helper",
":",
"create",
"positional",
"encoding",
"parameters",
"."
] | python | train |
scott-maddox/openbandparams | src/openbandparams/iii_v_zinc_blende_alloy.py | https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/iii_v_zinc_blende_alloy.py#L132-L141 | def F(self, **kwargs):
'''
Returns the Kane remote-band parameter, `F`, calculated from
`Eg_Gamma_0`, `Delta_SO`, `Ep`, and `meff_e_Gamma_0`.
'''
Eg = self.Eg_Gamma_0(**kwargs)
Delta_SO = self.Delta_SO(**kwargs)
Ep = self.Ep(**kwargs)
meff = self.meff_e_Ga... | [
"def",
"F",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"Eg",
"=",
"self",
".",
"Eg_Gamma_0",
"(",
"*",
"*",
"kwargs",
")",
"Delta_SO",
"=",
"self",
".",
"Delta_SO",
"(",
"*",
"*",
"kwargs",
")",
"Ep",
"=",
"self",
".",
"Ep",
"(",
"*",
"*... | Returns the Kane remote-band parameter, `F`, calculated from
`Eg_Gamma_0`, `Delta_SO`, `Ep`, and `meff_e_Gamma_0`. | [
"Returns",
"the",
"Kane",
"remote",
"-",
"band",
"parameter",
"F",
"calculated",
"from",
"Eg_Gamma_0",
"Delta_SO",
"Ep",
"and",
"meff_e_Gamma_0",
"."
] | python | train |
PyCQA/pylint | pylint/utils/file_state.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/utils/file_state.py#L103-L117 | def handle_ignored_message(
self, state_scope, msgid, line, node, args, confidence
): # pylint: disable=unused-argument
"""Report an ignored message.
state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG,
depending on whether the message was disabled locally in the... | [
"def",
"handle_ignored_message",
"(",
"self",
",",
"state_scope",
",",
"msgid",
",",
"line",
",",
"node",
",",
"args",
",",
"confidence",
")",
":",
"# pylint: disable=unused-argument",
"if",
"state_scope",
"==",
"MSG_STATE_SCOPE_MODULE",
":",
"try",
":",
"orig_lin... | Report an ignored message.
state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG,
depending on whether the message was disabled locally in the module,
or globally. The other arguments are the same as for add_message. | [
"Report",
"an",
"ignored",
"message",
"."
] | python | test |
allenai/allennlp | allennlp/common/util.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L272-L306 | def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType:
"""
In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded... | [
"def",
"get_spacy_model",
"(",
"spacy_model_name",
":",
"str",
",",
"pos_tags",
":",
"bool",
",",
"parse",
":",
"bool",
",",
"ner",
":",
"bool",
")",
"->",
"SpacyModelType",
":",
"options",
"=",
"(",
"spacy_model_name",
",",
"pos_tags",
",",
"parse",
",",
... | In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded once. | [
"In",
"order",
"to",
"avoid",
"loading",
"spacy",
"models",
"a",
"whole",
"bunch",
"of",
"times",
"we",
"ll",
"save",
"references",
"to",
"them",
"keyed",
"by",
"the",
"options",
"we",
"used",
"to",
"create",
"the",
"spacy",
"model",
"so",
"any",
"partic... | python | train |
wolverdude/GenSON | genson/schema/node.py | https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/node.py#L18-L37 | def add_schema(self, schema):
"""
Merges in an existing schema.
arguments:
* `schema` (required - `dict` or `SchemaNode`):
an existing JSON Schema to merge.
"""
# serialize instances of SchemaNode before parsing
if isinstance(schema, SchemaNode):
... | [
"def",
"add_schema",
"(",
"self",
",",
"schema",
")",
":",
"# serialize instances of SchemaNode before parsing",
"if",
"isinstance",
"(",
"schema",
",",
"SchemaNode",
")",
":",
"schema",
"=",
"schema",
".",
"to_schema",
"(",
")",
"for",
"subschema",
"in",
"self"... | Merges in an existing schema.
arguments:
* `schema` (required - `dict` or `SchemaNode`):
an existing JSON Schema to merge. | [
"Merges",
"in",
"an",
"existing",
"schema",
"."
] | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_console.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_console.py#L191-L516 | def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
if not isinstance(self.console, wxconsole.MessageConsole):
return
if not self.console.is_alive():
self.mpstate.console = textconsole.SimpleConsole()
return
type = msg.get_type()
... | [
"def",
"mavlink_packet",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"console",
",",
"wxconsole",
".",
"MessageConsole",
")",
":",
"return",
"if",
"not",
"self",
".",
"console",
".",
"is_alive",
"(",
")",
":",
"self"... | handle an incoming mavlink packet | [
"handle",
"an",
"incoming",
"mavlink",
"packet"
] | python | train |
LonamiWebs/Telethon | telethon/extensions/markdown.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/extensions/markdown.py#L132-L200 | def unparse(text, entities, delimiters=None, url_fmt=None):
"""
Performs the reverse operation to .parse(), effectively returning
markdown-like syntax given a normal text and its MessageEntity's.
:param text: the text to be reconverted into markdown.
:param entities: the MessageEntity's applied to ... | [
"def",
"unparse",
"(",
"text",
",",
"entities",
",",
"delimiters",
"=",
"None",
",",
"url_fmt",
"=",
"None",
")",
":",
"if",
"not",
"text",
"or",
"not",
"entities",
":",
"return",
"text",
"if",
"not",
"delimiters",
":",
"if",
"delimiters",
"is",
"not",... | Performs the reverse operation to .parse(), effectively returning
markdown-like syntax given a normal text and its MessageEntity's.
:param text: the text to be reconverted into markdown.
:param entities: the MessageEntity's applied to the text.
:return: a markdown-like text representing the combination... | [
"Performs",
"the",
"reverse",
"operation",
"to",
".",
"parse",
"()",
"effectively",
"returning",
"markdown",
"-",
"like",
"syntax",
"given",
"a",
"normal",
"text",
"and",
"its",
"MessageEntity",
"s",
"."
] | python | train |
genialis/resolwe | resolwe/flow/migrations/0006_add_total_size.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migrations/0006_add_total_size.py#L11-L16 | def calculate_total_size(apps, schema_editor):
"""Add ``total_size`` field to all file/dir-type outputs."""
Data = apps.get_model('flow', 'Data')
for data in Data.objects.all():
hydrate_size(data, force=True)
data.save() | [
"def",
"calculate_total_size",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Data",
"=",
"apps",
".",
"get_model",
"(",
"'flow'",
",",
"'Data'",
")",
"for",
"data",
"in",
"Data",
".",
"objects",
".",
"all",
"(",
")",
":",
"hydrate_size",
"(",
"data",
"... | Add ``total_size`` field to all file/dir-type outputs. | [
"Add",
"total_size",
"field",
"to",
"all",
"file",
"/",
"dir",
"-",
"type",
"outputs",
"."
] | python | train |
projectatomic/osbs-client | osbs/utils.py | https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/utils.py#L270-L314 | def reset_git_repo(target_dir, git_reference, retry_depth=None):
"""
hard reset git clone in target_dir to given git_reference
:param target_dir: str, filesystem path where the repo is cloned
:param git_reference: str, any valid git reference
:param retry_depth: int, if the repo was cloned with --s... | [
"def",
"reset_git_repo",
"(",
"target_dir",
",",
"git_reference",
",",
"retry_depth",
"=",
"None",
")",
":",
"deepen",
"=",
"retry_depth",
"or",
"0",
"base_commit_depth",
"=",
"0",
"for",
"_",
"in",
"range",
"(",
"GIT_FETCH_RETRY",
")",
":",
"try",
":",
"i... | hard reset git clone in target_dir to given git_reference
:param target_dir: str, filesystem path where the repo is cloned
:param git_reference: str, any valid git reference
:param retry_depth: int, if the repo was cloned with --shallow, this is the expected
depth of the commit
... | [
"hard",
"reset",
"git",
"clone",
"in",
"target_dir",
"to",
"given",
"git_reference"
] | python | train |
gopalkoduri/pypeaks | pypeaks/intervals.py | https://github.com/gopalkoduri/pypeaks/blob/59b1e4153e80c6a4c523dda241cc1713fd66161e/pypeaks/intervals.py#L23-L32 | def next_interval(self, interval):
"""
Given a value of an interval, this function returns the
next interval value
"""
index = np.where(self.intervals == interval)
if index[0][0] + 1 < len(self.intervals):
return self.intervals[index[0][0] + 1]
else:
... | [
"def",
"next_interval",
"(",
"self",
",",
"interval",
")",
":",
"index",
"=",
"np",
".",
"where",
"(",
"self",
".",
"intervals",
"==",
"interval",
")",
"if",
"index",
"[",
"0",
"]",
"[",
"0",
"]",
"+",
"1",
"<",
"len",
"(",
"self",
".",
"interval... | Given a value of an interval, this function returns the
next interval value | [
"Given",
"a",
"value",
"of",
"an",
"interval",
"this",
"function",
"returns",
"the",
"next",
"interval",
"value"
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/egg_info.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/egg_info.py#L332-L354 | def _add_egg_info(self, cmd):
"""
Add paths for egg-info files for an external egg-base.
The egg-info files are written to egg-base. If egg-base is
outside the current working directory, this method
searchs the egg-base directory for files to include
in the manifest. Use... | [
"def",
"_add_egg_info",
"(",
"self",
",",
"cmd",
")",
":",
"if",
"cmd",
".",
"egg_base",
"==",
"os",
".",
"curdir",
":",
"# egg-info files were already added by something else",
"return",
"discovered",
"=",
"distutils",
".",
"filelist",
".",
"findall",
"(",
"cmd... | Add paths for egg-info files for an external egg-base.
The egg-info files are written to egg-base. If egg-base is
outside the current working directory, this method
searchs the egg-base directory for files to include
in the manifest. Uses distutils.filelist.findall (which is
rea... | [
"Add",
"paths",
"for",
"egg",
"-",
"info",
"files",
"for",
"an",
"external",
"egg",
"-",
"base",
"."
] | python | test |
saltstack/salt | salt/modules/redismod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L382-L399 | def hmset(key, **fieldsvals):
'''
Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2
'''
host = fieldsvals.pop('host', None)
port = fieldsvals.pop... | [
"def",
"hmset",
"(",
"key",
",",
"*",
"*",
"fieldsvals",
")",
":",
"host",
"=",
"fieldsvals",
".",
"pop",
"(",
"'host'",
",",
"None",
")",
"port",
"=",
"fieldsvals",
".",
"pop",
"(",
"'port'",
",",
"None",
")",
"database",
"=",
"fieldsvals",
".",
"... | Sets multiple hash fields to multiple values.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hmset foo_hash bar_field1=bar_value1 bar_field2=bar_value2 | [
"Sets",
"multiple",
"hash",
"fields",
"to",
"multiple",
"values",
"."
] | python | train |
kaniblu/pytorch-text-utils | torchtextutils/vocab.py | https://github.com/kaniblu/pytorch-text-utils/blob/ab26b88b3e1ed8e777abf32dbfab900399e0cf08/torchtextutils/vocab.py#L54-L65 | def reconstruct_indices(self):
"""
Reconstruct word indices in case of word removals.
Vocabulary does not handle empty indices when words are removed,
hence it need to be told explicity about when to reconstruct them.
"""
del self.i2f, self.f2i
self.f2i, self.i2... | [
"def",
"reconstruct_indices",
"(",
"self",
")",
":",
"del",
"self",
".",
"i2f",
",",
"self",
".",
"f2i",
"self",
".",
"f2i",
",",
"self",
".",
"i2f",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"i",
",",
"w",
"in",
"enumerate",
"(",
"self",
".",
"word... | Reconstruct word indices in case of word removals.
Vocabulary does not handle empty indices when words are removed,
hence it need to be told explicity about when to reconstruct them. | [
"Reconstruct",
"word",
"indices",
"in",
"case",
"of",
"word",
"removals",
".",
"Vocabulary",
"does",
"not",
"handle",
"empty",
"indices",
"when",
"words",
"are",
"removed",
"hence",
"it",
"need",
"to",
"be",
"told",
"explicity",
"about",
"when",
"to",
"recon... | python | train |
airspeed-velocity/asv | asv/extern/asizeof.py | https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/extern/asizeof.py#L529-L540 | def _repr(obj, clip=80):
'''Clip long repr() string.
'''
try: # safe repr()
r = repr(obj)
except TypeError:
r = 'N/A'
if 0 < clip < len(r):
h = (clip // 2) - 2
if h > 0:
r = r[:h] + '....' + r[-h:]
return r | [
"def",
"_repr",
"(",
"obj",
",",
"clip",
"=",
"80",
")",
":",
"try",
":",
"# safe repr()",
"r",
"=",
"repr",
"(",
"obj",
")",
"except",
"TypeError",
":",
"r",
"=",
"'N/A'",
"if",
"0",
"<",
"clip",
"<",
"len",
"(",
"r",
")",
":",
"h",
"=",
"("... | Clip long repr() string. | [
"Clip",
"long",
"repr",
"()",
"string",
"."
] | python | train |
awslabs/sockeye | sockeye/encoder.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/encoder.py#L197-L220 | def get_transformer_encoder(config: transformer.TransformerConfig, prefix: str) -> 'Encoder':
"""
Returns a Transformer encoder, consisting of an embedding layer with
positional encodings and a TransformerEncoder instance.
:param config: Configuration for transformer encoder.
:param prefix: Prefix ... | [
"def",
"get_transformer_encoder",
"(",
"config",
":",
"transformer",
".",
"TransformerConfig",
",",
"prefix",
":",
"str",
")",
"->",
"'Encoder'",
":",
"encoder_seq",
"=",
"EncoderSequence",
"(",
"[",
"]",
",",
"dtype",
"=",
"config",
".",
"dtype",
")",
"cls"... | Returns a Transformer encoder, consisting of an embedding layer with
positional encodings and a TransformerEncoder instance.
:param config: Configuration for transformer encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance. | [
"Returns",
"a",
"Transformer",
"encoder",
"consisting",
"of",
"an",
"embedding",
"layer",
"with",
"positional",
"encodings",
"and",
"a",
"TransformerEncoder",
"instance",
"."
] | python | train |
kkroening/ffmpeg-python | ffmpeg/_probe.py | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_probe.py#L7-L24 | def probe(filename, cmd='ffprobe', **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code,
an :class:`Error` is returned with a generic error message.
The stderr outpu... | [
"def",
"probe",
"(",
"filename",
",",
"cmd",
"=",
"'ffprobe'",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"cmd",
",",
"'-show_format'",
",",
"'-show_streams'",
",",
"'-of'",
",",
"'json'",
"]",
"args",
"+=",
"convert_kwargs_to_cmd_line_args",
"("... | Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code,
an :class:`Error` is returned with a generic error message.
The stderr output can be retrieved by accessing the
``std... | [
"Run",
"ffprobe",
"on",
"the",
"specified",
"file",
"and",
"return",
"a",
"JSON",
"representation",
"of",
"the",
"output",
"."
] | python | train |
marcelcaraciolo/foursquare | pyfoursquare/foursquare.py | https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/pyfoursquare/foursquare.py#L208-L218 | def get_authorization_url(self):
"""Get the authorization URL to redirect the user"""
url = self._get_oauth_url('authenticate')
query = {
'client_id': self._client_id,
'response_type': 'code',
'redirect_uri': self.callback
}
query_str = self.ur... | [
"def",
"get_authorization_url",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_get_oauth_url",
"(",
"'authenticate'",
")",
"query",
"=",
"{",
"'client_id'",
":",
"self",
".",
"_client_id",
",",
"'response_type'",
":",
"'code'",
",",
"'redirect_uri'",
":",
... | Get the authorization URL to redirect the user | [
"Get",
"the",
"authorization",
"URL",
"to",
"redirect",
"the",
"user"
] | python | train |
iotile/coretools | iotilecore/iotile/core/dev/registry.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/registry.py#L52-L58 | def kvstore(self):
"""Lazily load the underlying key-value store backing this registry."""
if self._kvstore is None:
self._kvstore = self.BackingType(self.BackingFileName, respect_venv=True)
return self._kvstore | [
"def",
"kvstore",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kvstore",
"is",
"None",
":",
"self",
".",
"_kvstore",
"=",
"self",
".",
"BackingType",
"(",
"self",
".",
"BackingFileName",
",",
"respect_venv",
"=",
"True",
")",
"return",
"self",
".",
"_kv... | Lazily load the underlying key-value store backing this registry. | [
"Lazily",
"load",
"the",
"underlying",
"key",
"-",
"value",
"store",
"backing",
"this",
"registry",
"."
] | python | train |
ga4gh/ga4gh-server | ga4gh/server/datarepo.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datarepo.py#L1217-L1237 | def insertBiosample(self, biosample):
"""
Inserts the specified Biosample into this repository.
"""
try:
models.Biosample.create(
id=biosample.getId(),
datasetid=biosample.getParentContainer().getId(),
name=biosample.getLocalId(... | [
"def",
"insertBiosample",
"(",
"self",
",",
"biosample",
")",
":",
"try",
":",
"models",
".",
"Biosample",
".",
"create",
"(",
"id",
"=",
"biosample",
".",
"getId",
"(",
")",
",",
"datasetid",
"=",
"biosample",
".",
"getParentContainer",
"(",
")",
".",
... | Inserts the specified Biosample into this repository. | [
"Inserts",
"the",
"specified",
"Biosample",
"into",
"this",
"repository",
"."
] | python | train |
wakatime/wakatime | wakatime/stats.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L288-L301 | def get_file_head(file_name):
"""Returns the first 512000 bytes of the file's contents."""
text = None
try:
with open(file_name, 'r', encoding='utf-8') as fh:
text = fh.read(512000)
except:
try:
with open(file_name, 'r', encoding=sys.getfilesystemencoding()) as f... | [
"def",
"get_file_head",
"(",
"file_name",
")",
":",
"text",
"=",
"None",
"try",
":",
"with",
"open",
"(",
"file_name",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh",
":",
"text",
"=",
"fh",
".",
"read",
"(",
"512000",
")",
"except",
... | Returns the first 512000 bytes of the file's contents. | [
"Returns",
"the",
"first",
"512000",
"bytes",
"of",
"the",
"file",
"s",
"contents",
"."
] | python | train |
googleapis/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/securitycenter/google/cloud/securitycenter_v1/gapic/security_center_client.py#L122-L128 | def source_path(cls, organization, source):
"""Return a fully-qualified source string."""
return google.api_core.path_template.expand(
"organizations/{organization}/sources/{source}",
organization=organization,
source=source,
) | [
"def",
"source_path",
"(",
"cls",
",",
"organization",
",",
"source",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"organizations/{organization}/sources/{source}\"",
",",
"organization",
"=",
"organization",
",",
"source... | Return a fully-qualified source string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"source",
"string",
"."
] | python | train |
optimizely/python-sdk | optimizely/project_config.py | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/project_config.py#L478-L497 | def get_variable_for_feature(self, feature_key, variable_key):
""" Get the variable with the given variable key for the given feature.
Args:
feature_key: The key of the feature for which we are getting the variable.
variable_key: The key of the variable we are getting.
Returns:
Variable ... | [
"def",
"get_variable_for_feature",
"(",
"self",
",",
"feature_key",
",",
"variable_key",
")",
":",
"feature",
"=",
"self",
".",
"feature_key_map",
".",
"get",
"(",
"feature_key",
")",
"if",
"not",
"feature",
":",
"self",
".",
"logger",
".",
"error",
"(",
"... | Get the variable with the given variable key for the given feature.
Args:
feature_key: The key of the feature for which we are getting the variable.
variable_key: The key of the variable we are getting.
Returns:
Variable with the given key in the given variation. | [
"Get",
"the",
"variable",
"with",
"the",
"given",
"variable",
"key",
"for",
"the",
"given",
"feature",
"."
] | python | train |
saltstack/salt | salt/states/cron.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cron.py#L257-L383 | def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron ... | [
"def",
"present",
"(",
"name",
",",
"user",
"=",
"'root'",
",",
"minute",
"=",
"'*'",
",",
"hour",
"=",
"'*'",
",",
"daymonth",
"=",
"'*'",
",",
"month",
"=",
"'*'",
",",
"dayweek",
"=",
"'*'",
",",
"comment",
"=",
"None",
",",
"commented",
"=",
... | Verifies that the specified cron job is present for the specified user.
It is recommended to use `identifier`. Otherwise the cron job is installed
twice if you change the name.
For more advanced information about what exactly can be set in the cron
timing parameters, check your cron system's documentati... | [
"Verifies",
"that",
"the",
"specified",
"cron",
"job",
"is",
"present",
"for",
"the",
"specified",
"user",
".",
"It",
"is",
"recommended",
"to",
"use",
"identifier",
".",
"Otherwise",
"the",
"cron",
"job",
"is",
"installed",
"twice",
"if",
"you",
"change",
... | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/update_service/apis/default_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/update_service/apis/default_api.py#L2066-L2091 | def upload_job_chunk_list(self, upload_job_id, **kwargs): # noqa: E501
"""List all metadata for uploaded chunks # noqa: E501
List all metadata for uploaded chunks # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass a... | [
"def",
"upload_job_chunk_list",
"(",
"self",
",",
"upload_job_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
... | List all metadata for uploaded chunks # noqa: E501
List all metadata for uploaded chunks # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.upload_job_chunk_list(upload_job_id, asyn... | [
"List",
"all",
"metadata",
"for",
"uploaded",
"chunks",
"#",
"noqa",
":",
"E501"
] | python | train |
opencobra/cobrapy | cobra/flux_analysis/deletion.py | https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/deletion.py#L184-L225 | def single_reaction_deletion(model, reaction_list=None, method="fba",
solution=None, processes=None, **kwargs):
"""
Knock out each reaction from a given list.
Parameters
----------
model : cobra.Model
The metabolic model to perform deletions in.
reaction_lis... | [
"def",
"single_reaction_deletion",
"(",
"model",
",",
"reaction_list",
"=",
"None",
",",
"method",
"=",
"\"fba\"",
",",
"solution",
"=",
"None",
",",
"processes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_multi_deletion",
"(",
"model",
",... | Knock out each reaction from a given list.
Parameters
----------
model : cobra.Model
The metabolic model to perform deletions in.
reaction_list : iterable, optional
``cobra.Reaction``s to be deleted. If not passed,
all the reactions from the model are used.
method: {"fba", "... | [
"Knock",
"out",
"each",
"reaction",
"from",
"a",
"given",
"list",
"."
] | python | valid |
mdgoldberg/sportsref | sportsref/nba/players.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/players.py#L175-L177 | def stats_per100(self, kind='R', summary=False):
"""Returns a DataFrame of per-100-possession stats."""
return self._get_stats_table('per_poss', kind=kind, summary=summary) | [
"def",
"stats_per100",
"(",
"self",
",",
"kind",
"=",
"'R'",
",",
"summary",
"=",
"False",
")",
":",
"return",
"self",
".",
"_get_stats_table",
"(",
"'per_poss'",
",",
"kind",
"=",
"kind",
",",
"summary",
"=",
"summary",
")"
] | Returns a DataFrame of per-100-possession stats. | [
"Returns",
"a",
"DataFrame",
"of",
"per",
"-",
"100",
"-",
"possession",
"stats",
"."
] | python | test |
zvoase/django-relax | relax/viewserver.py | https://github.com/zvoase/django-relax/blob/10bb37bf3a512b290816856a6877c17fa37e930f/relax/viewserver.py#L158-L190 | def handle(self):
"""The main function called to handle a request."""
while True:
try:
line = self.rfile.readline()
try:
# All input data are lines of JSON like the following:
# ["<cmd_name>" "<cmd_arg1>" "<cmd_arg2>" ... | [
"def",
"handle",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"line",
"=",
"self",
".",
"rfile",
".",
"readline",
"(",
")",
"try",
":",
"# All input data are lines of JSON like the following:",
"# [\"<cmd_name>\" \"<cmd_arg1>\" \"<cmd_arg2>\" ...]",
"# S... | The main function called to handle a request. | [
"The",
"main",
"function",
"called",
"to",
"handle",
"a",
"request",
"."
] | python | valid |
inasafe/inasafe | safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_kw47_default_inasafe_fields.py#L106-L193 | def set_widgets(self):
"""Set widgets on the Extra Keywords tab."""
self.clear()
existing_inasafe_field = self.parent.get_existing_keyword(
'inasafe_fields')
existing_inasafe_default_values = self.parent.get_existing_keyword(
'inasafe_default_values')
# Re... | [
"def",
"set_widgets",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"existing_inasafe_field",
"=",
"self",
".",
"parent",
".",
"get_existing_keyword",
"(",
"'inasafe_fields'",
")",
"existing_inasafe_default_values",
"=",
"self",
".",
"parent",
".",
"get... | Set widgets on the Extra Keywords tab. | [
"Set",
"widgets",
"on",
"the",
"Extra",
"Keywords",
"tab",
"."
] | python | train |
Jammy2211/PyAutoLens | autolens/data/array/mask.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/mask.py#L231-L241 | def map_2d_array_to_masked_1d_array(self, array_2d):
"""For a 2D array (e.g. an image, noise_map, etc.) map it to a masked 1D array of valuees using this mask.
Parameters
----------
array_2d : ndarray | None | float
The 2D array to be mapped to a masked 1D array.
"""... | [
"def",
"map_2d_array_to_masked_1d_array",
"(",
"self",
",",
"array_2d",
")",
":",
"if",
"array_2d",
"is",
"None",
"or",
"isinstance",
"(",
"array_2d",
",",
"float",
")",
":",
"return",
"array_2d",
"return",
"mapping_util",
".",
"map_2d_array_to_masked_1d_array_from_... | For a 2D array (e.g. an image, noise_map, etc.) map it to a masked 1D array of valuees using this mask.
Parameters
----------
array_2d : ndarray | None | float
The 2D array to be mapped to a masked 1D array. | [
"For",
"a",
"2D",
"array",
"(",
"e",
".",
"g",
".",
"an",
"image",
"noise_map",
"etc",
".",
")",
"map",
"it",
"to",
"a",
"masked",
"1D",
"array",
"of",
"valuees",
"using",
"this",
"mask",
"."
] | python | valid |
pypa/pipenv | pipenv/vendor/click/decorators.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/decorators.py#L286-L307 | def help_option(*param_decls, **attrs):
"""Adds a ``--help`` option which immediately ends the program
printing out the help page. This is usually unnecessary to add as
this is added by default to all commands unless suppressed.
Like :func:`version_option`, this is implemented as eager option that
... | [
"def",
"help_option",
"(",
"*",
"param_decls",
",",
"*",
"*",
"attrs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"callback",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"value",
"and",
"not",
"ctx",
".",
"resilient_parsing"... | Adds a ``--help`` option which immediately ends the program
printing out the help page. This is usually unnecessary to add as
this is added by default to all commands unless suppressed.
Like :func:`version_option`, this is implemented as eager option that
prints in the callback and exits.
All arg... | [
"Adds",
"a",
"--",
"help",
"option",
"which",
"immediately",
"ends",
"the",
"program",
"printing",
"out",
"the",
"help",
"page",
".",
"This",
"is",
"usually",
"unnecessary",
"to",
"add",
"as",
"this",
"is",
"added",
"by",
"default",
"to",
"all",
"commands"... | python | train |
apache/airflow | airflow/models/xcom.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/xcom.py#L88-L136 | def set(
cls,
key,
value,
execution_date,
task_id,
dag_id,
session=None):
"""
Store an XCom value.
TODO: "pickling" has been deprecated and JSON is preferred.
"pickling" will be removed in Airflow 2.0.
... | [
"def",
"set",
"(",
"cls",
",",
"key",
",",
"value",
",",
"execution_date",
",",
"task_id",
",",
"dag_id",
",",
"session",
"=",
"None",
")",
":",
"session",
".",
"expunge_all",
"(",
")",
"enable_pickling",
"=",
"configuration",
".",
"getboolean",
"(",
"'c... | Store an XCom value.
TODO: "pickling" has been deprecated and JSON is preferred.
"pickling" will be removed in Airflow 2.0.
:return: None | [
"Store",
"an",
"XCom",
"value",
".",
"TODO",
":",
"pickling",
"has",
"been",
"deprecated",
"and",
"JSON",
"is",
"preferred",
".",
"pickling",
"will",
"be",
"removed",
"in",
"Airflow",
"2",
".",
"0",
"."
] | python | test |
stephantul/somber | somber/base.py | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/base.py#L471-L494 | def predict(self, X, batch_size=1, show_progressbar=False):
"""
Predict the BMU for each input data.
Parameters
----------
X : numpy array.
The input data.
batch_size : int, optional, default 100
The batch size to use in prediction. This may affec... | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"batch_size",
"=",
"1",
",",
"show_progressbar",
"=",
"False",
")",
":",
"dist",
"=",
"self",
".",
"transform",
"(",
"X",
",",
"batch_size",
",",
"show_progressbar",
")",
"res",
"=",
"dist",
".",
"__getattr... | Predict the BMU for each input data.
Parameters
----------
X : numpy array.
The input data.
batch_size : int, optional, default 100
The batch size to use in prediction. This may affect prediction
in stateful, i.e. sequential SOMs.
show_progres... | [
"Predict",
"the",
"BMU",
"for",
"each",
"input",
"data",
"."
] | python | train |
pkgw/pwkit | pwkit/environments/__init__.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/environments/__init__.py#L113-L130 | def prepend_environ_path(env, name, text, pathsep=os.pathsep):
"""Prepend `text` into a $PATH-like environment variable. `env` is a
dictionary of environment variables and `name` is the variable name.
`pathsep` is the character separating path elements, defaulting to
`os.pathsep`. The variable will be c... | [
"def",
"prepend_environ_path",
"(",
"env",
",",
"name",
",",
"text",
",",
"pathsep",
"=",
"os",
".",
"pathsep",
")",
":",
"env",
"[",
"name",
"]",
"=",
"prepend_path",
"(",
"env",
".",
"get",
"(",
"name",
")",
",",
"text",
",",
"pathsep",
"=",
"pat... | Prepend `text` into a $PATH-like environment variable. `env` is a
dictionary of environment variables and `name` is the variable name.
`pathsep` is the character separating path elements, defaulting to
`os.pathsep`. The variable will be created if it is not already in `env`.
Returns `env`.
Example:... | [
"Prepend",
"text",
"into",
"a",
"$PATH",
"-",
"like",
"environment",
"variable",
".",
"env",
"is",
"a",
"dictionary",
"of",
"environment",
"variables",
"and",
"name",
"is",
"the",
"variable",
"name",
".",
"pathsep",
"is",
"the",
"character",
"separating",
"p... | python | train |
quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L74-L92 | def validate_column_specs(events, columns):
"""
Verify that the columns of ``events`` can be used by a
EarningsEstimatesLoader to serve the BoundColumns described by
`columns`.
"""
required = required_estimates_fields(columns)
received = set(events.columns)
missing = required - received
... | [
"def",
"validate_column_specs",
"(",
"events",
",",
"columns",
")",
":",
"required",
"=",
"required_estimates_fields",
"(",
"columns",
")",
"received",
"=",
"set",
"(",
"events",
".",
"columns",
")",
"missing",
"=",
"required",
"-",
"received",
"if",
"missing"... | Verify that the columns of ``events`` can be used by a
EarningsEstimatesLoader to serve the BoundColumns described by
`columns`. | [
"Verify",
"that",
"the",
"columns",
"of",
"events",
"can",
"be",
"used",
"by",
"a",
"EarningsEstimatesLoader",
"to",
"serve",
"the",
"BoundColumns",
"described",
"by",
"columns",
"."
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/server/server.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/server.py#L192-L215 | def _create_handler(self, config):
"""
Creates a handler from its config.
Params:
config: handler config
Returns:
handler instance
"""
if config is None:
raise ValueError('No handler config to create handler from.')
if 'n... | [
"def",
"_create_handler",
"(",
"self",
",",
"config",
")",
":",
"if",
"config",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No handler config to create handler from.'",
")",
"if",
"'name'",
"not",
"in",
"config",
":",
"raise",
"ValueError",
"(",
"'Handler n... | Creates a handler from its config.
Params:
config: handler config
Returns:
handler instance | [
"Creates",
"a",
"handler",
"from",
"its",
"config",
"."
] | python | train |
ethereum/lahja | lahja/endpoint.py | https://github.com/ethereum/lahja/blob/e3993c5892232887a11800ed3e66332febcee96b/lahja/endpoint.py#L359-L377 | def broadcast(self, item: BaseEvent, config: Optional[BroadcastConfig] = None) -> None:
"""
Broadcast an instance of :class:`~lahja.misc.BaseEvent` on the event bus. Takes
an optional second parameter of :class:`~lahja.misc.BroadcastConfig` to decide
where this event should be broadcaste... | [
"def",
"broadcast",
"(",
"self",
",",
"item",
":",
"BaseEvent",
",",
"config",
":",
"Optional",
"[",
"BroadcastConfig",
"]",
"=",
"None",
")",
"->",
"None",
":",
"item",
".",
"_origin",
"=",
"self",
".",
"name",
"if",
"config",
"is",
"not",
"None",
"... | Broadcast an instance of :class:`~lahja.misc.BaseEvent` on the event bus. Takes
an optional second parameter of :class:`~lahja.misc.BroadcastConfig` to decide
where this event should be broadcasted to. By default, events are broadcasted across
all connected endpoints with their consuming call si... | [
"Broadcast",
"an",
"instance",
"of",
":",
"class",
":",
"~lahja",
".",
"misc",
".",
"BaseEvent",
"on",
"the",
"event",
"bus",
".",
"Takes",
"an",
"optional",
"second",
"parameter",
"of",
":",
"class",
":",
"~lahja",
".",
"misc",
".",
"BroadcastConfig",
"... | python | train |
billy-yoyo/RainbowSixSiege-Python-API | r6sapi/r6sapi.py | https://github.com/billy-yoyo/RainbowSixSiege-Python-API/blob/9860fdfd9a78aabd977eaa71b0a4ab4ed69e94d0/r6sapi/r6sapi.py#L1259-L1277 | def get_operator(self, operator):
"""|coro|
Checks the players stats for this operator, only loading them if they haven't already been found
Parameters
----------
operator : str
the name of the operator
Returns
-------
:class:`Operator`
... | [
"def",
"get_operator",
"(",
"self",
",",
"operator",
")",
":",
"if",
"operator",
"in",
"self",
".",
"operators",
":",
"return",
"self",
".",
"operators",
"[",
"operator",
"]",
"result",
"=",
"yield",
"from",
"self",
".",
"load_operator",
"(",
"operator",
... | |coro|
Checks the players stats for this operator, only loading them if they haven't already been found
Parameters
----------
operator : str
the name of the operator
Returns
-------
:class:`Operator`
the operator object found | [
"|coro|"
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/templating.py#L21-L33 | def _default_template_ctx_processor():
"""Default template context processor. Injects `request`,
`session` and `g`.
"""
reqctx = _request_ctx_stack.top
appctx = _app_ctx_stack.top
rv = {}
if appctx is not None:
rv['g'] = appctx.g
if reqctx is not None:
rv['request'] = re... | [
"def",
"_default_template_ctx_processor",
"(",
")",
":",
"reqctx",
"=",
"_request_ctx_stack",
".",
"top",
"appctx",
"=",
"_app_ctx_stack",
".",
"top",
"rv",
"=",
"{",
"}",
"if",
"appctx",
"is",
"not",
"None",
":",
"rv",
"[",
"'g'",
"]",
"=",
"appctx",
".... | Default template context processor. Injects `request`,
`session` and `g`. | [
"Default",
"template",
"context",
"processor",
".",
"Injects",
"request",
"session",
"and",
"g",
"."
] | python | test |
mozilla/DeepSpeech | bin/benchmark_nc.py | https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/bin/benchmark_nc.py#L139-L186 | def all_files(models=[]):
r'''
Return a list of full path of files matching 'models', sorted in human
numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000).
Files are supposed to be named identically except one variable component
e.g. the list,
test.weights.e5.lstm1200.ldc93s1.pb
... | [
"def",
"all_files",
"(",
"models",
"=",
"[",
"]",
")",
":",
"def",
"nsort",
"(",
"a",
",",
"b",
")",
":",
"fa",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"a",
")",
".",
"split",
"(",
"'.'",
")",
"fb",
"=",
"os",
".",
"path",
".",
"basen... | r'''
Return a list of full path of files matching 'models', sorted in human
numerical order (i.e., 0 1 2 ..., 10 11 12, ..., 100, ..., 1000).
Files are supposed to be named identically except one variable component
e.g. the list,
test.weights.e5.lstm1200.ldc93s1.pb
test.weights.e5.lstm1000.... | [
"r",
"Return",
"a",
"list",
"of",
"full",
"path",
"of",
"files",
"matching",
"models",
"sorted",
"in",
"human",
"numerical",
"order",
"(",
"i",
".",
"e",
".",
"0",
"1",
"2",
"...",
"10",
"11",
"12",
"...",
"100",
"...",
"1000",
")",
"."
] | python | train |
Equitable/trump | trump/converting/objects.py | https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/trump/converting/objects.py#L65-L76 | def use_trump_data(self, symbols):
"""
Use trump data to build conversion table
symbols :
list of symbols:
will attempt to use units to build the conversion table,
strings represent symbol names.
"""
dfs = {sym.units : sym.df[... | [
"def",
"use_trump_data",
"(",
"self",
",",
"symbols",
")",
":",
"dfs",
"=",
"{",
"sym",
".",
"units",
":",
"sym",
".",
"df",
"[",
"sym",
".",
"name",
"]",
"for",
"sym",
"in",
"symbols",
"}",
"self",
".",
"build_conversion_table",
"(",
"dfs",
")"
] | Use trump data to build conversion table
symbols :
list of symbols:
will attempt to use units to build the conversion table,
strings represent symbol names. | [
"Use",
"trump",
"data",
"to",
"build",
"conversion",
"table",
"symbols",
":",
"list",
"of",
"symbols",
":",
"will",
"attempt",
"to",
"use",
"units",
"to",
"build",
"the",
"conversion",
"table",
"strings",
"represent",
"symbol",
"names",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/atlas.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L2713-L2722 | def canonical_peer( self, peer ):
"""
Get the canonical peer name
"""
their_host, their_port = url_to_host_port( peer )
if their_host in ['127.0.0.1', '::1']:
their_host = 'localhost'
return "%s:%s" % (their_host, their_port) | [
"def",
"canonical_peer",
"(",
"self",
",",
"peer",
")",
":",
"their_host",
",",
"their_port",
"=",
"url_to_host_port",
"(",
"peer",
")",
"if",
"their_host",
"in",
"[",
"'127.0.0.1'",
",",
"'::1'",
"]",
":",
"their_host",
"=",
"'localhost'",
"return",
"\"%s:%... | Get the canonical peer name | [
"Get",
"the",
"canonical",
"peer",
"name"
] | python | train |
bitshares/python-bitshares | bitshares/bitshares.py | https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L128-L163 | def transfer(self, to, amount, asset, memo="", account=None, **kwargs):
""" Transfer an asset to another account.
:param str to: Recipient
:param float amount: Amount to transfer
:param str asset: Asset to transfer
:param str memo: (optional) Memo, may begin with... | [
"def",
"transfer",
"(",
"self",
",",
"to",
",",
"amount",
",",
"asset",
",",
"memo",
"=",
"\"\"",
",",
"account",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"memo",
"import",
"Memo",
"if",
"not",
"account",
":",
"if",
"\"default_a... | Transfer an asset to another account.
:param str to: Recipient
:param float amount: Amount to transfer
:param str asset: Asset to transfer
:param str memo: (optional) Memo, may begin with `#` for encrypted
messaging
:param str account: (option... | [
"Transfer",
"an",
"asset",
"to",
"another",
"account",
"."
] | python | train |
marcomusy/vtkplotter | vtkplotter/vtkio.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/vtkio.py#L357-L405 | def loadDolfin(filename, c="gold", alpha=0.5, wire=None, bc=None):
"""Reads a `Fenics/Dolfin` file format. Return an ``Actor(vtkActor)`` object."""
if not os.path.exists(filename):
colors.printc("~noentry Error in loadDolfin: Cannot find", filename, c=1)
return None
import xml.etree.ElementT... | [
"def",
"loadDolfin",
"(",
"filename",
",",
"c",
"=",
"\"gold\"",
",",
"alpha",
"=",
"0.5",
",",
"wire",
"=",
"None",
",",
"bc",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"colors",
".",
"print... | Reads a `Fenics/Dolfin` file format. Return an ``Actor(vtkActor)`` object. | [
"Reads",
"a",
"Fenics",
"/",
"Dolfin",
"file",
"format",
".",
"Return",
"an",
"Actor",
"(",
"vtkActor",
")",
"object",
"."
] | python | train |
AtteqCom/zsl | src/zsl/utils/xml_helper.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_helper.py#L81-L96 | def attrib_to_dict(element, *args, **kwargs):
"""For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be
``None``.
attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'}
Mapping between xml attributes and dictionary... | [
"def",
"attrib_to_dict",
"(",
"element",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"return",
"{",
"key",
":",
"element",
".",
"get",
"(",
"key",
")",
"for",
"key",
"in",
"args",
"}",
"if"... | For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be
``None``.
attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'}
Mapping between xml attributes and dictionary keys is done with kwargs.
attrib_to_dict(element... | [
"For",
"an",
"ElementTree",
"element",
"extract",
"specified",
"attributes",
".",
"If",
"an",
"attribute",
"does",
"not",
"exists",
"its",
"value",
"will",
"be",
"None",
"."
] | python | train |
yjzhang/uncurl_python | uncurl/nb_clustering.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/nb_clustering.py#L22-L28 | def log_ncr(a, b):
"""
Returns log(nCr(a,b)), given that b<a. Does not assume that a and b
are integers (uses log-gamma).
"""
val = gammaln(a+1) - gammaln(a-b+1) - gammaln(b+1)
return val | [
"def",
"log_ncr",
"(",
"a",
",",
"b",
")",
":",
"val",
"=",
"gammaln",
"(",
"a",
"+",
"1",
")",
"-",
"gammaln",
"(",
"a",
"-",
"b",
"+",
"1",
")",
"-",
"gammaln",
"(",
"b",
"+",
"1",
")",
"return",
"val"
] | Returns log(nCr(a,b)), given that b<a. Does not assume that a and b
are integers (uses log-gamma). | [
"Returns",
"log",
"(",
"nCr",
"(",
"a",
"b",
"))",
"given",
"that",
"b<a",
".",
"Does",
"not",
"assume",
"that",
"a",
"and",
"b",
"are",
"integers",
"(",
"uses",
"log",
"-",
"gamma",
")",
"."
] | python | train |
google/grr | grr/server/grr_response_server/databases/mem_clients.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_clients.py#L342-L352 | def ReadClientCrashInfoHistory(self, client_id):
"""Reads the full crash history for a particular client."""
history = self.crash_history.get(client_id)
if not history:
return []
res = []
for ts in sorted(history, reverse=True):
client_data = rdf_client.ClientCrash.FromSerializedString(h... | [
"def",
"ReadClientCrashInfoHistory",
"(",
"self",
",",
"client_id",
")",
":",
"history",
"=",
"self",
".",
"crash_history",
".",
"get",
"(",
"client_id",
")",
"if",
"not",
"history",
":",
"return",
"[",
"]",
"res",
"=",
"[",
"]",
"for",
"ts",
"in",
"so... | Reads the full crash history for a particular client. | [
"Reads",
"the",
"full",
"crash",
"history",
"for",
"a",
"particular",
"client",
"."
] | python | train |
bcb/jsonrpcclient | jsonrpcclient/clients/tornado_client.py | https://github.com/bcb/jsonrpcclient/blob/5b5abc28d1466d694c80b80c427a5dcb275382bb/jsonrpcclient/clients/tornado_client.py#L46-L66 | async def send_message( # type: ignore
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
"""
Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the reque... | [
"async",
"def",
"send_message",
"(",
"# type: ignore",
"self",
",",
"request",
":",
"str",
",",
"response_expected",
":",
"bool",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Response",
":",
"headers",
"=",
"dict",
"(",
"self",
".",
"DEFAULT_HEADERS",
... | Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. | [
"Transport",
"the",
"message",
"to",
"the",
"server",
"and",
"return",
"the",
"response",
"."
] | python | train |
edx/edx-django-release-util | release_util/management/commands/__init__.py | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L310-L324 | def apply_all(self):
"""
Applies all Django model migrations at once, recording the result.
"""
if self.__closed:
raise MigrationSessionError("Can't apply applied session")
if self._to_apply:
raise MigrationSessionError("Can't apply_all with migrations add... | [
"def",
"apply_all",
"(",
"self",
")",
":",
"if",
"self",
".",
"__closed",
":",
"raise",
"MigrationSessionError",
"(",
"\"Can't apply applied session\"",
")",
"if",
"self",
".",
"_to_apply",
":",
"raise",
"MigrationSessionError",
"(",
"\"Can't apply_all with migrations... | Applies all Django model migrations at once, recording the result. | [
"Applies",
"all",
"Django",
"model",
"migrations",
"at",
"once",
"recording",
"the",
"result",
"."
] | python | train |
deepmipt/DeepPavlov | deeppavlov/models/preprocessors/capitalization.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/models/preprocessors/capitalization.py#L75-L108 | def process_word(word: str, to_lower: bool = False,
append_case: Optional[str] = None) -> Tuple[str]:
"""Converts word to a tuple of symbols, optionally converts it to lowercase
and adds capitalization label.
Args:
word: input word
to_lower: whether to lowercase
app... | [
"def",
"process_word",
"(",
"word",
":",
"str",
",",
"to_lower",
":",
"bool",
"=",
"False",
",",
"append_case",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"str",
"]",
":",
"if",
"all",
"(",
"x",
".",
"isupper",
"(",
"... | Converts word to a tuple of symbols, optionally converts it to lowercase
and adds capitalization label.
Args:
word: input word
to_lower: whether to lowercase
append_case: whether to add case mark
('<FIRST_UPPER>' for first capital and '<ALL_UPPER>' for all caps)
Returns... | [
"Converts",
"word",
"to",
"a",
"tuple",
"of",
"symbols",
"optionally",
"converts",
"it",
"to",
"lowercase",
"and",
"adds",
"capitalization",
"label",
"."
] | python | test |
koenedaele/skosprovider | skosprovider/providers.py | https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/providers.py#L488-L503 | def _get_find_dict(self, c, **kwargs):
'''
Return a dict that can be used in the return list of the :meth:`find`
method.
:param c: A :class:`skosprovider.skos.Concept` or
:class:`skosprovider.skos.Collection`.
:rtype: dict
'''
language = self._get_lan... | [
"def",
"_get_find_dict",
"(",
"self",
",",
"c",
",",
"*",
"*",
"kwargs",
")",
":",
"language",
"=",
"self",
".",
"_get_language",
"(",
"*",
"*",
"kwargs",
")",
"return",
"{",
"'id'",
":",
"c",
".",
"id",
",",
"'uri'",
":",
"c",
".",
"uri",
",",
... | Return a dict that can be used in the return list of the :meth:`find`
method.
:param c: A :class:`skosprovider.skos.Concept` or
:class:`skosprovider.skos.Collection`.
:rtype: dict | [
"Return",
"a",
"dict",
"that",
"can",
"be",
"used",
"in",
"the",
"return",
"list",
"of",
"the",
":",
"meth",
":",
"find",
"method",
"."
] | python | valid |
nirum/tableprint | tableprint/printer.py | https://github.com/nirum/tableprint/blob/50ab4b96706fce8ee035a4d48cb456e3271eab3d/tableprint/printer.py#L276-L284 | def dataframe(df, **kwargs):
"""Print table with data from the given pandas DataFrame
Parameters
----------
df : DataFrame
A pandas DataFrame with the table to print
"""
table(df.values, list(df.columns), **kwargs) | [
"def",
"dataframe",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"table",
"(",
"df",
".",
"values",
",",
"list",
"(",
"df",
".",
"columns",
")",
",",
"*",
"*",
"kwargs",
")"
] | Print table with data from the given pandas DataFrame
Parameters
----------
df : DataFrame
A pandas DataFrame with the table to print | [
"Print",
"table",
"with",
"data",
"from",
"the",
"given",
"pandas",
"DataFrame"
] | python | train |
joerick/pyinstrument | pyinstrument/vendor/decorator.py | https://github.com/joerick/pyinstrument/blob/cc4f3f6fc1b493d7cd058ecf41ad012e0030a512/pyinstrument/vendor/decorator.py#L331-L433 | def dispatch_on(*dispatch_args):
"""
Factory of decorators turning a function into a generic function
dispatching on the given arguments.
"""
assert dispatch_args, 'No dispatch args passed'
dispatch_str = '(%s,)' % ', '.join(dispatch_args)
def check(arguments, wrong=operator.ne, msg=''):
... | [
"def",
"dispatch_on",
"(",
"*",
"dispatch_args",
")",
":",
"assert",
"dispatch_args",
",",
"'No dispatch args passed'",
"dispatch_str",
"=",
"'(%s,)'",
"%",
"', '",
".",
"join",
"(",
"dispatch_args",
")",
"def",
"check",
"(",
"arguments",
",",
"wrong",
"=",
"o... | Factory of decorators turning a function into a generic function
dispatching on the given arguments. | [
"Factory",
"of",
"decorators",
"turning",
"a",
"function",
"into",
"a",
"generic",
"function",
"dispatching",
"on",
"the",
"given",
"arguments",
"."
] | python | train |
tuomas2/automate | src/automate/extensions/rpc/rpc.py | https://github.com/tuomas2/automate/blob/d8a8cd03cd0da047e033a2d305f3f260f8c4e017/src/automate/extensions/rpc/rpc.py#L44-L50 | def set_object_status(self, statusdict):
"""
Set statuses from a dictionary of format ``{name: status}``
"""
for name, value in statusdict.items():
getattr(self.system, name).status = value
return True | [
"def",
"set_object_status",
"(",
"self",
",",
"statusdict",
")",
":",
"for",
"name",
",",
"value",
"in",
"statusdict",
".",
"items",
"(",
")",
":",
"getattr",
"(",
"self",
".",
"system",
",",
"name",
")",
".",
"status",
"=",
"value",
"return",
"True"
] | Set statuses from a dictionary of format ``{name: status}`` | [
"Set",
"statuses",
"from",
"a",
"dictionary",
"of",
"format",
"{",
"name",
":",
"status",
"}"
] | python | train |
eight04/pyAPNG | apng/__init__.py | https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L321-L334 | def append(self, png, **options):
"""Append one frame.
:arg PNG png: Append a :class:`PNG` as a frame.
:arg dict options: The options for :class:`FrameControl`.
"""
if not isinstance(png, PNG):
raise TypeError("Expect an instance of `PNG` but got `{}`".format(png))
control = FrameControl(**options)
... | [
"def",
"append",
"(",
"self",
",",
"png",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"isinstance",
"(",
"png",
",",
"PNG",
")",
":",
"raise",
"TypeError",
"(",
"\"Expect an instance of `PNG` but got `{}`\"",
".",
"format",
"(",
"png",
")",
")",
"co... | Append one frame.
:arg PNG png: Append a :class:`PNG` as a frame.
:arg dict options: The options for :class:`FrameControl`. | [
"Append",
"one",
"frame",
".",
":",
"arg",
"PNG",
"png",
":",
"Append",
"a",
":",
"class",
":",
"PNG",
"as",
"a",
"frame",
".",
":",
"arg",
"dict",
"options",
":",
"The",
"options",
"for",
":",
"class",
":",
"FrameControl",
"."
] | python | train |
raiden-network/raiden | raiden/raiden_service.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L1004-L1009 | def sign(self, message: Message):
""" Sign message inplace. """
if not isinstance(message, SignedMessage):
raise ValueError('{} is not signable.'.format(repr(message)))
message.sign(self.signer) | [
"def",
"sign",
"(",
"self",
",",
"message",
":",
"Message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"SignedMessage",
")",
":",
"raise",
"ValueError",
"(",
"'{} is not signable.'",
".",
"format",
"(",
"repr",
"(",
"message",
")",
")",
")... | Sign message inplace. | [
"Sign",
"message",
"inplace",
"."
] | python | train |
ecell/ecell4 | ecell4/extra/azure_batch.py | https://github.com/ecell/ecell4/blob/a4a1229661c39b2059adbbacae9090e5ba664e01/ecell4/extra/azure_batch.py#L45-L60 | def print_batch_exception(batch_exception):
"""Prints the contents of the specified Batch exception.
:param batch_exception:
"""
_log.error('-------------------------------------------')
_log.error('Exception encountered:')
if batch_exception.error and \
batch_exception.error.messag... | [
"def",
"print_batch_exception",
"(",
"batch_exception",
")",
":",
"_log",
".",
"error",
"(",
"'-------------------------------------------'",
")",
"_log",
".",
"error",
"(",
"'Exception encountered:'",
")",
"if",
"batch_exception",
".",
"error",
"and",
"batch_exception"... | Prints the contents of the specified Batch exception.
:param batch_exception: | [
"Prints",
"the",
"contents",
"of",
"the",
"specified",
"Batch",
"exception",
"."
] | python | train |
Grunny/zap-cli | zapcli/commands/context.py | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L35-L39 | def context_new(zap_helper, name):
"""Create a new context."""
console.info('Creating context with name: {0}'.format(name))
res = zap_helper.zap.context.new_context(contextname=name)
console.info('Context "{0}" created with ID: {1}'.format(name, res)) | [
"def",
"context_new",
"(",
"zap_helper",
",",
"name",
")",
":",
"console",
".",
"info",
"(",
"'Creating context with name: {0}'",
".",
"format",
"(",
"name",
")",
")",
"res",
"=",
"zap_helper",
".",
"zap",
".",
"context",
".",
"new_context",
"(",
"contextnam... | Create a new context. | [
"Create",
"a",
"new",
"context",
"."
] | python | train |
rkhleics/wagtailmenus | wagtailmenus/models/pages.py | https://github.com/rkhleics/wagtailmenus/blob/a41f240bed0d362e0d4dd4ef04a230f2b1827a93/wagtailmenus/models/pages.py#L67-L80 | def has_submenu_items(self, current_page, allow_repeating_parents,
original_menu_tag, menu_instance=None, request=None):
"""
When rendering pages in a menu template a `has_children_in_menu`
attribute is added to each page, letting template developers know
whethe... | [
"def",
"has_submenu_items",
"(",
"self",
",",
"current_page",
",",
"allow_repeating_parents",
",",
"original_menu_tag",
",",
"menu_instance",
"=",
"None",
",",
"request",
"=",
"None",
")",
":",
"return",
"menu_instance",
".",
"page_has_children",
"(",
"self",
")"
... | When rendering pages in a menu template a `has_children_in_menu`
attribute is added to each page, letting template developers know
whether or not the item has a submenu that must be rendered.
By default, we return a boolean indicating whether the page has
suitable child pages to include... | [
"When",
"rendering",
"pages",
"in",
"a",
"menu",
"template",
"a",
"has_children_in_menu",
"attribute",
"is",
"added",
"to",
"each",
"page",
"letting",
"template",
"developers",
"know",
"whether",
"or",
"not",
"the",
"item",
"has",
"a",
"submenu",
"that",
"must... | python | train |
3ll3d00d/vibe | backend/src/analyser/common/targetcontroller.py | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/targetcontroller.py#L64-L75 | def delete(self, name):
"""
Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted.
"""
if name in self._cache:
del self._cache[name]
self.writeCache()
# TODO clean files
return True
... | [
"def",
"delete",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_cache",
":",
"del",
"self",
".",
"_cache",
"[",
"name",
"]",
"self",
".",
"writeCache",
"(",
")",
"# TODO clean files",
"return",
"True",
"return",
"False"
] | Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted. | [
"Deletes",
"the",
"named",
"entry",
"in",
"the",
"cache",
".",
":",
"param",
"name",
":",
"the",
"name",
".",
":",
"return",
":",
"true",
"if",
"it",
"is",
"deleted",
"."
] | python | train |
titusjan/argos | argos/config/abstractcti.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/abstractcti.py#L400-L412 | def _nodeGetNonDefaultsDict(self):
""" Retrieves this nodes` values as a dictionary to be used for persistence.
A dictionary with the data value will be returned if the data is not equal to the
defaultData, the node is enabled and the node is editable. Otherwise and empty
dic... | [
"def",
"_nodeGetNonDefaultsDict",
"(",
"self",
")",
":",
"dct",
"=",
"{",
"}",
"isEditable",
"=",
"bool",
"(",
"int",
"(",
"self",
".",
"valueColumnItemFlags",
")",
"and",
"Qt",
".",
"ItemIsEditable",
")",
"if",
"(",
"self",
".",
"data",
"!=",
"self",
... | Retrieves this nodes` values as a dictionary to be used for persistence.
A dictionary with the data value will be returned if the data is not equal to the
defaultData, the node is enabled and the node is editable. Otherwise and empty
dictionary is returned.
Non-recursive... | [
"Retrieves",
"this",
"nodes",
"values",
"as",
"a",
"dictionary",
"to",
"be",
"used",
"for",
"persistence",
".",
"A",
"dictionary",
"with",
"the",
"data",
"value",
"will",
"be",
"returned",
"if",
"the",
"data",
"is",
"not",
"equal",
"to",
"the",
"defaultDat... | python | train |
annoviko/pyclustering | pyclustering/cluster/rock.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/rock.py#L97-L123 | def process(self):
"""!
@brief Performs cluster analysis in line with rules of ROCK algorithm.
@remark Results of clustering can be obtained using corresponding get methods.
@see get_clusters()
"""
# TODO: (Not related to spec... | [
"def",
"process",
"(",
"self",
")",
":",
"# TODO: (Not related to specification, just idea) First iteration should be investigated. Euclidean distance should be used for clustering between two \r",
"# points and rock algorithm between clusters because we consider non-categorical samples. But it is req... | !
@brief Performs cluster analysis in line with rules of ROCK algorithm.
@remark Results of clustering can be obtained using corresponding get methods.
@see get_clusters() | [
"!"
] | python | valid |
the01/python-paps | examples/measure/server.py | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/measure/server.py#L136-L155 | def create(host, port):
"""
Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None
"""
wrapper = WrapperServer({
'server': None
})
d = {
'listen_port': port,
'changer': wrapper
}
if host:
... | [
"def",
"create",
"(",
"host",
",",
"port",
")",
":",
"wrapper",
"=",
"WrapperServer",
"(",
"{",
"'server'",
":",
"None",
"}",
")",
"d",
"=",
"{",
"'listen_port'",
":",
"port",
",",
"'changer'",
":",
"wrapper",
"}",
"if",
"host",
":",
"d",
"[",
"'li... | Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None | [
"Prepare",
"server",
"to",
"execute"
] | python | train |
senaite/senaite.core | bika/lims/browser/analyses/view.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analyses/view.py#L1176-L1190 | def _folder_item_remarks(self, analysis_brain, item):
"""Renders the Remarks field for the passed in analysis
If the edition of the analysis is permitted, adds the field into the
list of editable fields.
:param analysis_brain: Brain that represents an analysis
:param item: anal... | [
"def",
"_folder_item_remarks",
"(",
"self",
",",
"analysis_brain",
",",
"item",
")",
":",
"if",
"self",
".",
"analysis_remarks_enabled",
"(",
")",
":",
"item",
"[",
"\"Remarks\"",
"]",
"=",
"analysis_brain",
".",
"getRemarks",
"if",
"self",
".",
"is_analysis_e... | Renders the Remarks field for the passed in analysis
If the edition of the analysis is permitted, adds the field into the
list of editable fields.
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row | [
"Renders",
"the",
"Remarks",
"field",
"for",
"the",
"passed",
"in",
"analysis"
] | python | train |
fronzbot/blinkpy | blinkpy/api.py | https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/api.py#L80-L88 | def request_system_disarm(blink, network):
"""
Disarm system.
:param blink: Blink instance.
:param network: Sync module network id.
"""
url = "{}/network/{}/disarm".format(blink.urls.base_url, network)
return http_post(blink, url) | [
"def",
"request_system_disarm",
"(",
"blink",
",",
"network",
")",
":",
"url",
"=",
"\"{}/network/{}/disarm\"",
".",
"format",
"(",
"blink",
".",
"urls",
".",
"base_url",
",",
"network",
")",
"return",
"http_post",
"(",
"blink",
",",
"url",
")"
] | Disarm system.
:param blink: Blink instance.
:param network: Sync module network id. | [
"Disarm",
"system",
"."
] | python | train |
log2timeline/dfdatetime | dfdatetime/time_elements.py | https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L528-L545 | def CopyToDateTimeString(self):
"""Copies the time elements to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or
"YYYY-MM-DD hh:mm:ss.######" or None if time elements are missing.
Raises:
ValueError: if the precision value is unsupported... | [
"def",
"CopyToDateTimeString",
"(",
"self",
")",
":",
"if",
"self",
".",
"_number_of_seconds",
"is",
"None",
"or",
"self",
".",
"fraction_of_second",
"is",
"None",
":",
"return",
"None",
"precision_helper",
"=",
"precisions",
".",
"PrecisionHelperFactory",
".",
... | Copies the time elements to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss" or
"YYYY-MM-DD hh:mm:ss.######" or None if time elements are missing.
Raises:
ValueError: if the precision value is unsupported. | [
"Copies",
"the",
"time",
"elements",
"to",
"a",
"date",
"and",
"time",
"string",
"."
] | python | train |
boundary/pulse-api-cli | boundary/hostgroup_get.py | https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/hostgroup_get.py#L36-L44 | def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.hostGroupId is not None:
self.hostGroupId = self.args.hostGroupId
self.path = "v1/hostgroup/{0}".format(str(self.hostGroupId)) | [
"def",
"get_arguments",
"(",
"self",
")",
":",
"ApiCli",
".",
"get_arguments",
"(",
"self",
")",
"if",
"self",
".",
"args",
".",
"hostGroupId",
"is",
"not",
"None",
":",
"self",
".",
"hostGroupId",
"=",
"self",
".",
"args",
".",
"hostGroupId",
"self",
... | Extracts the specific arguments of this CLI | [
"Extracts",
"the",
"specific",
"arguments",
"of",
"this",
"CLI"
] | python | test |
GNS3/gns3-server | gns3server/web/documentation.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/web/documentation.py#L121-L127 | def _include_query_example(self, f, method, path, api_version, server_type):
"""If a sample session is available we include it in documentation"""
m = method["method"].lower()
query_path = "{}_{}_{}.txt".format(server_type, m, self._file_path(path))
if os.path.isfile(os.path.join(self._d... | [
"def",
"_include_query_example",
"(",
"self",
",",
"f",
",",
"method",
",",
"path",
",",
"api_version",
",",
"server_type",
")",
":",
"m",
"=",
"method",
"[",
"\"method\"",
"]",
".",
"lower",
"(",
")",
"query_path",
"=",
"\"{}_{}_{}.txt\"",
".",
"format",
... | If a sample session is available we include it in documentation | [
"If",
"a",
"sample",
"session",
"is",
"available",
"we",
"include",
"it",
"in",
"documentation"
] | python | train |
lago-project/lago | lago/log_utils.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L436-L476 | def handle_error(self):
"""
Handles an error log record that should be shown
Returns:
None
"""
if not self.tasks:
return
# All the parents inherit the failure
self.mark_parent_tasks_as_failed(
self.cur_task,
flush_... | [
"def",
"handle_error",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"tasks",
":",
"return",
"# All the parents inherit the failure",
"self",
".",
"mark_parent_tasks_as_failed",
"(",
"self",
".",
"cur_task",
",",
"flush_logs",
"=",
"True",
",",
")",
"# Show t... | Handles an error log record that should be shown
Returns:
None | [
"Handles",
"an",
"error",
"log",
"record",
"that",
"should",
"be",
"shown"
] | python | train |
dropbox/stone | stone/frontend/parser.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/parser.py#L551-L560 | def p_union_patch(self, p):
"""union_patch : PATCH uniont ID NL INDENT field_list examples DEDENT"""
p[0] = AstUnionPatch(
path=self.path,
lineno=p[2][1],
lexpos=p[2][2],
name=p[3],
fields=p[6],
examples=p[7],
closed=p[2... | [
"def",
"p_union_patch",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"AstUnionPatch",
"(",
"path",
"=",
"self",
".",
"path",
",",
"lineno",
"=",
"p",
"[",
"2",
"]",
"[",
"1",
"]",
",",
"lexpos",
"=",
"p",
"[",
"2",
"]",
"[",
"2... | union_patch : PATCH uniont ID NL INDENT field_list examples DEDENT | [
"union_patch",
":",
"PATCH",
"uniont",
"ID",
"NL",
"INDENT",
"field_list",
"examples",
"DEDENT"
] | python | train |
projectatomic/atomic-reactor | atomic_reactor/util.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1116-L1148 | def get_config_and_id_from_registry(image, registry, digest, insecure=False,
dockercfg_path=None, version='v2'):
"""Return image config by digest
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
... | [
"def",
"get_config_and_id_from_registry",
"(",
"image",
",",
"registry",
",",
"digest",
",",
"insecure",
"=",
"False",
",",
"dockercfg_path",
"=",
"None",
",",
"version",
"=",
"'v2'",
")",
":",
"registry_session",
"=",
"RegistrySession",
"(",
"registry",
",",
... | Return image config by digest
:param image: ImageName, the remote image to inspect
:param registry: str, URI for registry, if URI schema is not provided,
https:// will be used
:param digest: str, digest of the image manifest
:param insecure: bool, when True registry's cert is ... | [
"Return",
"image",
"config",
"by",
"digest"
] | python | train |
rackerlabs/timid | timid/steps.py | https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/steps.py#L329-L339 | def init(self, ctxt, step_addr):
"""
Initialize the item. This calls the class constructor with the
appropriate arguments and returns the initialized object.
:param ctxt: The context object.
:param step_addr: The address of the step in the test
configu... | [
"def",
"init",
"(",
"self",
",",
"ctxt",
",",
"step_addr",
")",
":",
"return",
"self",
".",
"cls",
"(",
"ctxt",
",",
"self",
".",
"name",
",",
"self",
".",
"conf",
",",
"step_addr",
")"
] | Initialize the item. This calls the class constructor with the
appropriate arguments and returns the initialized object.
:param ctxt: The context object.
:param step_addr: The address of the step in the test
configuration. | [
"Initialize",
"the",
"item",
".",
"This",
"calls",
"the",
"class",
"constructor",
"with",
"the",
"appropriate",
"arguments",
"and",
"returns",
"the",
"initialized",
"object",
"."
] | python | test |
carpyncho/feets | feets/libs/ls_fap.py | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L169-L193 | def tau_davies(Z, fmax, t, y, dy, normalization='standard', dH=1, dK=3):
"""tau factor for estimating Davies bound (Baluev 2008, Table 1)"""
N = len(t)
NH = N - dH # DOF for null hypothesis
NK = N - dK # DOF for periodic hypothesis
Dt = _weighted_var(t, dy)
Teff = np.sqrt(4 * np.pi * Dt)
W... | [
"def",
"tau_davies",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
"=",
"'standard'",
",",
"dH",
"=",
"1",
",",
"dK",
"=",
"3",
")",
":",
"N",
"=",
"len",
"(",
"t",
")",
"NH",
"=",
"N",
"-",
"dH",
"# DOF for null... | tau factor for estimating Davies bound (Baluev 2008, Table 1) | [
"tau",
"factor",
"for",
"estimating",
"Davies",
"bound",
"(",
"Baluev",
"2008",
"Table",
"1",
")"
] | python | train |
unt-libraries/pyuntl | pyuntl/untl_structure.py | https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/untl_structure.py#L216-L295 | def create_form_data(self, **kwargs):
"""Create groupings of form elements."""
# Get the specified keyword arguments.
children = kwargs.get('children', [])
sort_order = kwargs.get('sort_order', None)
solr_response = kwargs.get('solr_response', None)
superuser = kwargs.get... | [
"def",
"create_form_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get the specified keyword arguments.",
"children",
"=",
"kwargs",
".",
"get",
"(",
"'children'",
",",
"[",
"]",
")",
"sort_order",
"=",
"kwargs",
".",
"get",
"(",
"'sort_order'",
"... | Create groupings of form elements. | [
"Create",
"groupings",
"of",
"form",
"elements",
"."
] | python | train |
hvac/hvac | hvac/api/system_backend/key.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/system_backend/key.py#L156-L213 | def start_rekey(self, secret_shares=5, secret_threshold=3, pgp_keys=None, backup=False, require_verification=False, recovery_key=False):
"""Initializes a new rekey attempt.
Only a single recovery key rekeyattempt can take place at a time, and changing the parameters of a rekey
requires cancelin... | [
"def",
"start_rekey",
"(",
"self",
",",
"secret_shares",
"=",
"5",
",",
"secret_threshold",
"=",
"3",
",",
"pgp_keys",
"=",
"None",
",",
"backup",
"=",
"False",
",",
"require_verification",
"=",
"False",
",",
"recovery_key",
"=",
"False",
")",
":",
"params... | Initializes a new rekey attempt.
Only a single recovery key rekeyattempt can take place at a time, and changing the parameters of a rekey
requires canceling and starting a new rekey, which will also provide a new nonce.
Supported methods:
PUT: /sys/rekey/init. Produces: 204 (empty ... | [
"Initializes",
"a",
"new",
"rekey",
"attempt",
"."
] | python | train |
chriskuehl/identify | identify/identify.py | https://github.com/chriskuehl/identify/blob/27ff23a3a5a08fb46e7eac79c393c1d678b4217a/identify/identify.py#L165-L173 | def parse_shebang_from_file(path):
"""Parse the shebang given a file path."""
if not os.path.lexists(path):
raise ValueError('{} does not exist.'.format(path))
if not os.access(path, os.X_OK):
return ()
with open(path, 'rb') as f:
return parse_shebang(f) | [
"def",
"parse_shebang_from_file",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"lexists",
"(",
"path",
")",
":",
"raise",
"ValueError",
"(",
"'{} does not exist.'",
".",
"format",
"(",
"path",
")",
")",
"if",
"not",
"os",
".",
"access",
... | Parse the shebang given a file path. | [
"Parse",
"the",
"shebang",
"given",
"a",
"file",
"path",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.