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 |
|---|---|---|---|---|---|---|---|---|
pycampers/zproc | zproc/state/state.py | https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/state/state.py#L253-L265 | def set(self, value: dict):
"""
Set the state, completely over-writing the previous value.
.. caution::
This kind of operation usually leads to a data race.
Please take good care while using this.
Use the :py:func:`atomic` deocrator if you're feeling anxio... | [
"def",
"set",
"(",
"self",
",",
"value",
":",
"dict",
")",
":",
"self",
".",
"_s_request_reply",
"(",
"{",
"Msgs",
".",
"cmd",
":",
"Cmds",
".",
"set_state",
",",
"Msgs",
".",
"info",
":",
"value",
"}",
")"
] | Set the state, completely over-writing the previous value.
.. caution::
This kind of operation usually leads to a data race.
Please take good care while using this.
Use the :py:func:`atomic` deocrator if you're feeling anxious. | [
"Set",
"the",
"state",
"completely",
"over",
"-",
"writing",
"the",
"previous",
"value",
"."
] | python | train |
log2timeline/dfdatetime | dfdatetime/time_elements.py | https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/time_elements.py#L119-L139 | def _CopyFromDateTimeValues(self, date_time_values):
"""Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds.
"""
year = date_time_values.get('year', 0)
... | [
"def",
"_CopyFromDateTimeValues",
"(",
"self",
",",
"date_time_values",
")",
":",
"year",
"=",
"date_time_values",
".",
"get",
"(",
"'year'",
",",
"0",
")",
"month",
"=",
"date_time_values",
".",
"get",
"(",
"'month'",
",",
"0",
")",
"day_of_month",
"=",
"... | Copies time elements from date and time values.
Args:
date_time_values (dict[str, int]): date and time values, such as year,
month, day of month, hours, minutes, seconds, microseconds. | [
"Copies",
"time",
"elements",
"from",
"date",
"and",
"time",
"values",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/exitfuncs.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/exitfuncs.py#L36-L45 | def _run_exitfuncs():
"""run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out.
"""
while _exithandlers:
func, targs, kargs = _exithandlers.pop()
func(*targs, **kargs) | [
"def",
"_run_exitfuncs",
"(",
")",
":",
"while",
"_exithandlers",
":",
"func",
",",
"targs",
",",
"kargs",
"=",
"_exithandlers",
".",
"pop",
"(",
")",
"func",
"(",
"*",
"targs",
",",
"*",
"*",
"kargs",
")"
] | run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out. | [
"run",
"any",
"registered",
"exit",
"functions"
] | python | train |
katerina7479/pypdflite | pypdflite/pdflite.py | https://github.com/katerina7479/pypdflite/blob/ac2501f30d6619eae9dea5644717575ca9263d0a/pypdflite/pdflite.py#L122-L146 | def _put_pages(self):
""" First, the Document object does the heavy-lifting for the
individual page objects and content.
Then, the overall "Pages" object is generated.
"""
self.document._get_orientation_changes()
self.document._output_pages()
... | [
"def",
"_put_pages",
"(",
"self",
")",
":",
"self",
".",
"document",
".",
"_get_orientation_changes",
"(",
")",
"self",
".",
"document",
".",
"_output_pages",
"(",
")",
"# Pages Object, provides reference to page objects (Kids list).\r",
"self",
".",
"session",
".",
... | First, the Document object does the heavy-lifting for the
individual page objects and content.
Then, the overall "Pages" object is generated. | [
"First",
"the",
"Document",
"object",
"does",
"the",
"heavy",
"-",
"lifting",
"for",
"the",
"individual",
"page",
"objects",
"and",
"content",
".",
"Then",
"the",
"overall",
"Pages",
"object",
"is",
"generated",
"."
] | python | test |
RedHatInsights/insights-core | insights/client/client.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/client.py#L108-L176 | def _legacy_handle_registration(config, pconn):
'''
Handle the registration process
Returns:
True - machine is registered
False - machine is unregistered
None - could not reach the API
'''
logger.debug('Trying registration.')
# force-reregister -- remove machine-id files ... | [
"def",
"_legacy_handle_registration",
"(",
"config",
",",
"pconn",
")",
":",
"logger",
".",
"debug",
"(",
"'Trying registration.'",
")",
"# force-reregister -- remove machine-id files and registration files",
"# before trying to register again",
"if",
"config",
".",
"reregister... | Handle the registration process
Returns:
True - machine is registered
False - machine is unregistered
None - could not reach the API | [
"Handle",
"the",
"registration",
"process",
"Returns",
":",
"True",
"-",
"machine",
"is",
"registered",
"False",
"-",
"machine",
"is",
"unregistered",
"None",
"-",
"could",
"not",
"reach",
"the",
"API"
] | python | train |
estnltk/estnltk | estnltk/syntax/maltparser_support.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/syntax/maltparser_support.py#L893-L908 | def _get_clause_words( sentence_text, clause_id ):
''' Collects clause with index *clause_id* from given *sentence_text*.
Returns a pair (clause, isEmbedded), where:
*clause* is a list of word tokens in the clause;
*isEmbedded* is a bool indicating whether the clause is embedded;
'''
... | [
"def",
"_get_clause_words",
"(",
"sentence_text",
",",
"clause_id",
")",
":",
"clause",
"=",
"[",
"]",
"isEmbedded",
"=",
"False",
"indices",
"=",
"sentence_text",
".",
"clause_indices",
"clause_anno",
"=",
"sentence_text",
".",
"clause_annotations",
"for",
"wid",... | Collects clause with index *clause_id* from given *sentence_text*.
Returns a pair (clause, isEmbedded), where:
*clause* is a list of word tokens in the clause;
*isEmbedded* is a bool indicating whether the clause is embedded; | [
"Collects",
"clause",
"with",
"index",
"*",
"clause_id",
"*",
"from",
"given",
"*",
"sentence_text",
"*",
".",
"Returns",
"a",
"pair",
"(",
"clause",
"isEmbedded",
")",
"where",
":",
"*",
"clause",
"*",
"is",
"a",
"list",
"of",
"word",
"tokens",
"in",
... | python | train |
dnanexus/dx-toolkit | src/python/dxpy/utils/__init__.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/utils/__init__.py#L159-L196 | def normalize_time_input(t, future=False, default_unit='ms'):
"""
:param default_unit: units of the input time *t*; must be one of "s" or
"ms". This param is only respected if *t* looks like an int (e.g.
"12345", 12345).
:type default_unit: string
Converts inputs such as:
"2012-0... | [
"def",
"normalize_time_input",
"(",
"t",
",",
"future",
"=",
"False",
",",
"default_unit",
"=",
"'ms'",
")",
":",
"error_msg",
"=",
"'Error: Expected an int timestamp, a date format (e.g. YYYY-MM-DD), or an int with a single-letter suffix (s=seconds, m=minutes, h=hours, d=days, w=wee... | :param default_unit: units of the input time *t*; must be one of "s" or
"ms". This param is only respected if *t* looks like an int (e.g.
"12345", 12345).
:type default_unit: string
Converts inputs such as:
"2012-05-01"
"-5d"
1352863174
"1352863174"
to millisecon... | [
":",
"param",
"default_unit",
":",
"units",
"of",
"the",
"input",
"time",
"*",
"t",
"*",
";",
"must",
"be",
"one",
"of",
"s",
"or",
"ms",
".",
"This",
"param",
"is",
"only",
"respected",
"if",
"*",
"t",
"*",
"looks",
"like",
"an",
"int",
"(",
"e"... | python | train |
apache/spark | python/pyspark/ml/classification.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/classification.py#L531-L545 | def summary(self):
"""
Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model
trained on the training set. An exception is thrown if `trainingSummary is None`.
"""
if self.hasSummary:
if self.numClasses <= 2:
return... | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"self",
".",
"hasSummary",
":",
"if",
"self",
".",
"numClasses",
"<=",
"2",
":",
"return",
"BinaryLogisticRegressionTrainingSummary",
"(",
"super",
"(",
"LogisticRegressionModel",
",",
"self",
")",
".",
"summary",... | Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model
trained on the training set. An exception is thrown if `trainingSummary is None`. | [
"Gets",
"summary",
"(",
"e",
".",
"g",
".",
"accuracy",
"/",
"precision",
"/",
"recall",
"objective",
"history",
"total",
"iterations",
")",
"of",
"model",
"trained",
"on",
"the",
"training",
"set",
".",
"An",
"exception",
"is",
"thrown",
"if",
"trainingSu... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L553-L563 | def handle_heart_failure(self, heart):
"""handler to attach to heartbeater.
called when a previously registered heart fails to respond to beat request.
triggers unregistration"""
self.log.debug("heartbeat::handle_heart_failure(%r)", heart)
eid = self.hearts.get(heart, None)
... | [
"def",
"handle_heart_failure",
"(",
"self",
",",
"heart",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"heartbeat::handle_heart_failure(%r)\"",
",",
"heart",
")",
"eid",
"=",
"self",
".",
"hearts",
".",
"get",
"(",
"heart",
",",
"None",
")",
"queue",... | handler to attach to heartbeater.
called when a previously registered heart fails to respond to beat request.
triggers unregistration | [
"handler",
"to",
"attach",
"to",
"heartbeater",
".",
"called",
"when",
"a",
"previously",
"registered",
"heart",
"fails",
"to",
"respond",
"to",
"beat",
"request",
".",
"triggers",
"unregistration"
] | python | test |
marshmallow-code/webargs | examples/schema_example.py | https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/examples/schema_example.py#L62-L80 | def use_schema(schema, list_view=False, locations=None):
"""View decorator for using a marshmallow schema to
(1) parse a request's input and
(2) serializing the view's output to a JSON response.
"""
def decorator(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
... | [
"def",
"use_schema",
"(",
"schema",
",",
"list_view",
"=",
"False",
",",
"locations",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
... | View decorator for using a marshmallow schema to
(1) parse a request's input and
(2) serializing the view's output to a JSON response. | [
"View",
"decorator",
"for",
"using",
"a",
"marshmallow",
"schema",
"to",
"(",
"1",
")",
"parse",
"a",
"request",
"s",
"input",
"and",
"(",
"2",
")",
"serializing",
"the",
"view",
"s",
"output",
"to",
"a",
"JSON",
"response",
"."
] | python | train |
gccxml/pygccxml | pygccxml/declarations/pointer_traits.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/pointer_traits.py#L116-L129 | def _search_in_bases(type_):
"""Implementation detail."""
found = False
for base_type in type_.declaration.bases:
try:
found = internal_type_traits.get_by_name(
base_type.related_class, "element_type")
except runtime_errors.declaration_not_found_t:
pas... | [
"def",
"_search_in_bases",
"(",
"type_",
")",
":",
"found",
"=",
"False",
"for",
"base_type",
"in",
"type_",
".",
"declaration",
".",
"bases",
":",
"try",
":",
"found",
"=",
"internal_type_traits",
".",
"get_by_name",
"(",
"base_type",
".",
"related_class",
... | Implementation detail. | [
"Implementation",
"detail",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/module/executor_group.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/executor_group.py#L31-L62 | def _load_general(data, targets, major_axis):
"""Load a list of arrays into a list of arrays specified by slices."""
for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
el... | [
"def",
"_load_general",
"(",
"data",
",",
"targets",
",",
"major_axis",
")",
":",
"for",
"d_src",
",",
"d_targets",
",",
"axis",
"in",
"zip",
"(",
"data",
",",
"targets",
",",
"major_axis",
")",
":",
"# pylint: disable=too-many-nested-blocks",
"if",
"isinstanc... | Load a list of arrays into a list of arrays specified by slices. | [
"Load",
"a",
"list",
"of",
"arrays",
"into",
"a",
"list",
"of",
"arrays",
"specified",
"by",
"slices",
"."
] | python | train |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/manipulate/insert.py | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/manipulate/insert.py#L50-L65 | def insert(self, table, columns, values, execute=True):
"""Insert a single row into a table."""
# TODO: Cant accept lists?
# Concatenate statement
cols, vals = get_col_val_str(columns)
statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals)
# Exe... | [
"def",
"insert",
"(",
"self",
",",
"table",
",",
"columns",
",",
"values",
",",
"execute",
"=",
"True",
")",
":",
"# TODO: Cant accept lists?",
"# Concatenate statement",
"cols",
",",
"vals",
"=",
"get_col_val_str",
"(",
"columns",
")",
"statement",
"=",
"\"IN... | Insert a single row into a table. | [
"Insert",
"a",
"single",
"row",
"into",
"a",
"table",
"."
] | python | train |
grktsh/falcon-oas | src/falcon_oas/problems.py | https://github.com/grktsh/falcon-oas/blob/380921e82a50b565b3df6e494b06cc9dba961db7/src/falcon_oas/problems.py#L52-L62 | def serialize_problem(req, resp, problem):
"""Serialize the given instance of Problem."""
preferred = req.client_prefers(
('application/json', 'application/problem+json')
)
if preferred is None:
preferred = 'application/json'
resp.data = problem.to_json().encode('utf-8')
resp.co... | [
"def",
"serialize_problem",
"(",
"req",
",",
"resp",
",",
"problem",
")",
":",
"preferred",
"=",
"req",
".",
"client_prefers",
"(",
"(",
"'application/json'",
",",
"'application/problem+json'",
")",
")",
"if",
"preferred",
"is",
"None",
":",
"preferred",
"=",
... | Serialize the given instance of Problem. | [
"Serialize",
"the",
"given",
"instance",
"of",
"Problem",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/diffusion_analyzer.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/diffusion_analyzer.py#L677-L737 | def from_files(cls, filepaths, specie, step_skip=10, ncores=None,
initial_disp=None, initial_structure=None, **kwargs):
"""
Convenient constructor that takes in a list of vasprun.xml paths to
perform diffusion analysis.
Args:
filepaths ([str]): List of pat... | [
"def",
"from_files",
"(",
"cls",
",",
"filepaths",
",",
"specie",
",",
"step_skip",
"=",
"10",
",",
"ncores",
"=",
"None",
",",
"initial_disp",
"=",
"None",
",",
"initial_structure",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ncores",
"is",... | Convenient constructor that takes in a list of vasprun.xml paths to
perform diffusion analysis.
Args:
filepaths ([str]): List of paths to vasprun.xml files of runs. (
must be ordered in sequence of MD simulation). For example,
you may have done sequential VAS... | [
"Convenient",
"constructor",
"that",
"takes",
"in",
"a",
"list",
"of",
"vasprun",
".",
"xml",
"paths",
"to",
"perform",
"diffusion",
"analysis",
"."
] | python | train |
Unidata/MetPy | metpy/calc/tools.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/tools.py#L819-L870 | def lat_lon_grid_deltas(longitude, latitude, **kwargs):
r"""Calculate the delta between grid points that are in a latitude/longitude format.
Calculate the signed delta distance between grid points when the grid spacing is defined by
delta lat/lon rather than delta x/y
Parameters
----------
lon... | [
"def",
"lat_lon_grid_deltas",
"(",
"longitude",
",",
"latitude",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pyproj",
"import",
"Geod",
"# Inputs must be the same number of dimensions",
"if",
"latitude",
".",
"ndim",
"!=",
"longitude",
".",
"ndim",
":",
"raise",
... | r"""Calculate the delta between grid points that are in a latitude/longitude format.
Calculate the signed delta distance between grid points when the grid spacing is defined by
delta lat/lon rather than delta x/y
Parameters
----------
longitude : array_like
array of longitudes defining the... | [
"r",
"Calculate",
"the",
"delta",
"between",
"grid",
"points",
"that",
"are",
"in",
"a",
"latitude",
"/",
"longitude",
"format",
"."
] | python | train |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2230-L2241 | def _handle_continue(self, node, scope, ctxt, stream):
"""Handle continue node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling continue")
raise errors.InterpContinue() | [
"def",
"_handle_continue",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_dlog",
"(",
"\"handling continue\"",
")",
"raise",
"errors",
".",
"InterpContinue",
"(",
")"
] | Handle continue node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO | [
"Handle",
"continue",
"node"
] | python | train |
secure-systems-lab/securesystemslib | securesystemslib/interface.py | https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/interface.py#L772-L817 | def import_ecdsa_publickey_from_file(filepath):
"""
<Purpose>
Load the ECDSA public key object (conformant to
'securesystemslib.formats.KEY_SCHEMA') stored in 'filepath'. Return
'filepath' in securesystemslib.formats.ECDSAKEY_SCHEMA format.
If the key object in 'filepath' contains a private key, i... | [
"def",
"import_ecdsa_publickey_from_file",
"(",
"filepath",
")",
":",
"# Does 'filepath' have the correct format?",
"# Ensure the arguments have the appropriate number of objects and object",
"# types, and that all dict keys are properly named.",
"# Raise 'securesystemslib.exceptions.FormatError' ... | <Purpose>
Load the ECDSA public key object (conformant to
'securesystemslib.formats.KEY_SCHEMA') stored in 'filepath'. Return
'filepath' in securesystemslib.formats.ECDSAKEY_SCHEMA format.
If the key object in 'filepath' contains a private key, it is discarded.
<Arguments>
filepath:
<file... | [
"<Purpose",
">",
"Load",
"the",
"ECDSA",
"public",
"key",
"object",
"(",
"conformant",
"to",
"securesystemslib",
".",
"formats",
".",
"KEY_SCHEMA",
")",
"stored",
"in",
"filepath",
".",
"Return",
"filepath",
"in",
"securesystemslib",
".",
"formats",
".",
"ECDS... | python | train |
universalcore/unicore.hub.client | unicore/hub/client/appclient.py | https://github.com/universalcore/unicore.hub.client/blob/c706f4d31e493bd4e7ea8236780a9b271b850b8b/unicore/hub/client/appclient.py#L97-L105 | def reset_key(self):
"""
Resets the app's key on the `unicore.hub` server.
:returns: str -- the new key
"""
new_key = self.client.reset_app_key(self.get('uuid'))
self.data['key'] = new_key
return new_key | [
"def",
"reset_key",
"(",
"self",
")",
":",
"new_key",
"=",
"self",
".",
"client",
".",
"reset_app_key",
"(",
"self",
".",
"get",
"(",
"'uuid'",
")",
")",
"self",
".",
"data",
"[",
"'key'",
"]",
"=",
"new_key",
"return",
"new_key"
] | Resets the app's key on the `unicore.hub` server.
:returns: str -- the new key | [
"Resets",
"the",
"app",
"s",
"key",
"on",
"the",
"unicore",
".",
"hub",
"server",
"."
] | python | train |
nickhand/classylss | classylss/__init__.py | https://github.com/nickhand/classylss/blob/b297cb25bc47ffed845470fe1c052346ea96cddd/classylss/__init__.py#L36-L58 | def load_precision(filename):
"""
Load a CLASS precision file into a dictionary.
Parameters
----------
filename : str
the name of an existing file to load, or one in the files included
as part of the CLASS source
Returns
-------
dict :
the precision parameters l... | [
"def",
"load_precision",
"(",
"filename",
")",
":",
"# also look in data dir",
"path",
"=",
"_find_file",
"(",
"filename",
")",
"r",
"=",
"dict",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"exec",
"(",
"f",
".",
"read",
"... | Load a CLASS precision file into a dictionary.
Parameters
----------
filename : str
the name of an existing file to load, or one in the files included
as part of the CLASS source
Returns
-------
dict :
the precision parameters loaded from file | [
"Load",
"a",
"CLASS",
"precision",
"file",
"into",
"a",
"dictionary",
"."
] | python | train |
rob-smallshire/cartouche | cartouche/parser.py | https://github.com/rob-smallshire/cartouche/blob/d45a8fc1fb4820bf8e741a70a8d5dafe5d26b43a/cartouche/parser.py#L283-L303 | def group_paragraphs(indent_paragraphs):
'''
Group paragraphs so that more indented paragraphs become children of less
indented paragraphs.
'''
# The tree consists of tuples of the form (indent, [children]) where the
# children may be strings or other tuples
root = Node(0, [], None)
cur... | [
"def",
"group_paragraphs",
"(",
"indent_paragraphs",
")",
":",
"# The tree consists of tuples of the form (indent, [children]) where the",
"# children may be strings or other tuples",
"root",
"=",
"Node",
"(",
"0",
",",
"[",
"]",
",",
"None",
")",
"current_node",
"=",
"root... | Group paragraphs so that more indented paragraphs become children of less
indented paragraphs. | [
"Group",
"paragraphs",
"so",
"that",
"more",
"indented",
"paragraphs",
"become",
"children",
"of",
"less",
"indented",
"paragraphs",
"."
] | python | train |
senaite/senaite.jsonapi | src/senaite/jsonapi/api.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/api.py#L250-L272 | def make_items_for(brains_or_objects, endpoint=None, complete=False):
"""Generate API compatible data items for the given list of brains/objects
:param brains_or_objects: List of objects or brains
:type brains_or_objects: list/Products.ZCatalog.Lazy.LazyMap
:param endpoint: The named URL endpoint for t... | [
"def",
"make_items_for",
"(",
"brains_or_objects",
",",
"endpoint",
"=",
"None",
",",
"complete",
"=",
"False",
")",
":",
"# check if the user wants to include children",
"include_children",
"=",
"req",
".",
"get_children",
"(",
"False",
")",
"def",
"extract_data",
... | Generate API compatible data items for the given list of brains/objects
:param brains_or_objects: List of objects or brains
:type brains_or_objects: list/Products.ZCatalog.Lazy.LazyMap
:param endpoint: The named URL endpoint for the root of the items
:type endpoint: str/unicode
:param complete: Fla... | [
"Generate",
"API",
"compatible",
"data",
"items",
"for",
"the",
"given",
"list",
"of",
"brains",
"/",
"objects"
] | python | train |
Qiskit/qiskit-terra | qiskit/dagcircuit/dagcircuit.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/dagcircuit/dagcircuit.py#L1427-L1439 | def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.topological_op_nodes():
name = node.name
if name not in op_dict:
op_dict[name] ... | [
"def",
"count_ops",
"(",
"self",
")",
":",
"op_dict",
"=",
"{",
"}",
"for",
"node",
"in",
"self",
".",
"topological_op_nodes",
"(",
")",
":",
"name",
"=",
"node",
".",
"name",
"if",
"name",
"not",
"in",
"op_dict",
":",
"op_dict",
"[",
"name",
"]",
... | Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name. | [
"Count",
"the",
"occurrences",
"of",
"operation",
"names",
"."
] | python | test |
saltstack/salt | salt/netapi/rest_cherrypy/app.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1368-L1432 | def POST(self, **kwargs):
'''
Start an execution command and immediately return the job id
.. http:post:: /minions
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |r... | [
"def",
"POST",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"job_data",
"=",
"list",
"(",
"self",
".",
"exec_lowstate",
"(",
"client",
"=",
"'local_async'",
",",
"token",
"=",
"cherrypy",
".",
"session",
".",
"get",
"(",
"'token'",
")",
")",
")",
... | Start an execution command and immediately return the job id
.. http:post:: /minions
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:resheader Content-Type: |res_ct|
:status 200: |200|
... | [
"Start",
"an",
"execution",
"command",
"and",
"immediately",
"return",
"the",
"job",
"id"
] | python | train |
aws/sagemaker-python-sdk | src/sagemaker/estimator.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/estimator.py#L464-L471 | def delete_endpoint(self):
"""Delete an Amazon SageMaker ``Endpoint``.
Raises:
ValueError: If the endpoint does not exist.
"""
self._ensure_latest_training_job(error_message='Endpoint was not created yet')
self.sagemaker_session.delete_endpoint(self.latest_training_j... | [
"def",
"delete_endpoint",
"(",
"self",
")",
":",
"self",
".",
"_ensure_latest_training_job",
"(",
"error_message",
"=",
"'Endpoint was not created yet'",
")",
"self",
".",
"sagemaker_session",
".",
"delete_endpoint",
"(",
"self",
".",
"latest_training_job",
".",
"name... | Delete an Amazon SageMaker ``Endpoint``.
Raises:
ValueError: If the endpoint does not exist. | [
"Delete",
"an",
"Amazon",
"SageMaker",
"Endpoint",
"."
] | python | train |
openego/eDisGo | edisgo/flex_opt/reinforce_measures.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/flex_opt/reinforce_measures.py#L477-L557 | def reinforce_branches_overloading(network, crit_lines):
"""
Reinforce MV or LV grid due to overloading.
Parameters
----------
network : :class:`~.grid.network.Network`
crit_lines : :pandas:`pandas.DataFrame<dataframe>`
Dataframe containing over-loaded lines, their maximum relative
... | [
"def",
"reinforce_branches_overloading",
"(",
"network",
",",
"crit_lines",
")",
":",
"# load standard line data",
"try",
":",
"standard_line_lv",
"=",
"network",
".",
"equipment_data",
"[",
"'lv_cables'",
"]",
".",
"loc",
"[",
"network",
".",
"config",
"[",
"'gri... | Reinforce MV or LV grid due to overloading.
Parameters
----------
network : :class:`~.grid.network.Network`
crit_lines : :pandas:`pandas.DataFrame<dataframe>`
Dataframe containing over-loaded lines, their maximum relative
over-loading and the corresponding time step.
Index o... | [
"Reinforce",
"MV",
"or",
"LV",
"grid",
"due",
"to",
"overloading",
".",
"Parameters",
"----------",
"network",
":",
":",
"class",
":",
"~",
".",
"grid",
".",
"network",
".",
"Network",
"crit_lines",
":",
":",
"pandas",
":",
"pandas",
".",
"DataFrame<datafr... | python | train |
KelSolaar/Foundations | foundations/decorators.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/decorators.py#L80-L129 | def memoize(cache=None):
"""
| Implements method / definition memoization.
| Any method / definition decorated will get its return value cached and restored whenever called with the same arguments.
:param cache: Alternate cache.
:type cache: dict
:return: Object.
:rtype: object
"""
... | [
"def",
"memoize",
"(",
"cache",
"=",
"None",
")",
":",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"{",
"}",
"def",
"memoize_decorator",
"(",
"object",
")",
":",
"\"\"\"\n Implements method / definition memoization.\n\n :param object: Object to decorat... | | Implements method / definition memoization.
| Any method / definition decorated will get its return value cached and restored whenever called with the same arguments.
:param cache: Alternate cache.
:type cache: dict
:return: Object.
:rtype: object | [
"|",
"Implements",
"method",
"/",
"definition",
"memoization",
".",
"|",
"Any",
"method",
"/",
"definition",
"decorated",
"will",
"get",
"its",
"return",
"value",
"cached",
"and",
"restored",
"whenever",
"called",
"with",
"the",
"same",
"arguments",
"."
] | python | train |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/utils.py | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/utils.py#L124-L152 | def expected_eye_positions(bounding_box, padding = None):
"""expected_eye_positions(bounding_box, padding) -> eyes
Computes the expected eye positions based on the relative coordinates of the bounding box.
This function can be used to translate between bounding-box-based image cropping and eye-location-based al... | [
"def",
"expected_eye_positions",
"(",
"bounding_box",
",",
"padding",
"=",
"None",
")",
":",
"if",
"padding",
"is",
"None",
":",
"padding",
"=",
"default_paddings",
"[",
"'eyes'",
"]",
"top",
",",
"left",
",",
"right",
"=",
"padding",
"[",
"'top'",
"]",
... | expected_eye_positions(bounding_box, padding) -> eyes
Computes the expected eye positions based on the relative coordinates of the bounding box.
This function can be used to translate between bounding-box-based image cropping and eye-location-based alignment.
The returned eye locations return the **average** ey... | [
"expected_eye_positions",
"(",
"bounding_box",
"padding",
")",
"-",
">",
"eyes"
] | python | train |
spyder-ide/spyder | spyder/config/gui.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/gui.py#L116-L127 | def config_shortcut(action, context, name, parent):
"""
Create a Shortcut namedtuple for a widget
The data contained in this tuple will be registered in
our shortcuts preferences page
"""
keystr = get_shortcut(context, name)
qsc = QShortcut(QKeySequence(keystr), parent, action)
qsc.... | [
"def",
"config_shortcut",
"(",
"action",
",",
"context",
",",
"name",
",",
"parent",
")",
":",
"keystr",
"=",
"get_shortcut",
"(",
"context",
",",
"name",
")",
"qsc",
"=",
"QShortcut",
"(",
"QKeySequence",
"(",
"keystr",
")",
",",
"parent",
",",
"action"... | Create a Shortcut namedtuple for a widget
The data contained in this tuple will be registered in
our shortcuts preferences page | [
"Create",
"a",
"Shortcut",
"namedtuple",
"for",
"a",
"widget",
"The",
"data",
"contained",
"in",
"this",
"tuple",
"will",
"be",
"registered",
"in",
"our",
"shortcuts",
"preferences",
"page"
] | python | train |
zetaops/pyoko | pyoko/model.py | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/model.py#L121-L126 | def prnt(self):
"""
Prints DB data representation of the object.
"""
print("= = = =\n\n%s object key: \033[32m%s\033[0m" % (self.__class__.__name__, self.key))
pprnt(self._data or self.clean_value()) | [
"def",
"prnt",
"(",
"self",
")",
":",
"print",
"(",
"\"= = = =\\n\\n%s object key: \\033[32m%s\\033[0m\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"key",
")",
")",
"pprnt",
"(",
"self",
".",
"_data",
"or",
"self",
".",
"clean... | Prints DB data representation of the object. | [
"Prints",
"DB",
"data",
"representation",
"of",
"the",
"object",
"."
] | python | train |
CivicSpleen/ambry | ambry/library/search_backends/whoosh_backend.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L231-L237 | def _get_generic_schema(self):
""" Returns whoosh's generic schema. """
schema = Schema(
identifier=ID(stored=True), # Partition versioned id
type=ID(stored=True),
name=NGRAM(phrase=True, stored=True, minsize=2, maxsize=8))
return schema | [
"def",
"_get_generic_schema",
"(",
"self",
")",
":",
"schema",
"=",
"Schema",
"(",
"identifier",
"=",
"ID",
"(",
"stored",
"=",
"True",
")",
",",
"# Partition versioned id",
"type",
"=",
"ID",
"(",
"stored",
"=",
"True",
")",
",",
"name",
"=",
"NGRAM",
... | Returns whoosh's generic schema. | [
"Returns",
"whoosh",
"s",
"generic",
"schema",
"."
] | python | train |
PyHDI/Pyverilog | pyverilog/vparser/parser.py | https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L830-L833 | def p_lpartselect_lpointer_minus(self, p):
'lpartselect : pointer LBRACKET expression MINUSCOLON expression RBRACKET'
p[0] = Partselect(p[1], p[3], Minus(p[3], p[5]), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_lpartselect_lpointer_minus",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Partselect",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"Minus",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
")",
",",
"line... | lpartselect : pointer LBRACKET expression MINUSCOLON expression RBRACKET | [
"lpartselect",
":",
"pointer",
"LBRACKET",
"expression",
"MINUSCOLON",
"expression",
"RBRACKET"
] | python | train |
pandas-dev/pandas | pandas/core/series.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/series.py#L2912-L3065 | def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
kind='quicksort', na_position='last', sort_remaining=True):
"""
Sort Series by index labels.
Returns a new Series sorted by label if `inplace` argument is
``False``, otherwise updates the original... | [
"def",
"sort_index",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"level",
"=",
"None",
",",
"ascending",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"kind",
"=",
"'quicksort'",
",",
"na_position",
"=",
"'last'",
",",
"sort_remaining",
"=",
"True",
")"... | Sort Series by index labels.
Returns a new Series sorted by label if `inplace` argument is
``False``, otherwise updates the original series and returns None.
Parameters
----------
axis : int, default 0
Axis to direct sorting. This can only be 0 for Series.
l... | [
"Sort",
"Series",
"by",
"index",
"labels",
"."
] | python | train |
awslabs/sockeye | sockeye/translate.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/translate.py#L203-L245 | def read_and_translate(translator: inference.Translator,
output_handler: OutputHandler,
chunk_size: Optional[int],
input_file: Optional[str] = None,
input_factors: Optional[List[str]] = None,
input_is_json... | [
"def",
"read_and_translate",
"(",
"translator",
":",
"inference",
".",
"Translator",
",",
"output_handler",
":",
"OutputHandler",
",",
"chunk_size",
":",
"Optional",
"[",
"int",
"]",
",",
"input_file",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"inp... | Reads from either a file or stdin and translates each line, calling the output_handler with the result.
:param output_handler: Handler that will write output to a stream.
:param translator: Translator that will translate each line of input.
:param chunk_size: The size of the portion to read at a time from ... | [
"Reads",
"from",
"either",
"a",
"file",
"or",
"stdin",
"and",
"translates",
"each",
"line",
"calling",
"the",
"output_handler",
"with",
"the",
"result",
"."
] | python | train |
openid/python-openid | openid/extensions/ax.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/ax.py#L458-L480 | def _getExtensionKVArgs(self, aliases=None):
"""Get the extension arguments for the key/value pairs
contained in this message.
@param aliases: An alias mapping. Set to None if you don't
care about the aliases for this request.
"""
if aliases is None:
alia... | [
"def",
"_getExtensionKVArgs",
"(",
"self",
",",
"aliases",
"=",
"None",
")",
":",
"if",
"aliases",
"is",
"None",
":",
"aliases",
"=",
"NamespaceMap",
"(",
")",
"ax_args",
"=",
"{",
"}",
"for",
"type_uri",
",",
"values",
"in",
"self",
".",
"data",
".",
... | Get the extension arguments for the key/value pairs
contained in this message.
@param aliases: An alias mapping. Set to None if you don't
care about the aliases for this request. | [
"Get",
"the",
"extension",
"arguments",
"for",
"the",
"key",
"/",
"value",
"pairs",
"contained",
"in",
"this",
"message",
"."
] | python | train |
belbio/bel | bel/lang/bel_specification.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/bel_specification.py#L545-L589 | def get_ebnf_template():
"""Get EBNF template from Github belbio/bel_specifications repo"""
spec_dir = config["bel"]["lang"]["specifications"]
local_fp = f"{spec_dir}/bel.ebnf.j2"
repo_url = (
"https://api.github.com/repos/belbio/bel_specifications/contents/resources/bel.ebnf.j2"
)
pa... | [
"def",
"get_ebnf_template",
"(",
")",
":",
"spec_dir",
"=",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"lang\"",
"]",
"[",
"\"specifications\"",
"]",
"local_fp",
"=",
"f\"{spec_dir}/bel.ebnf.j2\"",
"repo_url",
"=",
"(",
"\"https://api.github.com/repos/belbio/bel_specificatio... | Get EBNF template from Github belbio/bel_specifications repo | [
"Get",
"EBNF",
"template",
"from",
"Github",
"belbio",
"/",
"bel_specifications",
"repo"
] | python | train |
etcher-be/epab | epab/cmd/_chglog.py | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_chglog.py#L69-L96 | def _chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
"""
Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes
"""
if config.CHANGELOG_DISABLE():
LOGGER.info('skipping changelog upda... | [
"def",
"_chglog",
"(",
"amend",
":",
"bool",
"=",
"False",
",",
"stage",
":",
"bool",
"=",
"False",
",",
"next_version",
":",
"str",
"=",
"None",
",",
"auto_next_version",
":",
"bool",
"=",
"False",
")",
":",
"if",
"config",
".",
"CHANGELOG_DISABLE",
"... | Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes | [
"Writes",
"the",
"changelog"
] | python | train |
portantier/habu | habu/lib/vhosts.py | https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/vhosts.py#L17-L43 | def get_vhosts(ip, first=1, no_cache=False):
"""Returns a list of webs hosted on IP (checks bing.com)
>>> 'www.bing.com' in vhosts(204.79.197.200)
True
"""
if not no_cache:
homedir = pwd.getpwuid(os.getuid()).pw_dir
requests_cache.install_cache(homedir + '/.habu_requests_cache')
... | [
"def",
"get_vhosts",
"(",
"ip",
",",
"first",
"=",
"1",
",",
"no_cache",
"=",
"False",
")",
":",
"if",
"not",
"no_cache",
":",
"homedir",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
".",
"pw_dir",
"requests_cache",
".",
"i... | Returns a list of webs hosted on IP (checks bing.com)
>>> 'www.bing.com' in vhosts(204.79.197.200)
True | [
"Returns",
"a",
"list",
"of",
"webs",
"hosted",
"on",
"IP",
"(",
"checks",
"bing",
".",
"com",
")",
">>>",
"www",
".",
"bing",
".",
"com",
"in",
"vhosts",
"(",
"204",
".",
"79",
".",
"197",
".",
"200",
")",
"True"
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_mps_utils.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_mps_utils.py#L515-L541 | def train_return_grad(self, input, grad):
"""
Performs a forward pass from the input batch, followed by a backward
pass using the provided gradient (in place of a loss function). Returns
a MpsFloatArray representing the output (final gradient) of the backward
pass. Calling asnump... | [
"def",
"train_return_grad",
"(",
"self",
",",
"input",
",",
"grad",
")",
":",
"assert",
"self",
".",
"_mode",
"==",
"MpsGraphMode",
".",
"TrainReturnGrad",
"assert",
"input",
".",
"shape",
"==",
"self",
".",
"_ishape",
"assert",
"grad",
".",
"shape",
"==",... | Performs a forward pass from the input batch, followed by a backward
pass using the provided gradient (in place of a loss function). Returns
a MpsFloatArray representing the output (final gradient) of the backward
pass. Calling asnumpy() on this value will wait for the batch to finish
an... | [
"Performs",
"a",
"forward",
"pass",
"from",
"the",
"input",
"batch",
"followed",
"by",
"a",
"backward",
"pass",
"using",
"the",
"provided",
"gradient",
"(",
"in",
"place",
"of",
"a",
"loss",
"function",
")",
".",
"Returns",
"a",
"MpsFloatArray",
"representin... | python | train |
ellmetha/neojsonrpc | neojsonrpc/client.py | https://github.com/ellmetha/neojsonrpc/blob/e369b633a727482d5f9e310f0c3337ae5f7265db/neojsonrpc/client.py#L146-L155 | def get_block_sys_fee(self, block_index, **kwargs):
""" Returns the system fees associated with a specific block index.
:param block_index: a block index (block height)
:type block_index: int
:return: system fees of the block, expressed in NeoGas units
:rtype: str
"""
... | [
"def",
"get_block_sys_fee",
"(",
"self",
",",
"block_index",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_call",
"(",
"JSONRPCMethods",
".",
"GET_BLOCK_SYS_FEE",
".",
"value",
",",
"[",
"block_index",
",",
"]",
",",
"*",
"*",
"kwargs",
")"... | Returns the system fees associated with a specific block index.
:param block_index: a block index (block height)
:type block_index: int
:return: system fees of the block, expressed in NeoGas units
:rtype: str | [
"Returns",
"the",
"system",
"fees",
"associated",
"with",
"a",
"specific",
"block",
"index",
"."
] | python | test |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SSPILScreen.py | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SSPILScreen.py#L88-L110 | def _initBuffer(self, bufferColorMode, bufferSize):
"""!
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param buffe... | [
"def",
"_initBuffer",
"(",
"self",
",",
"bufferColorMode",
",",
"bufferSize",
")",
":",
"# super(SSScreenBase)._initBuffer(bufferColorMode, bufferSize)",
"self",
".",
"_buffer_color_mode",
"=",
"bufferColorMode",
"#create screen image buffer and canvas",
"if",
"bufferSize",
"==... | !
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param bufferColorMode: 色彩模式, 取值: "RGB" 或 "1"
@param bufferSize: 缓存... | [
"!",
"\\",
"~english",
"Initialize",
"the",
"buffer",
"object",
"instance",
"use",
"PIL",
"Image",
"as",
"for",
"buffer"
] | python | train |
myyang/django-unixtimestampfield | unixtimestampfield/fields.py | https://github.com/myyang/django-unixtimestampfield/blob/d647681cd628d1a5cdde8dcbb025bcb9612e9b24/unixtimestampfield/fields.py#L329-L345 | def to_naive_datetime(self, value):
"""
from value to datetime with tzinfo format (datetime.datetime instance)
"""
if isinstance(value, (six.integer_types, float, six.string_types)):
try:
return self.from_number(value)
except ValueError:
... | [
"def",
"to_naive_datetime",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"six",
".",
"integer_types",
",",
"float",
",",
"six",
".",
"string_types",
")",
")",
":",
"try",
":",
"return",
"self",
".",
"from_number",
"(... | from value to datetime with tzinfo format (datetime.datetime instance) | [
"from",
"value",
"to",
"datetime",
"with",
"tzinfo",
"format",
"(",
"datetime",
".",
"datetime",
"instance",
")"
] | python | train |
SheffieldML/GPy | GPy/util/mocap.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/mocap.py#L32-L42 | def find_children(self):
"""Take a tree and set the children according to the parents.
Takes a tree structure which lists the parents of each vertex
and computes the children for each vertex and places them in."""
for i in range(len(self.vertices)):
self.vertices[i].children... | [
"def",
"find_children",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"vertices",
")",
")",
":",
"self",
".",
"vertices",
"[",
"i",
"]",
".",
"children",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(... | Take a tree and set the children according to the parents.
Takes a tree structure which lists the parents of each vertex
and computes the children for each vertex and places them in. | [
"Take",
"a",
"tree",
"and",
"set",
"the",
"children",
"according",
"to",
"the",
"parents",
"."
] | python | train |
lvh/maxims | maxims/named.py | https://github.com/lvh/maxims/blob/5c53b25d2cc4ccecbfe90193ade9ce0dbfbe4623/maxims/named.py#L44-L67 | def forget(empowered, powerupClass, interface):
"""
Forgets powerups previously stored with ``remember``.
:param empowered: The Empowered (Store or Item) to be powered down.
:type empowered: ``axiom.item.Empowered``
:param powerupClass: The class for which powerups will be forgotten.
:type powe... | [
"def",
"forget",
"(",
"empowered",
",",
"powerupClass",
",",
"interface",
")",
":",
"className",
"=",
"fullyQualifiedName",
"(",
"powerupClass",
")",
"withThisName",
"=",
"_StoredByName",
".",
"className",
"==",
"className",
"items",
"=",
"empowered",
".",
"stor... | Forgets powerups previously stored with ``remember``.
:param empowered: The Empowered (Store or Item) to be powered down.
:type empowered: ``axiom.item.Empowered``
:param powerupClass: The class for which powerups will be forgotten.
:type powerupClass: class
:param interface: The interface the powe... | [
"Forgets",
"powerups",
"previously",
"stored",
"with",
"remember",
"."
] | python | train |
gwpy/gwpy | gwpy/segments/io/hdf5.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/io/hdf5.py#L304-L336 | def write_hdf5_segmentlist(seglist, output, path=None, **kwargs):
"""Write a `SegmentList` to an HDF5 file/group
Parameters
----------
seglist : :class:`~ligo.segments.segmentlist`
data to write
output : `str`, `h5py.File`, `h5py.Group`
filename or HDF5 object to write to
path... | [
"def",
"write_hdf5_segmentlist",
"(",
"seglist",
",",
"output",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Please specify the HDF5 path via the \"",
"\"``path=`` keyword argument\"",
... | Write a `SegmentList` to an HDF5 file/group
Parameters
----------
seglist : :class:`~ligo.segments.segmentlist`
data to write
output : `str`, `h5py.File`, `h5py.Group`
filename or HDF5 object to write to
path : `str`
path to which to write inside the HDF5 file, relative to... | [
"Write",
"a",
"SegmentList",
"to",
"an",
"HDF5",
"file",
"/",
"group"
] | python | train |
fboender/ansible-cmdb | src/ansible-cmdb.py | https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/src/ansible-cmdb.py#L34-L45 | def get_logger():
"""
Instantiate a logger.
"""
root = logging.getLogger()
root.setLevel(logging.WARNING)
ch = logging.StreamHandler(sys.stderr)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
return root | [
"def",
"get_logger",
"(",
")",
":",
"root",
"=",
"logging",
".",
"getLogger",
"(",
")",
"root",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"ch",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stderr",
")",
"ch",
".",
"setLevel",
"... | Instantiate a logger. | [
"Instantiate",
"a",
"logger",
"."
] | python | train |
aiortc/aioice | aioice/ice.py | https://github.com/aiortc/aioice/blob/a04d810d94ec2d00eca9ce01eacca74b3b086616/aioice/ice.py#L468-L490 | def set_selected_pair(self, component, local_foundation, remote_foundation):
"""
Force the selected candidate pair.
If the remote party does not support ICE, you should using this
instead of calling :meth:`connect`.
"""
# find local candidate
protocol = None
... | [
"def",
"set_selected_pair",
"(",
"self",
",",
"component",
",",
"local_foundation",
",",
"remote_foundation",
")",
":",
"# find local candidate",
"protocol",
"=",
"None",
"for",
"p",
"in",
"self",
".",
"_protocols",
":",
"if",
"(",
"p",
".",
"local_candidate",
... | Force the selected candidate pair.
If the remote party does not support ICE, you should using this
instead of calling :meth:`connect`. | [
"Force",
"the",
"selected",
"candidate",
"pair",
"."
] | python | train |
sorgerlab/indra | indra/sources/trrust/processor.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trrust/processor.py#L20-L34 | def extract_statements(self):
"""Process the table to extract Statements."""
for _, (tf, target, effect, refs) in self.df.iterrows():
tf_agent = get_grounded_agent(tf)
target_agent = get_grounded_agent(target)
if effect == 'Activation':
stmt_cls = Incr... | [
"def",
"extract_statements",
"(",
"self",
")",
":",
"for",
"_",
",",
"(",
"tf",
",",
"target",
",",
"effect",
",",
"refs",
")",
"in",
"self",
".",
"df",
".",
"iterrows",
"(",
")",
":",
"tf_agent",
"=",
"get_grounded_agent",
"(",
"tf",
")",
"target_ag... | Process the table to extract Statements. | [
"Process",
"the",
"table",
"to",
"extract",
"Statements",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/core/structure.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L2173-L2187 | def from_dict(cls, d):
"""
Reconstitute a Molecule object from a dict representation created using
as_dict().
Args:
d (dict): dict representation of Molecule.
Returns:
Molecule object
"""
sites = [Site.from_dict(sd) for sd in d["sites"]]
... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"sites",
"=",
"[",
"Site",
".",
"from_dict",
"(",
"sd",
")",
"for",
"sd",
"in",
"d",
"[",
"\"sites\"",
"]",
"]",
"charge",
"=",
"d",
".",
"get",
"(",
"\"charge\"",
",",
"0",
")",
"spin_multiplic... | Reconstitute a Molecule object from a dict representation created using
as_dict().
Args:
d (dict): dict representation of Molecule.
Returns:
Molecule object | [
"Reconstitute",
"a",
"Molecule",
"object",
"from",
"a",
"dict",
"representation",
"created",
"using",
"as_dict",
"()",
"."
] | python | train |
pyroscope/pyrocore | src/pyrocore/scripts/rtcontrol.py | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/rtcontrol.py#L83-L93 | def add(self, field, val):
"Add a sample"
if engine.FieldDefinition.FIELDS[field]._matcher is matching.TimeFilter:
val = self._basetime - val
try:
self.total[field] += val
self.min[field] = min(self.min[field], val) if field in self.min else val
s... | [
"def",
"add",
"(",
"self",
",",
"field",
",",
"val",
")",
":",
"if",
"engine",
".",
"FieldDefinition",
".",
"FIELDS",
"[",
"field",
"]",
".",
"_matcher",
"is",
"matching",
".",
"TimeFilter",
":",
"val",
"=",
"self",
".",
"_basetime",
"-",
"val",
"try... | Add a sample | [
"Add",
"a",
"sample"
] | python | train |
Duke-GCB/DukeDSClient | ddsc/cmdparser.py | https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/cmdparser.py#L345-L357 | def register_upload_command(self, upload_func):
"""
Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks).
"""
... | [
"def",
"register_upload_command",
"(",
"self",
",",
"upload_func",
")",
":",
"description",
"=",
"\"Uploads local files and folders to a remote host.\"",
"upload_parser",
"=",
"self",
".",
"subparsers",
".",
"add_parser",
"(",
"'upload'",
",",
"description",
"=",
"descr... | Add the upload command to the parser and call upload_func(project_name, folders, follow_symlinks) when chosen.
:param upload_func: func Called when this option is chosen: upload_func(project_name, folders, follow_symlinks). | [
"Add",
"the",
"upload",
"command",
"to",
"the",
"parser",
"and",
"call",
"upload_func",
"(",
"project_name",
"folders",
"follow_symlinks",
")",
"when",
"chosen",
".",
":",
"param",
"upload_func",
":",
"func",
"Called",
"when",
"this",
"option",
"is",
"chosen",... | python | train |
PGower/petl_django | petl_django/django_view.py | https://github.com/PGower/petl_django/blob/463144eeb38ca2da30644f53c247bfbc15702bb2/petl_django/django_view.py#L67-L124 | def todjango(table, model, update=True, create=True, use_bulk_create=True, *args, **kwargs):
'''
Given a table with appropriate headings create Django models.
'''
assert issubclass(model, Model), 'Must be supplied a valid Django model class'
table_iterator = iter(table)
table_headers = tab... | [
"def",
"todjango",
"(",
"table",
",",
"model",
",",
"update",
"=",
"True",
",",
"create",
"=",
"True",
",",
"use_bulk_create",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"issubclass",
"(",
"model",
",",
"Model",
")",
... | Given a table with appropriate headings create Django models. | [
"Given",
"a",
"table",
"with",
"appropriate",
"headings",
"create",
"Django",
"models",
"."
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/licensing/licensing_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/licensing/licensing_client.py#L337-L348 | def register_extension_license(self, extension_license_data):
"""RegisterExtensionLicense.
[Preview API]
:param :class:`<ExtensionLicenseData> <azure.devops.v5_0.licensing.models.ExtensionLicenseData>` extension_license_data:
:rtype: bool
"""
content = self._serialize.bod... | [
"def",
"register_extension_license",
"(",
"self",
",",
"extension_license_data",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"extension_license_data",
",",
"'ExtensionLicenseData'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_... | RegisterExtensionLicense.
[Preview API]
:param :class:`<ExtensionLicenseData> <azure.devops.v5_0.licensing.models.ExtensionLicenseData>` extension_license_data:
:rtype: bool | [
"RegisterExtensionLicense",
".",
"[",
"Preview",
"API",
"]",
":",
"param",
":",
"class",
":",
"<ExtensionLicenseData",
">",
"<azure",
".",
"devops",
".",
"v5_0",
".",
"licensing",
".",
"models",
".",
"ExtensionLicenseData",
">",
"extension_license_data",
":",
":... | python | train |
pyviz/param | param/__init__.py | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/__init__.py#L576-L590 | def _initialize_generator(self,gen,obj=None):
"""
Add 'last time' and 'last value' attributes to the generator.
"""
# CEBALERT: use a dictionary to hold these things.
if hasattr(obj,"_Dynamic_time_fn"):
gen._Dynamic_time_fn = obj._Dynamic_time_fn
gen._Dynamic... | [
"def",
"_initialize_generator",
"(",
"self",
",",
"gen",
",",
"obj",
"=",
"None",
")",
":",
"# CEBALERT: use a dictionary to hold these things.",
"if",
"hasattr",
"(",
"obj",
",",
"\"_Dynamic_time_fn\"",
")",
":",
"gen",
".",
"_Dynamic_time_fn",
"=",
"obj",
".",
... | Add 'last time' and 'last value' attributes to the generator. | [
"Add",
"last",
"time",
"and",
"last",
"value",
"attributes",
"to",
"the",
"generator",
"."
] | python | train |
dmlc/gluon-nlp | src/gluonnlp/embedding/token_embedding.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L323-L380 | def _load_embedding_serialized(self, pretrained_file_path):
"""Load embedding vectors from a pre-trained token embedding file.
For every unknown token, if its representation `self.unknown_token` is encountered in the
pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre... | [
"def",
"_load_embedding_serialized",
"(",
"self",
",",
"pretrained_file_path",
")",
":",
"deserialized_embedding",
"=",
"TokenEmbedding",
".",
"deserialize",
"(",
"pretrained_file_path",
")",
"if",
"deserialized_embedding",
".",
"unknown_token",
":",
"# Some .npz files on S... | Load embedding vectors from a pre-trained token embedding file.
For every unknown token, if its representation `self.unknown_token` is encountered in the
pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token
embedding vector loaded from the file; otherwise... | [
"Load",
"embedding",
"vectors",
"from",
"a",
"pre",
"-",
"trained",
"token",
"embedding",
"file",
"."
] | python | train |
openpermissions/perch | perch/validators.py | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/validators.py#L83-L109 | def validate_url(url):
"""Validate URL is valid
NOTE: only support http & https
"""
schemes = ['http', 'https']
netloc_re = re.compile(
r'^'
r'(?:\S+(?::\S*)?@)?' # user:pass auth
r'(?:[a-z0-9]|[a-z0-9][a-z0-9\-]{0,61}[a-z0-9])'
r'(?:\.(?:[a-z0-9]|[a-z0-9][a-z0-9\-]... | [
"def",
"validate_url",
"(",
"url",
")",
":",
"schemes",
"=",
"[",
"'http'",
",",
"'https'",
"]",
"netloc_re",
"=",
"re",
".",
"compile",
"(",
"r'^'",
"r'(?:\\S+(?::\\S*)?@)?'",
"# user:pass auth",
"r'(?:[a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])'",
"r'(?:\\.(?:[a-z0-9]... | Validate URL is valid
NOTE: only support http & https | [
"Validate",
"URL",
"is",
"valid"
] | python | train |
phoebe-project/phoebe2 | phoebe/atmospheres/passbands.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/atmospheres/passbands.py#L340-L357 | def _planck_spi(self, lam, Teff):
"""
Computes the spectral index of the monochromatic blackbody intensity
using the Planck function. The spectral index is defined as:
B(lambda) = 5 + d(log I)/d(log lambda),
where I is the Planck function.
@lam: wavelength in m
... | [
"def",
"_planck_spi",
"(",
"self",
",",
"lam",
",",
"Teff",
")",
":",
"hclkt",
"=",
"self",
".",
"h",
"*",
"self",
".",
"c",
"/",
"lam",
"/",
"self",
".",
"k",
"/",
"Teff",
"expterm",
"=",
"np",
".",
"exp",
"(",
"hclkt",
")",
"return",
"hclkt",... | Computes the spectral index of the monochromatic blackbody intensity
using the Planck function. The spectral index is defined as:
B(lambda) = 5 + d(log I)/d(log lambda),
where I is the Planck function.
@lam: wavelength in m
@Teff: effective temperature in K
Return... | [
"Computes",
"the",
"spectral",
"index",
"of",
"the",
"monochromatic",
"blackbody",
"intensity",
"using",
"the",
"Planck",
"function",
".",
"The",
"spectral",
"index",
"is",
"defined",
"as",
":"
] | python | train |
alan-turing-institute/topic-modelling-tools | topicmodels/multimix/inference.py | https://github.com/alan-turing-institute/topic-modelling-tools/blob/f0cf90cdd06f1072e824b446f201c7469b9de5df/topicmodels/multimix/inference.py#L80-L109 | def estimate(self, maxiter=250, convergence=1e-7):
"""
run EM algorithm until convergence, or until maxiter reached
"""
self.loglik = np.zeros(maxiter)
iter = 0
while iter < maxiter:
self.loglik[iter] = self.E_step()
if np.isnan(self.loglik[it... | [
"def",
"estimate",
"(",
"self",
",",
"maxiter",
"=",
"250",
",",
"convergence",
"=",
"1e-7",
")",
":",
"self",
".",
"loglik",
"=",
"np",
".",
"zeros",
"(",
"maxiter",
")",
"iter",
"=",
"0",
"while",
"iter",
"<",
"maxiter",
":",
"self",
".",
"loglik... | run EM algorithm until convergence, or until maxiter reached | [
"run",
"EM",
"algorithm",
"until",
"convergence",
"or",
"until",
"maxiter",
"reached"
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/win32/context_i386.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/win32/context_i386.py#L244-L269 | def from_dict(cls, ctx):
'Instance a new structure from a Python dictionary.'
ctx = Context(ctx)
s = cls()
ContextFlags = ctx['ContextFlags']
setattr(s, 'ContextFlags', ContextFlags)
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for k... | [
"def",
"from_dict",
"(",
"cls",
",",
"ctx",
")",
":",
"ctx",
"=",
"Context",
"(",
"ctx",
")",
"s",
"=",
"cls",
"(",
")",
"ContextFlags",
"=",
"ctx",
"[",
"'ContextFlags'",
"]",
"setattr",
"(",
"s",
",",
"'ContextFlags'",
",",
"ContextFlags",
")",
"if... | Instance a new structure from a Python dictionary. | [
"Instance",
"a",
"new",
"structure",
"from",
"a",
"Python",
"dictionary",
"."
] | python | train |
ralphbean/taskw | taskw/warrior.py | https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L289-L298 | def task_done(self, **kw):
"""
Marks a pending task as done, optionally specifying a completion
date with the 'end' argument.
"""
def validate(task):
if not Status.is_pending(task['status']):
raise ValueError("Task is not pending.")
return sel... | [
"def",
"task_done",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"def",
"validate",
"(",
"task",
")",
":",
"if",
"not",
"Status",
".",
"is_pending",
"(",
"task",
"[",
"'status'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Task is not pending.\"",
")"... | Marks a pending task as done, optionally specifying a completion
date with the 'end' argument. | [
"Marks",
"a",
"pending",
"task",
"as",
"done",
"optionally",
"specifying",
"a",
"completion",
"date",
"with",
"the",
"end",
"argument",
"."
] | python | train |
pandas-dev/pandas | pandas/core/indexing.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L2573-L2582 | def convert_from_missing_indexer_tuple(indexer, axes):
"""
create a filtered indexer that doesn't have any missing indexers
"""
def get_indexer(_i, _idx):
return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else
_idx)
return tuple(get_indexer(_i, _idx) for _i, _... | [
"def",
"convert_from_missing_indexer_tuple",
"(",
"indexer",
",",
"axes",
")",
":",
"def",
"get_indexer",
"(",
"_i",
",",
"_idx",
")",
":",
"return",
"(",
"axes",
"[",
"_i",
"]",
".",
"get_loc",
"(",
"_idx",
"[",
"'key'",
"]",
")",
"if",
"isinstance",
... | create a filtered indexer that doesn't have any missing indexers | [
"create",
"a",
"filtered",
"indexer",
"that",
"doesn",
"t",
"have",
"any",
"missing",
"indexers"
] | python | train |
yyuu/botornado | boto/sdb/db/manager/xmlmanager.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sdb/db/manager/xmlmanager.py#L475-L484 | def unmarshal_props(self, fp, cls=None, id=None):
"""
Same as unmarshalling an object, except it returns
from "get_props_from_doc"
"""
if isinstance(fp, str) or isinstance(fp, unicode):
doc = parseString(fp)
else:
doc = parse(fp)
return sel... | [
"def",
"unmarshal_props",
"(",
"self",
",",
"fp",
",",
"cls",
"=",
"None",
",",
"id",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"fp",
",",
"str",
")",
"or",
"isinstance",
"(",
"fp",
",",
"unicode",
")",
":",
"doc",
"=",
"parseString",
"(",
... | Same as unmarshalling an object, except it returns
from "get_props_from_doc" | [
"Same",
"as",
"unmarshalling",
"an",
"object",
"except",
"it",
"returns",
"from",
"get_props_from_doc"
] | python | train |
saltstack/salt | salt/cloud/clouds/nova.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/nova.py#L934-L1077 | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'nov... | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"'nova'... | Create a single VM from a data dict | [
"Create",
"a",
"single",
"VM",
"from",
"a",
"data",
"dict"
] | python | train |
bitcaster-io/bitcaster | src/bitcaster/web/templatetags/bc_assets.py | https://github.com/bitcaster-io/bitcaster/blob/04625a4b67c1ad01e5d38faa3093828b360d4a98/src/bitcaster/web/templatetags/bc_assets.py#L19-L35 | def asset(path):
"""
Join the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_wit... | [
"def",
"asset",
"(",
"path",
")",
":",
"commit",
"=",
"bitcaster",
".",
"get_full_version",
"(",
")",
"return",
"mark_safe",
"(",
"'{0}?{1}'",
".",
"format",
"(",
"_static",
"(",
"path",
")",
",",
"commit",
")",
")"
] | Join the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_with_path as varname %} | [
"Join",
"the",
"given",
"path",
"with",
"the",
"STATIC_URL",
"setting",
"."
] | python | train |
Neurosim-lab/netpyne | examples/RL_arm/main.py | https://github.com/Neurosim-lab/netpyne/blob/edb67b5098b2e7923d55010ded59ad1bf75c0f18/examples/RL_arm/main.py#L127-L134 | def saveWeights(sim):
''' Save the weights for each plastic synapse '''
with open(sim.weightsfilename,'w') as fid:
for weightdata in sim.allWeights:
fid.write('%0.0f' % weightdata[0]) # Time
for i in range(1,len(weightdata)): fid.write('\t%0.8f' % weightdata[i])
fid.w... | [
"def",
"saveWeights",
"(",
"sim",
")",
":",
"with",
"open",
"(",
"sim",
".",
"weightsfilename",
",",
"'w'",
")",
"as",
"fid",
":",
"for",
"weightdata",
"in",
"sim",
".",
"allWeights",
":",
"fid",
".",
"write",
"(",
"'%0.0f'",
"%",
"weightdata",
"[",
... | Save the weights for each plastic synapse | [
"Save",
"the",
"weights",
"for",
"each",
"plastic",
"synapse"
] | python | train |
titusjan/argos | argos/inspector/pgplugins/lineplot1d.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L153-L159 | def finalize(self):
""" Is called before destruction. Can be used to clean-up resources
"""
logger.debug("Finalizing: {}".format(self))
self.plotItem.scene().sigMouseMoved.disconnect(self.mouseMoved)
self.plotItem.close()
self.graphicsLayoutWidget.close() | [
"def",
"finalize",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Finalizing: {}\"",
".",
"format",
"(",
"self",
")",
")",
"self",
".",
"plotItem",
".",
"scene",
"(",
")",
".",
"sigMouseMoved",
".",
"disconnect",
"(",
"self",
".",
"mouseMoved",
... | Is called before destruction. Can be used to clean-up resources | [
"Is",
"called",
"before",
"destruction",
".",
"Can",
"be",
"used",
"to",
"clean",
"-",
"up",
"resources"
] | python | train |
gersolar/netcdf | netcdf/netcdf.py | https://github.com/gersolar/netcdf/blob/cae82225be98586d7516bbfc5aafa8f2a2b266c4/netcdf/netcdf.py#L300-L315 | def getvar(root, name, vtype='', dimensions=(), digits=0, fill_value=None,
source=None):
"""
Return a variable from a NCFile or NCPackage instance. If the variable
doesn't exists create it.
Keyword arguments:
root -- the root descriptor returned by the 'open' function
name -- the nam... | [
"def",
"getvar",
"(",
"root",
",",
"name",
",",
"vtype",
"=",
"''",
",",
"dimensions",
"=",
"(",
")",
",",
"digits",
"=",
"0",
",",
"fill_value",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"return",
"root",
".",
"getvar",
"(",
"name",
","... | Return a variable from a NCFile or NCPackage instance. If the variable
doesn't exists create it.
Keyword arguments:
root -- the root descriptor returned by the 'open' function
name -- the name of the variable
vtype -- the type of each value, ex ['f4', 'i4', 'i1', 'S1'] (default '')
dimensions -... | [
"Return",
"a",
"variable",
"from",
"a",
"NCFile",
"or",
"NCPackage",
"instance",
".",
"If",
"the",
"variable",
"doesn",
"t",
"exists",
"create",
"it",
"."
] | python | train |
molmod/molmod | molmod/io/xyz.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/io/xyz.py#L247-L253 | def get_molecule(self, index=0):
"""Get a molecule from the trajectory
Optional argument:
| ``index`` -- The frame index [default=0]
"""
return Molecule(self.numbers, self.geometries[index], self.titles[index], symbols=self.symbols) | [
"def",
"get_molecule",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"return",
"Molecule",
"(",
"self",
".",
"numbers",
",",
"self",
".",
"geometries",
"[",
"index",
"]",
",",
"self",
".",
"titles",
"[",
"index",
"]",
",",
"symbols",
"=",
"self",
... | Get a molecule from the trajectory
Optional argument:
| ``index`` -- The frame index [default=0] | [
"Get",
"a",
"molecule",
"from",
"the",
"trajectory"
] | python | train |
bigchaindb/bigchaindb | bigchaindb/events.py | https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/events.py#L86-L97 | def dispatch(self, event):
"""Given an event, send it to all the subscribers.
Args
event (:class:`~bigchaindb.events.EventTypes`): the event to
dispatch to all the subscribers.
"""
for event_types, queues in self.queues.items():
if event.type & e... | [
"def",
"dispatch",
"(",
"self",
",",
"event",
")",
":",
"for",
"event_types",
",",
"queues",
"in",
"self",
".",
"queues",
".",
"items",
"(",
")",
":",
"if",
"event",
".",
"type",
"&",
"event_types",
":",
"for",
"queue",
"in",
"queues",
":",
"queue",
... | Given an event, send it to all the subscribers.
Args
event (:class:`~bigchaindb.events.EventTypes`): the event to
dispatch to all the subscribers. | [
"Given",
"an",
"event",
"send",
"it",
"to",
"all",
"the",
"subscribers",
"."
] | python | train |
KelSolaar/Umbra | umbra/managers/patches_manager.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/patches_manager.py#L367-L390 | def register_patches(self):
"""
Registers the patches.
:return: Method success.
:rtype: bool
"""
if not self.__paths:
return False
unregistered_patches = []
for path in self.paths:
for file in foundations.walkers.files_walker(pat... | [
"def",
"register_patches",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__paths",
":",
"return",
"False",
"unregistered_patches",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"paths",
":",
"for",
"file",
"in",
"foundations",
".",
"walkers",
".",... | Registers the patches.
:return: Method success.
:rtype: bool | [
"Registers",
"the",
"patches",
"."
] | python | train |
getfleety/coralillo | coralillo/core.py | https://github.com/getfleety/coralillo/blob/9cac101738a0fa7c1106f129604c00ef703370e1/coralillo/core.py#L194-L224 | def update(self, **kwargs):
''' validates the given data against this object's rules and then
updates '''
redis = type(self).get_redis()
errors = ValidationErrors()
for fieldname, field in self.proxy:
if not field.fillable:
continue
given... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"errors",
"=",
"ValidationErrors",
"(",
")",
"for",
"fieldname",
",",
"field",
"in",
"self",
".",
"proxy",
":",
"if... | validates the given data against this object's rules and then
updates | [
"validates",
"the",
"given",
"data",
"against",
"this",
"object",
"s",
"rules",
"and",
"then",
"updates"
] | python | train |
vladcalin/gemstone | gemstone/core/decorators.py | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/decorators.py#L35-L94 | def exposed_method(name=None, private=False, is_coroutine=True, requires_handler_reference=False):
"""
Marks a method as exposed via JSON RPC.
:param name: the name of the exposed method. Must contains only letters, digits, dots and underscores.
If not present or is set explicitly to ``Non... | [
"def",
"exposed_method",
"(",
"name",
"=",
"None",
",",
"private",
"=",
"False",
",",
"is_coroutine",
"=",
"True",
",",
"requires_handler_reference",
"=",
"False",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"# validation",
"if",
"name",
":",
"metho... | Marks a method as exposed via JSON RPC.
:param name: the name of the exposed method. Must contains only letters, digits, dots and underscores.
If not present or is set explicitly to ``None``, this parameter will default to the name
of the exposed method.
If two me... | [
"Marks",
"a",
"method",
"as",
"exposed",
"via",
"JSON",
"RPC",
"."
] | python | train |
cogniteev/yamlious | yamlious/__init__.py | https://github.com/cogniteev/yamlious/blob/fc6a603367c2135b43ef2356959963d9dccbb25a/yamlious/__init__.py#L182-L188 | def from_yaml(*streams):
""" Build voluptuous.Schema function parameters from a streams of YAMLs
"""
return from_dict(merge_dicts(*map(
lambda f: yaml.load(f, Loader=Loader),
list(streams)
))) | [
"def",
"from_yaml",
"(",
"*",
"streams",
")",
":",
"return",
"from_dict",
"(",
"merge_dicts",
"(",
"*",
"map",
"(",
"lambda",
"f",
":",
"yaml",
".",
"load",
"(",
"f",
",",
"Loader",
"=",
"Loader",
")",
",",
"list",
"(",
"streams",
")",
")",
")",
... | Build voluptuous.Schema function parameters from a streams of YAMLs | [
"Build",
"voluptuous",
".",
"Schema",
"function",
"parameters",
"from",
"a",
"streams",
"of",
"YAMLs"
] | python | train |
LLNL/scraper | scraper/code_gov/__init__.py | https://github.com/LLNL/scraper/blob/881a316e4c04dfa5a9cf491b7c7f9f997a7c56ea/scraper/code_gov/__init__.py#L131-L172 | def force_attributes(metadata, config):
"""
Forces certain fields in the Code.gov Metadata json
"""
organization = config.get('organization', '')
logger.debug('Organization: %s', organization)
contact_email = config.get('contact_email')
logger.debug('Contact Email: %s', contact_email)
... | [
"def",
"force_attributes",
"(",
"metadata",
",",
"config",
")",
":",
"organization",
"=",
"config",
".",
"get",
"(",
"'organization'",
",",
"''",
")",
"logger",
".",
"debug",
"(",
"'Organization: %s'",
",",
"organization",
")",
"contact_email",
"=",
"config",
... | Forces certain fields in the Code.gov Metadata json | [
"Forces",
"certain",
"fields",
"in",
"the",
"Code",
".",
"gov",
"Metadata",
"json"
] | python | test |
neovim/pynvim | scripts/logging_statement_modifier.py | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L145-L156 | def first_arg_to_level_name(arg):
"""Decide what level the argument specifies and return it. The argument
must contain (case-insensitive) one of the values in LEVELS or be an integer
constant. Otherwise None will be returned."""
try:
return int(arg)
except ValueError:
arg = arg.upp... | [
"def",
"first_arg_to_level_name",
"(",
"arg",
")",
":",
"try",
":",
"return",
"int",
"(",
"arg",
")",
"except",
"ValueError",
":",
"arg",
"=",
"arg",
".",
"upper",
"(",
")",
"for",
"level",
"in",
"LEVELS",
":",
"if",
"level",
"in",
"arg",
":",
"retur... | Decide what level the argument specifies and return it. The argument
must contain (case-insensitive) one of the values in LEVELS or be an integer
constant. Otherwise None will be returned. | [
"Decide",
"what",
"level",
"the",
"argument",
"specifies",
"and",
"return",
"it",
".",
"The",
"argument",
"must",
"contain",
"(",
"case",
"-",
"insensitive",
")",
"one",
"of",
"the",
"values",
"in",
"LEVELS",
"or",
"be",
"an",
"integer",
"constant",
".",
... | python | train |
nosedjango/nosedjango | nosedjango/plugins/base_plugin.py | https://github.com/nosedjango/nosedjango/blob/cd4d06857c88291769bc38e5c9573f43b7ffcd6a/nosedjango/plugins/base_plugin.py#L22-L30 | def _random_token(self, bits=128):
"""
Generates a random token, using the url-safe base64 alphabet.
The "bits" argument specifies the bits of randomness to use.
"""
alphabet = string.ascii_letters + string.digits + '-_'
# alphabet length is 64, so each letter provides lg... | [
"def",
"_random_token",
"(",
"self",
",",
"bits",
"=",
"128",
")",
":",
"alphabet",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'-_'",
"# alphabet length is 64, so each letter provides lg(64) = 6 bits",
"num_letters",
"=",
"int",
"(",
... | Generates a random token, using the url-safe base64 alphabet.
The "bits" argument specifies the bits of randomness to use. | [
"Generates",
"a",
"random",
"token",
"using",
"the",
"url",
"-",
"safe",
"base64",
"alphabet",
".",
"The",
"bits",
"argument",
"specifies",
"the",
"bits",
"of",
"randomness",
"to",
"use",
"."
] | python | valid |
jbeluch/xbmcswift2 | xbmcswift2/common.py | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/common.py#L29-L43 | def enum(*args, **kwargs):
'''An enum class to mirror XBMC constatns. All args and kwargs.keys are
added as atrrs on the returned object.
>>> States = enum('NEW_JERSEY', NY='NEW_YORK')
>>> States.NY
'NEW_YORK'
>>> States.NEW_JERSEY
'NEW_JERSEY'
>>> States._fields
['NY', 'NEW_JERSEY'... | [
"def",
"enum",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"(",
"arg",
",",
"arg",
")",
"for",
"arg",
"in",
"args",
")",
"kwargs",
"[",
"'_fields'",
"]",
"=",
"kwargs",
".",
"keys",
"(",
")",
"return",
"ty... | An enum class to mirror XBMC constatns. All args and kwargs.keys are
added as atrrs on the returned object.
>>> States = enum('NEW_JERSEY', NY='NEW_YORK')
>>> States.NY
'NEW_YORK'
>>> States.NEW_JERSEY
'NEW_JERSEY'
>>> States._fields
['NY', 'NEW_JERSEY'] | [
"An",
"enum",
"class",
"to",
"mirror",
"XBMC",
"constatns",
".",
"All",
"args",
"and",
"kwargs",
".",
"keys",
"are",
"added",
"as",
"atrrs",
"on",
"the",
"returned",
"object",
"."
] | python | train |
cuihantao/andes | andes/routines/pflow.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L197-L228 | def calc_inc(self):
"""
Calculate the Newton incrementals for each step
Returns
-------
matrix
The solution to ``x = -A\\b``
"""
system = self.system
self.newton_call()
A = sparse([[system.dae.Fx, system.dae.Gx],
[... | [
"def",
"calc_inc",
"(",
"self",
")",
":",
"system",
"=",
"self",
".",
"system",
"self",
".",
"newton_call",
"(",
")",
"A",
"=",
"sparse",
"(",
"[",
"[",
"system",
".",
"dae",
".",
"Fx",
",",
"system",
".",
"dae",
".",
"Gx",
"]",
",",
"[",
"syst... | Calculate the Newton incrementals for each step
Returns
-------
matrix
The solution to ``x = -A\\b`` | [
"Calculate",
"the",
"Newton",
"incrementals",
"for",
"each",
"step"
] | python | train |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/utils.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/utils.py#L474-L483 | def striptags(self):
r"""Unescape markup into an unicode string and strip all tags. This
also resolves known HTML4 and XHTML entities. Whitespace is
normalized to one:
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
"""
stripped = u' '... | [
"def",
"striptags",
"(",
"self",
")",
":",
"stripped",
"=",
"u' '",
".",
"join",
"(",
"_striptags_re",
".",
"sub",
"(",
"''",
",",
"self",
")",
".",
"split",
"(",
")",
")",
"return",
"Markup",
"(",
"stripped",
")",
".",
"unescape",
"(",
")"
] | r"""Unescape markup into an unicode string and strip all tags. This
also resolves known HTML4 and XHTML entities. Whitespace is
normalized to one:
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About' | [
"r",
"Unescape",
"markup",
"into",
"an",
"unicode",
"string",
"and",
"strip",
"all",
"tags",
".",
"This",
"also",
"resolves",
"known",
"HTML4",
"and",
"XHTML",
"entities",
".",
"Whitespace",
"is",
"normalized",
"to",
"one",
":"
] | python | train |
AtteqCom/zsl | src/zsl/utils/task_helper.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/task_helper.py#L20-L30 | def run_task(task_cls, task_data):
"""Instantiate and run the perform method od given task data.
:param task_cls: task class
:param task_data: task data
:type task_data: TaskData
:return: task's result
"""
task = instantiate(task_cls)
task_callable = get_callable(task)
return task_c... | [
"def",
"run_task",
"(",
"task_cls",
",",
"task_data",
")",
":",
"task",
"=",
"instantiate",
"(",
"task_cls",
")",
"task_callable",
"=",
"get_callable",
"(",
"task",
")",
"return",
"task_callable",
"(",
"TaskData",
"(",
"task_data",
")",
")"
] | Instantiate and run the perform method od given task data.
:param task_cls: task class
:param task_data: task data
:type task_data: TaskData
:return: task's result | [
"Instantiate",
"and",
"run",
"the",
"perform",
"method",
"od",
"given",
"task",
"data",
"."
] | python | train |
ladybug-tools/ladybug | ladybug/futil.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/futil.py#L249-L279 | def unzip_file(source_file, dest_dir=None, mkdir=False):
"""Unzip a compressed file.
Args:
source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)
dest_dir: Target folder to extract to (e.g. c:/ladybug).
Default is set to the same directory as the source file... | [
"def",
"unzip_file",
"(",
"source_file",
",",
"dest_dir",
"=",
"None",
",",
"mkdir",
"=",
"False",
")",
":",
"# set default dest_dir and create it if need be.",
"if",
"dest_dir",
"is",
"None",
":",
"dest_dir",
",",
"fname",
"=",
"os",
".",
"path",
".",
"split"... | Unzip a compressed file.
Args:
source_file: Full path to a valid compressed file (e.g. c:/ladybug/testPts.zip)
dest_dir: Target folder to extract to (e.g. c:/ladybug).
Default is set to the same directory as the source file.
mkdir: Set to True to create the directory if doesn't ... | [
"Unzip",
"a",
"compressed",
"file",
"."
] | python | train |
pyscaffold/configupdater | src/configupdater/configupdater.py | https://github.com/pyscaffold/configupdater/blob/6ebac0b1fa7b8222baacdd4991d18cfc61659f84/src/configupdater/configupdater.py#L995-L1009 | def has_option(self, section, option):
"""Checks for the existence of a given option in a given section.
Args:
section (str): name of section
option (str): name of option
Returns:
bool: whether the option exists in the given section
"""
if se... | [
"def",
"has_option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"section",
"not",
"in",
"self",
".",
"sections",
"(",
")",
":",
"return",
"False",
"else",
":",
"option",
"=",
"self",
".",
"optionxform",
"(",
"option",
")",
"return",
... | Checks for the existence of a given option in a given section.
Args:
section (str): name of section
option (str): name of option
Returns:
bool: whether the option exists in the given section | [
"Checks",
"for",
"the",
"existence",
"of",
"a",
"given",
"option",
"in",
"a",
"given",
"section",
"."
] | python | train |
galaxyproject/pulsar | pulsar/client/client.py | https://github.com/galaxyproject/pulsar/blob/9ab6683802884324652da0a9f0808c7eb59d3ab4/pulsar/client/client.py#L102-L133 | def launch(self, command_line, dependencies_description=None, env=[], remote_staging=[], job_config=None):
"""
Queue up the execution of the supplied `command_line` on the remote
server. Called launch for historical reasons, should be renamed to
enqueue or something like that.
*... | [
"def",
"launch",
"(",
"self",
",",
"command_line",
",",
"dependencies_description",
"=",
"None",
",",
"env",
"=",
"[",
"]",
",",
"remote_staging",
"=",
"[",
"]",
",",
"job_config",
"=",
"None",
")",
":",
"launch_params",
"=",
"dict",
"(",
"command_line",
... | Queue up the execution of the supplied `command_line` on the remote
server. Called launch for historical reasons, should be renamed to
enqueue or something like that.
**Parameters**
command_line : str
Command to execute. | [
"Queue",
"up",
"the",
"execution",
"of",
"the",
"supplied",
"command_line",
"on",
"the",
"remote",
"server",
".",
"Called",
"launch",
"for",
"historical",
"reasons",
"should",
"be",
"renamed",
"to",
"enqueue",
"or",
"something",
"like",
"that",
"."
] | python | train |
Shinichi-Nakagawa/pitchpx | pitchpx/game/players.py | https://github.com/Shinichi-Nakagawa/pitchpx/blob/5747402a0b3416f5e910b479e100df858f0b6440/pitchpx/game/players.py#L264-L272 | def read_xml(cls, url, markup, game):
"""
read xml object
:param url: contents url
:param markup: markup provider
:param game: MLBAM Game object
:return: pitchpx.game.players.Players object
"""
return Players._read_objects(MlbamUtil.find_xml("".join([url, ... | [
"def",
"read_xml",
"(",
"cls",
",",
"url",
",",
"markup",
",",
"game",
")",
":",
"return",
"Players",
".",
"_read_objects",
"(",
"MlbamUtil",
".",
"find_xml",
"(",
"\"\"",
".",
"join",
"(",
"[",
"url",
",",
"cls",
".",
"FILENAME",
"]",
")",
",",
"m... | read xml object
:param url: contents url
:param markup: markup provider
:param game: MLBAM Game object
:return: pitchpx.game.players.Players object | [
"read",
"xml",
"object",
":",
"param",
"url",
":",
"contents",
"url",
":",
"param",
"markup",
":",
"markup",
"provider",
":",
"param",
"game",
":",
"MLBAM",
"Game",
"object",
":",
"return",
":",
"pitchpx",
".",
"game",
".",
"players",
".",
"Players",
"... | python | train |
astropy/astropy-helpers | astropy_helpers/setup_helpers.py | https://github.com/astropy/astropy-helpers/blob/f5a27d3f84a98ea0eebb85e0cf3e7214c6bc0d09/astropy_helpers/setup_helpers.py#L309-L343 | def run_command_hooks(cmd_obj, hook_kind):
"""Run hooks registered for that command and phase.
*cmd_obj* is a finalized command object; *hook_kind* is either
'pre_hook' or 'post_hook'.
"""
hooks = getattr(cmd_obj, hook_kind, None)
if not hooks:
return
for modname, hook in hooks:
... | [
"def",
"run_command_hooks",
"(",
"cmd_obj",
",",
"hook_kind",
")",
":",
"hooks",
"=",
"getattr",
"(",
"cmd_obj",
",",
"hook_kind",
",",
"None",
")",
"if",
"not",
"hooks",
":",
"return",
"for",
"modname",
",",
"hook",
"in",
"hooks",
":",
"if",
"isinstance... | Run hooks registered for that command and phase.
*cmd_obj* is a finalized command object; *hook_kind* is either
'pre_hook' or 'post_hook'. | [
"Run",
"hooks",
"registered",
"for",
"that",
"command",
"and",
"phase",
"."
] | python | train |
inveniosoftware-attic/invenio-upgrader | invenio_upgrader/engine.py | https://github.com/inveniosoftware-attic/invenio-upgrader/blob/cee4bcb118515463ecf6de1421642007f79a9fcd/invenio_upgrader/engine.py#L507-L514 | def repository(self):
"""Repository."""
m = re.match("(.+)(_\d{4}_\d{2}_\d{2}_)(.+)", self.__module__)
if m:
return m.group(1)
m = re.match("(.+)(_release_)(.+)", self.__module__)
if m:
return m.group(1) | [
"def",
"repository",
"(",
"self",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"\"(.+)(_\\d{4}_\\d{2}_\\d{2}_)(.+)\"",
",",
"self",
".",
"__module__",
")",
"if",
"m",
":",
"return",
"m",
".",
"group",
"(",
"1",
")",
"m",
"=",
"re",
".",
"match",
"(",... | Repository. | [
"Repository",
"."
] | python | train |
fhs/pyhdf | pyhdf/SD.py | https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/SD.py#L1817-L1837 | def endaccess(self):
"""Terminates access to the SDS.
Args::
no argument
Returns::
None.
The SDS instance should not be used afterwards.
The 'endaccess()' method is implicitly called when
the SDS instance is deleted.
C library equivalent ... | [
"def",
"endaccess",
"(",
"self",
")",
":",
"status",
"=",
"_C",
".",
"SDendaccess",
"(",
"self",
".",
"_id",
")",
"_checkErr",
"(",
"'endaccess'",
",",
"status",
",",
"\"cannot execute\"",
")",
"self",
".",
"_id",
"=",
"None"
] | Terminates access to the SDS.
Args::
no argument
Returns::
None.
The SDS instance should not be used afterwards.
The 'endaccess()' method is implicitly called when
the SDS instance is deleted.
C library equivalent : SDendaccess | [
"Terminates",
"access",
"to",
"the",
"SDS",
"."
] | python | train |
INM-6/hybridLFPy | hybridLFPy/helpers.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/hybridLFPy/helpers.py#L853-L899 | def compound_crossspec(a_data, tbin, Df=None, pointProcess=False):
"""
Calculate cross spectra of compound signals.
a_data is a list of datasets (a_data = [data1,data2,...]).
For each dataset in a_data, the compound signal is calculated
and the crossspectra between these compound signals is computed... | [
"def",
"compound_crossspec",
"(",
"a_data",
",",
"tbin",
",",
"Df",
"=",
"None",
",",
"pointProcess",
"=",
"False",
")",
":",
"a_mdata",
"=",
"[",
"]",
"for",
"data",
"in",
"a_data",
":",
"a_mdata",
".",
"append",
"(",
"np",
".",
"sum",
"(",
"data",
... | Calculate cross spectra of compound signals.
a_data is a list of datasets (a_data = [data1,data2,...]).
For each dataset in a_data, the compound signal is calculated
and the crossspectra between these compound signals is computed.
If pointProcess=True, power spectra are normalized by the length T o... | [
"Calculate",
"cross",
"spectra",
"of",
"compound",
"signals",
".",
"a_data",
"is",
"a",
"list",
"of",
"datasets",
"(",
"a_data",
"=",
"[",
"data1",
"data2",
"...",
"]",
")",
".",
"For",
"each",
"dataset",
"in",
"a_data",
"the",
"compound",
"signal",
"is"... | python | train |
osrg/ryu | ryu/services/protocols/bgp/core_managers/table_manager.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/core_managers/table_manager.py#L302-L314 | def get_evpn_table(self):
"""Returns global EVPN table.
Creates the table if it does not exist.
"""
evpn_table = self._global_tables.get(RF_L2_EVPN)
# Lazy initialization of the table.
if not evpn_table:
evpn_table = EvpnTable(self._core_service, self._signal... | [
"def",
"get_evpn_table",
"(",
"self",
")",
":",
"evpn_table",
"=",
"self",
".",
"_global_tables",
".",
"get",
"(",
"RF_L2_EVPN",
")",
"# Lazy initialization of the table.",
"if",
"not",
"evpn_table",
":",
"evpn_table",
"=",
"EvpnTable",
"(",
"self",
".",
"_core_... | Returns global EVPN table.
Creates the table if it does not exist. | [
"Returns",
"global",
"EVPN",
"table",
"."
] | python | train |
Grunny/zap-cli | zapcli/commands/context.py | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/context.py#L64-L71 | def context_exclude(zap_helper, name, pattern):
"""Exclude a pattern from a given context."""
console.info('Excluding regex {0} from context with name: {1}'.format(pattern, name))
with zap_error_handler():
result = zap_helper.zap.context.exclude_from_context(contextname=name, regex=pattern)
... | [
"def",
"context_exclude",
"(",
"zap_helper",
",",
"name",
",",
"pattern",
")",
":",
"console",
".",
"info",
"(",
"'Excluding regex {0} from context with name: {1}'",
".",
"format",
"(",
"pattern",
",",
"name",
")",
")",
"with",
"zap_error_handler",
"(",
")",
":"... | Exclude a pattern from a given context. | [
"Exclude",
"a",
"pattern",
"from",
"a",
"given",
"context",
"."
] | python | train |
ASKIDA/Selenium2LibraryExtension | src/Selenium2LibraryExtension/keywords/__init__.py | https://github.com/ASKIDA/Selenium2LibraryExtension/blob/5ca3fa776063c6046dff317cb2575e4772d7541f/src/Selenium2LibraryExtension/keywords/__init__.py#L380-L388 | def wait_until_page_contains_elements(self, timeout, *locators):
"""This is a copy of `Wait Until Page Contains Element` but it allows
multiple arguments in order to wait for more than one element.
| *Argument* | *Description* | *Example* |
| timeout | maximum time to wait, if set to ${None} it will use Sele... | [
"def",
"wait_until_page_contains_elements",
"(",
"self",
",",
"timeout",
",",
"*",
"locators",
")",
":",
"self",
".",
"_wait_until_no_error",
"(",
"timeout",
",",
"self",
".",
"_wait_for_elements",
",",
"locators",
")"
] | This is a copy of `Wait Until Page Contains Element` but it allows
multiple arguments in order to wait for more than one element.
| *Argument* | *Description* | *Example* |
| timeout | maximum time to wait, if set to ${None} it will use Selenium's default timeout | 5s |
| *locators | Selenium 2 element locat... | [
"This",
"is",
"a",
"copy",
"of",
"Wait",
"Until",
"Page",
"Contains",
"Element",
"but",
"it",
"allows",
"multiple",
"arguments",
"in",
"order",
"to",
"wait",
"for",
"more",
"than",
"one",
"element",
".",
"|",
"*",
"Argument",
"*",
"|",
"*",
"Description"... | python | train |
tensorflow/probability | tensorflow_probability/python/distributions/vector_diffeomixture.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L958-L972 | def softmax(x, axis, name=None):
"""Equivalent to tf.nn.softmax but works around b/70297725."""
with tf.name_scope(name or "softmax"):
x = tf.convert_to_tensor(value=x, name="x")
ndims = (
tensorshape_util.rank(x.shape)
if tensorshape_util.rank(x.shape) is not None else tf.rank(
... | [
"def",
"softmax",
"(",
"x",
",",
"axis",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"\"softmax\"",
")",
":",
"x",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"value",
"=",
"x",
",",
"name",
"=",
"\"x\"",
... | Equivalent to tf.nn.softmax but works around b/70297725. | [
"Equivalent",
"to",
"tf",
".",
"nn",
".",
"softmax",
"but",
"works",
"around",
"b",
"/",
"70297725",
"."
] | python | test |
gwpy/gwpy | gwpy/table/filter.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/filter.py#L218-L256 | def filter_table(table, *column_filters):
"""Apply one or more column slice filters to a `Table`
Multiple column filters can be given, and will be applied
concurrently
Parameters
----------
table : `~astropy.table.Table`
the table to filter
column_filter : `str`, `tuple`
a... | [
"def",
"filter_table",
"(",
"table",
",",
"*",
"column_filters",
")",
":",
"keep",
"=",
"numpy",
".",
"ones",
"(",
"len",
"(",
"table",
")",
",",
"dtype",
"=",
"bool",
")",
"for",
"name",
",",
"op_func",
",",
"operand",
"in",
"parse_column_filters",
"(... | Apply one or more column slice filters to a `Table`
Multiple column filters can be given, and will be applied
concurrently
Parameters
----------
table : `~astropy.table.Table`
the table to filter
column_filter : `str`, `tuple`
a column slice filter definition, in one of two fo... | [
"Apply",
"one",
"or",
"more",
"column",
"slice",
"filters",
"to",
"a",
"Table"
] | python | train |
sixty-north/python-transducers | transducer/functional.py | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/functional.py#L5-L31 | def compose(f, *fs):
"""Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
... | [
"def",
"compose",
"(",
"f",
",",
"*",
"fs",
")",
":",
"rfs",
"=",
"list",
"(",
"chain",
"(",
"[",
"f",
"]",
",",
"fs",
")",
")",
"rfs",
".",
"reverse",
"(",
")",
"def",
"composed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"retur... | Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
this last prov... | [
"Compose",
"functions",
"right",
"to",
"left",
"."
] | python | train |
dmlc/xgboost | python-package/xgboost/core.py | https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/core.py#L1040-L1054 | def attributes(self):
"""Get attributes stored in the Booster as a dictionary.
Returns
-------
result : dictionary of attribute_name: attribute_value pairs of strings.
Returns an empty dict if there's no attributes.
"""
length = c_bst_ulong()
sarr = ... | [
"def",
"attributes",
"(",
"self",
")",
":",
"length",
"=",
"c_bst_ulong",
"(",
")",
"sarr",
"=",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char_p",
")",
"(",
")",
"_check_call",
"(",
"_LIB",
".",
"XGBoosterGetAttrNames",
"(",
"self",
".",
"handle"... | Get attributes stored in the Booster as a dictionary.
Returns
-------
result : dictionary of attribute_name: attribute_value pairs of strings.
Returns an empty dict if there's no attributes. | [
"Get",
"attributes",
"stored",
"in",
"the",
"Booster",
"as",
"a",
"dictionary",
"."
] | python | train |
catherinedevlin/ddl-generator | ddlgenerator/ddlgenerator.py | https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/ddlgenerator.py#L263-L281 | def ddl(self, dialect=None, creates=True, drops=True):
"""
Returns SQL to define the table.
"""
dialect = self._dialect(dialect)
creator = CreateTable(self.table).compile(mock_engines[dialect])
creator = "\n".join(l for l in str(creator).splitlines() if l.strip()) # remov... | [
"def",
"ddl",
"(",
"self",
",",
"dialect",
"=",
"None",
",",
"creates",
"=",
"True",
",",
"drops",
"=",
"True",
")",
":",
"dialect",
"=",
"self",
".",
"_dialect",
"(",
"dialect",
")",
"creator",
"=",
"CreateTable",
"(",
"self",
".",
"table",
")",
"... | Returns SQL to define the table. | [
"Returns",
"SQL",
"to",
"define",
"the",
"table",
"."
] | python | train |
stan-dev/pystan | pystan/experimental/misc.py | https://github.com/stan-dev/pystan/blob/57bdccea11888157e7aaafba083003080a934805/pystan/experimental/misc.py#L7-L40 | def fix_include(model_code):
"""Reformat `model_code` (remove whitespace) around the #include statements.
Note
----
A modified `model_code` is returned.
Parameters
----------
model_code : str
Model code
Returns
-------
str
Reformatted model code
... | [
"def",
"fix_include",
"(",
"model_code",
")",
":",
"pattern",
"=",
"r\"(?<=\\n)\\s*(#include)\\s*(\\S+)\\s*(?=\\n)\"",
"model_code",
",",
"n",
"=",
"re",
".",
"subn",
"(",
"pattern",
",",
"r\"\\1 \\2\"",
",",
"model_code",
")",
"if",
"n",
"==",
"1",
":",
"msg"... | Reformat `model_code` (remove whitespace) around the #include statements.
Note
----
A modified `model_code` is returned.
Parameters
----------
model_code : str
Model code
Returns
-------
str
Reformatted model code
Example
-------
>... | [
"Reformat",
"model_code",
"(",
"remove",
"whitespace",
")",
"around",
"the",
"#include",
"statements",
".",
"Note",
"----",
"A",
"modified",
"model_code",
"is",
"returned",
"."
] | python | train |
mcs07/ChemDataExtractor | chemdataextractor/cli/dict.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/dict.py#L312-L322 | def build(ctx, inputs, output, cs):
"""Build chemical name dictionary."""
click.echo('chemdataextractor.dict.build')
dt = DictionaryTagger(lexicon=ChemLexicon(), case_sensitive=cs)
names = []
for input in inputs:
for line in input:
tokens = line.split()
names.append(t... | [
"def",
"build",
"(",
"ctx",
",",
"inputs",
",",
"output",
",",
"cs",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.dict.build'",
")",
"dt",
"=",
"DictionaryTagger",
"(",
"lexicon",
"=",
"ChemLexicon",
"(",
")",
",",
"case_sensitive",
"=",
"cs",
... | Build chemical name dictionary. | [
"Build",
"chemical",
"name",
"dictionary",
"."
] | python | train |
mgbarrero/xbob.db.atvskeystroke | xbob/db/atvskeystroke/query.py | https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L122-L140 | def model_ids(self, protocol=None, groups=None):
"""Returns a list of model ids for the specific query by the user.
Models correspond to Clients for the XM2VTS database (At most one model per identity).
Keyword Parameters:
protocol
Ignored.
groups
The groups to which the subjects a... | [
"def",
"model_ids",
"(",
"self",
",",
"protocol",
"=",
"None",
",",
"groups",
"=",
"None",
")",
":",
"return",
"[",
"client",
".",
"subid",
"for",
"client",
"in",
"self",
".",
"models",
"(",
"protocol",
",",
"groups",
")",
"]"
] | Returns a list of model ids for the specific query by the user.
Models correspond to Clients for the XM2VTS database (At most one model per identity).
Keyword Parameters:
protocol
Ignored.
groups
The groups to which the subjects attached to the models belong ('dev', 'eval', 'world')
... | [
"Returns",
"a",
"list",
"of",
"model",
"ids",
"for",
"the",
"specific",
"query",
"by",
"the",
"user",
".",
"Models",
"correspond",
"to",
"Clients",
"for",
"the",
"XM2VTS",
"database",
"(",
"At",
"most",
"one",
"model",
"per",
"identity",
")",
"."
] | python | train |
troeger/opensubmit | web/opensubmit/models/assignment.py | https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/models/assignment.py#L142-L172 | def can_create_submission(self, user=None):
'''
Central access control for submitting things related to assignments.
'''
if user:
# Super users, course owners and tutors should be able to test their validations
# before the submission is officially possible.
... | [
"def",
"can_create_submission",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
":",
"# Super users, course owners and tutors should be able to test their validations",
"# before the submission is officially possible.",
"# They should also be able to submit after the dea... | Central access control for submitting things related to assignments. | [
"Central",
"access",
"control",
"for",
"submitting",
"things",
"related",
"to",
"assignments",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.