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 |
|---|---|---|---|---|---|---|---|---|
tensorflow/tensor2tensor | tensor2tensor/layers/discretization.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L908-L934 | def vq_nearest_neighbor(x, means,
soft_em=False, num_samples=10, temperature=None):
"""Find the nearest element in means to elements in x."""
bottleneck_size = common_layers.shape_list(means)[0]
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum... | [
"def",
"vq_nearest_neighbor",
"(",
"x",
",",
"means",
",",
"soft_em",
"=",
"False",
",",
"num_samples",
"=",
"10",
",",
"temperature",
"=",
"None",
")",
":",
"bottleneck_size",
"=",
"common_layers",
".",
"shape_list",
"(",
"means",
")",
"[",
"0",
"]",
"x... | Find the nearest element in means to elements in x. | [
"Find",
"the",
"nearest",
"element",
"in",
"means",
"to",
"elements",
"in",
"x",
"."
] | python | train |
Gandi/gandi.cli | gandi/cli/core/utils/__init__.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/core/utils/__init__.py#L474-L477 | def output_sub_line(gandi, key, val, justify):
""" Base helper to output a key value using left justify."""
msg = ('\t%%-%ds:%%s' % justify) % (key, (' %s' % val) if val else '')
gandi.echo(msg) | [
"def",
"output_sub_line",
"(",
"gandi",
",",
"key",
",",
"val",
",",
"justify",
")",
":",
"msg",
"=",
"(",
"'\\t%%-%ds:%%s'",
"%",
"justify",
")",
"%",
"(",
"key",
",",
"(",
"' %s'",
"%",
"val",
")",
"if",
"val",
"else",
"''",
")",
"gandi",
".",
... | Base helper to output a key value using left justify. | [
"Base",
"helper",
"to",
"output",
"a",
"key",
"value",
"using",
"left",
"justify",
"."
] | python | train |
empymod/empymod | empymod/model.py | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L68-L590 | def bipole(src, rec, depth, res, freqtime, signal=None, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, msrc=False,
srcpts=1, mrec=False, recpts=1, strength=0, xdirect=False,
ht='fht', htarg=None, ft='sin', ftarg=None, opt=None, loop=None,
verb=2):
r"""Ret... | [
"def",
"bipole",
"(",
"src",
",",
"rec",
",",
"depth",
",",
"res",
",",
"freqtime",
",",
"signal",
"=",
"None",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
"None",
",",
"mpermV",
"=",
"No... | r"""Return the electromagnetic field due to an electromagnetic source.
Calculate the electromagnetic frequency- or time-domain field due to
arbitrary finite electric or magnetic bipole sources, measured by arbitrary
finite electric or magnetic bipole receivers. By default, the
electromagnetic response ... | [
"r",
"Return",
"the",
"electromagnetic",
"field",
"due",
"to",
"an",
"electromagnetic",
"source",
"."
] | python | train |
RJT1990/pyflux | pyflux/arma/nnarx.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/nnarx.py#L304-L341 | def _mean_prediction(self, mu, Y, h, t_z):
""" Creates a h-step ahead mean prediction
Parameters
----------
mu : np.ndarray
The past predicted values
Y : np.ndarray
The past data
h : int
How many steps ahead for the prediction
... | [
"def",
"_mean_prediction",
"(",
"self",
",",
"mu",
",",
"Y",
",",
"h",
",",
"t_z",
")",
":",
"# Create arrays to iteratre over",
"Y_exp",
"=",
"Y",
".",
"copy",
"(",
")",
"# Loop over h time periods ",
"for",
"t",
"in",
"range",
"(",
"0",
",",
"h"... | Creates a h-step ahead mean prediction
Parameters
----------
mu : np.ndarray
The past predicted values
Y : np.ndarray
The past data
h : int
How many steps ahead for the prediction
t_z : np.ndarray
A vector of (transforme... | [
"Creates",
"a",
"h",
"-",
"step",
"ahead",
"mean",
"prediction"
] | python | train |
raiden-network/raiden | raiden/network/proxies/secret_registry.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/secret_registry.py#L79-L301 | def register_secret_batch(
self,
secrets: List[Secret],
):
"""Register a batch of secrets. Check if they are already registered at
the given block identifier."""
secrets_to_register = list()
secrethashes_to_register = list()
secrethashes_not_sent = lis... | [
"def",
"register_secret_batch",
"(",
"self",
",",
"secrets",
":",
"List",
"[",
"Secret",
"]",
",",
")",
":",
"secrets_to_register",
"=",
"list",
"(",
")",
"secrethashes_to_register",
"=",
"list",
"(",
")",
"secrethashes_not_sent",
"=",
"list",
"(",
")",
"tra... | Register a batch of secrets. Check if they are already registered at
the given block identifier. | [
"Register",
"a",
"batch",
"of",
"secrets",
".",
"Check",
"if",
"they",
"are",
"already",
"registered",
"at",
"the",
"given",
"block",
"identifier",
"."
] | python | train |
ubccr/pinky | pinky/perception/aromaticity.py | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/perception/aromaticity.py#L237-L264 | def addHydrogens(molecule, usedPyroles=None):
"""(molecule) -> add implicit hydrogens to a molecule.
If the atom has specified valences and the atom must be
charged then a Valence Error is raised"""
for atom in molecule.atoms:
# if the atom has an explicit hcount, we can't set the
# hcou... | [
"def",
"addHydrogens",
"(",
"molecule",
",",
"usedPyroles",
"=",
"None",
")",
":",
"for",
"atom",
"in",
"molecule",
".",
"atoms",
":",
"# if the atom has an explicit hcount, we can't set the",
"# hcount",
"if",
"atom",
".",
"has_explicit_hcount",
":",
"atom",
".",
... | (molecule) -> add implicit hydrogens to a molecule.
If the atom has specified valences and the atom must be
charged then a Valence Error is raised | [
"(",
"molecule",
")",
"-",
">",
"add",
"implicit",
"hydrogens",
"to",
"a",
"molecule",
".",
"If",
"the",
"atom",
"has",
"specified",
"valences",
"and",
"the",
"atom",
"must",
"be",
"charged",
"then",
"a",
"Valence",
"Error",
"is",
"raised"
] | python | train |
limodou/uliweb | uliweb/lib/werkzeug/contrib/jsrouting.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/jsrouting.py#L236-L247 | def js_to_url_function(converter):
"""Get the JavaScript converter function from a rule."""
if hasattr(converter, 'js_to_url_function'):
data = converter.js_to_url_function()
else:
for cls in getmro(type(converter)):
if cls in js_to_url_functions:
data = js_to_url... | [
"def",
"js_to_url_function",
"(",
"converter",
")",
":",
"if",
"hasattr",
"(",
"converter",
",",
"'js_to_url_function'",
")",
":",
"data",
"=",
"converter",
".",
"js_to_url_function",
"(",
")",
"else",
":",
"for",
"cls",
"in",
"getmro",
"(",
"type",
"(",
"... | Get the JavaScript converter function from a rule. | [
"Get",
"the",
"JavaScript",
"converter",
"function",
"from",
"a",
"rule",
"."
] | python | train |
xi/ldif3 | ldif3.py | https://github.com/xi/ldif3/blob/debc4222bb48492de0d3edcc3c71fdae5bc612a4/ldif3.py#L233-L240 | def _strip_line_sep(self, s):
"""Strip trailing line separators from s, but no other whitespaces."""
if s[-2:] == b'\r\n':
return s[:-2]
elif s[-1:] == b'\n':
return s[:-1]
else:
return s | [
"def",
"_strip_line_sep",
"(",
"self",
",",
"s",
")",
":",
"if",
"s",
"[",
"-",
"2",
":",
"]",
"==",
"b'\\r\\n'",
":",
"return",
"s",
"[",
":",
"-",
"2",
"]",
"elif",
"s",
"[",
"-",
"1",
":",
"]",
"==",
"b'\\n'",
":",
"return",
"s",
"[",
":... | Strip trailing line separators from s, but no other whitespaces. | [
"Strip",
"trailing",
"line",
"separators",
"from",
"s",
"but",
"no",
"other",
"whitespaces",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/akkar_bommer_2010.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/akkar_bommer_2010.py#L195-L209 | def _get_fault_type_dummy_variables(self, sites, rup, imt):
"""
Same classification of SadighEtAl1997. Akkar and Bommer 2010 is based
on Akkar and Bommer 2007b; read Strong-Motion Dataset and Record
Processing on p. 514 (Akkar and Bommer 2007b).
"""
Fn, Fr = 0, 0
... | [
"def",
"_get_fault_type_dummy_variables",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"imt",
")",
":",
"Fn",
",",
"Fr",
"=",
"0",
",",
"0",
"if",
"rup",
".",
"rake",
">=",
"-",
"135",
"and",
"rup",
".",
"rake",
"<=",
"-",
"45",
":",
"# normal",
"... | Same classification of SadighEtAl1997. Akkar and Bommer 2010 is based
on Akkar and Bommer 2007b; read Strong-Motion Dataset and Record
Processing on p. 514 (Akkar and Bommer 2007b). | [
"Same",
"classification",
"of",
"SadighEtAl1997",
".",
"Akkar",
"and",
"Bommer",
"2010",
"is",
"based",
"on",
"Akkar",
"and",
"Bommer",
"2007b",
";",
"read",
"Strong",
"-",
"Motion",
"Dataset",
"and",
"Record",
"Processing",
"on",
"p",
".",
"514",
"(",
"Ak... | python | train |
theislab/scanpy | scanpy/utils.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/utils.py#L180-L340 | def cross_entropy_neighbors_in_rep(adata, use_rep, n_points=3):
"""Compare neighborhood graph of representation based on cross entropy.
`n_points` denotes the number of points to add as highlight annotation.
Returns
-------
The cross entropy and the geodesic-distance-weighted cross entropy as
... | [
"def",
"cross_entropy_neighbors_in_rep",
"(",
"adata",
",",
"use_rep",
",",
"n_points",
"=",
"3",
")",
":",
"# see below why we need this",
"if",
"'X_diffmap'",
"not",
"in",
"adata",
".",
"obsm",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Run `t... | Compare neighborhood graph of representation based on cross entropy.
`n_points` denotes the number of points to add as highlight annotation.
Returns
-------
The cross entropy and the geodesic-distance-weighted cross entropy as
``entropy, geo_entropy_d, geo_entropy_o``.
Adds the most overlappi... | [
"Compare",
"neighborhood",
"graph",
"of",
"representation",
"based",
"on",
"cross",
"entropy",
"."
] | python | train |
unt-libraries/pyuntl | pyuntl/form_logic.py | https://github.com/unt-libraries/pyuntl/blob/f92413302897dab948aac18ee9e482ace0187bd4/pyuntl/form_logic.py#L30-L42 | def get_qualifier_dict(vocabularies, qualifier_vocab):
"""Get the qualifier dictionary based on the element's qualifier
vocabulary.
"""
# Raise exception if the vocabulary can't be found.
if vocabularies.get(qualifier_vocab, None) is None:
raise UNTLFormException(
'Could not retr... | [
"def",
"get_qualifier_dict",
"(",
"vocabularies",
",",
"qualifier_vocab",
")",
":",
"# Raise exception if the vocabulary can't be found.",
"if",
"vocabularies",
".",
"get",
"(",
"qualifier_vocab",
",",
"None",
")",
"is",
"None",
":",
"raise",
"UNTLFormException",
"(",
... | Get the qualifier dictionary based on the element's qualifier
vocabulary. | [
"Get",
"the",
"qualifier",
"dictionary",
"based",
"on",
"the",
"element",
"s",
"qualifier",
"vocabulary",
"."
] | python | train |
google/textfsm | textfsm/parser.py | https://github.com/google/textfsm/blob/63a2aaece33e07947aa80963dca99b893964633b/textfsm/parser.py#L1044-L1093 | def main(argv=None):
"""Validate text parsed with FSM or validate an FSM via command line."""
if argv is None:
argv = sys.argv
try:
opts, args = getopt.getopt(argv[1:], 'h', ['help'])
except getopt.error as msg:
raise Usage(msg)
for opt, _ in opts:
if opt in ('-h', '--help'):
print(__... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"try",
":",
"opts",
",",
"args",
"=",
"getopt",
".",
"getopt",
"(",
"argv",
"[",
"1",
":",
"]",
",",
"'h'",
",",
"[",
"'help'... | Validate text parsed with FSM or validate an FSM via command line. | [
"Validate",
"text",
"parsed",
"with",
"FSM",
"or",
"validate",
"an",
"FSM",
"via",
"command",
"line",
"."
] | python | train |
gwastro/pycbc | pycbc/inference/io/base_mcmc.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inference/io/base_mcmc.py#L291-L354 | def write_samples(self, samples, parameters=None, last_iteration=None):
"""Writes samples to the given file.
Results are written to ``samples_group/{vararg}``, where ``{vararg}``
is the name of a model params. The samples are written as an
``nwalkers x niterations`` array. If samples al... | [
"def",
"write_samples",
"(",
"self",
",",
"samples",
",",
"parameters",
"=",
"None",
",",
"last_iteration",
"=",
"None",
")",
":",
"nwalkers",
",",
"nsamples",
"=",
"list",
"(",
"samples",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
".",
"shape",
"a... | Writes samples to the given file.
Results are written to ``samples_group/{vararg}``, where ``{vararg}``
is the name of a model params. The samples are written as an
``nwalkers x niterations`` array. If samples already exist, the new
samples are appended to the current.
If the c... | [
"Writes",
"samples",
"to",
"the",
"given",
"file",
"."
] | python | train |
facetoe/zenpy | zenpy/lib/api.py | https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/api.py#L1930-L1942 | def bulk_attachments(self, article, attachments):
"""
This function implements associating attachments to an article after article creation (for
unassociated attachments).
:param article: Article id or :class:`Article` object
:param attachments: :class:`ArticleAttachment` object... | [
"def",
"bulk_attachments",
"(",
"self",
",",
"article",
",",
"attachments",
")",
":",
"return",
"HelpdeskAttachmentRequest",
"(",
"self",
")",
".",
"post",
"(",
"self",
".",
"endpoint",
".",
"bulk_attachments",
",",
"article",
"=",
"article",
",",
"attachments... | This function implements associating attachments to an article after article creation (for
unassociated attachments).
:param article: Article id or :class:`Article` object
:param attachments: :class:`ArticleAttachment` object, or list of :class:`ArticleAttachment` objects,
up to 20 supp... | [
"This",
"function",
"implements",
"associating",
"attachments",
"to",
"an",
"article",
"after",
"article",
"creation",
"(",
"for",
"unassociated",
"attachments",
")",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xmultitagedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xmultitagedit.py#L313-L354 | def dropEvent( self, event ):
"""
Handles the drop event.
:param event | <QDropEvent>
"""
tags = nativestring(event.mimeData().text())
# handle an internal move
if event.source() == self:
curr_item = self.selectedItems()[0... | [
"def",
"dropEvent",
"(",
"self",
",",
"event",
")",
":",
"tags",
"=",
"nativestring",
"(",
"event",
".",
"mimeData",
"(",
")",
".",
"text",
"(",
")",
")",
"# handle an internal move",
"if",
"event",
".",
"source",
"(",
")",
"==",
"self",
":",
"curr_ite... | Handles the drop event.
:param event | <QDropEvent> | [
"Handles",
"the",
"drop",
"event",
".",
":",
"param",
"event",
"|",
"<QDropEvent",
">"
] | python | train |
Capitains/Nautilus | capitains_nautilus/cts/resolver/base.py | https://github.com/Capitains/Nautilus/blob/6be453fe0cc0e2c1b89ff06e5af1409165fc1411/capitains_nautilus/cts/resolver/base.py#L48-L59 | def xmlparse(self, file):
""" Parse a XML file
:param file: Opened File
:return: Tree
"""
if self.CACHE_FULL_TEI is True:
return self.get_or(
_cache_key("Nautilus", self.name, "File", "Tree", file.name),
super(ProtoNautilusCtsResolver,... | [
"def",
"xmlparse",
"(",
"self",
",",
"file",
")",
":",
"if",
"self",
".",
"CACHE_FULL_TEI",
"is",
"True",
":",
"return",
"self",
".",
"get_or",
"(",
"_cache_key",
"(",
"\"Nautilus\"",
",",
"self",
".",
"name",
",",
"\"File\"",
",",
"\"Tree\"",
",",
"fi... | Parse a XML file
:param file: Opened File
:return: Tree | [
"Parse",
"a",
"XML",
"file"
] | python | train |
python-openxml/python-docx | docx/oxml/section.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/oxml/section.py#L147-L154 | def get_headerReference(self, type_):
"""Return headerReference element of *type_* or None if not present."""
matching_headerReferences = self.xpath(
"./w:headerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_)
)
if len(matching_headerReferences) == 0:
ret... | [
"def",
"get_headerReference",
"(",
"self",
",",
"type_",
")",
":",
"matching_headerReferences",
"=",
"self",
".",
"xpath",
"(",
"\"./w:headerReference[@w:type='%s']\"",
"%",
"WD_HEADER_FOOTER",
".",
"to_xml",
"(",
"type_",
")",
")",
"if",
"len",
"(",
"matching_hea... | Return headerReference element of *type_* or None if not present. | [
"Return",
"headerReference",
"element",
"of",
"*",
"type_",
"*",
"or",
"None",
"if",
"not",
"present",
"."
] | python | train |
rameshg87/pyremotevbox | pyremotevbox/ZSI/address.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/address.py#L148-L194 | def setRequest(self, endPointReference, action):
'''Call For Request
'''
self._action = action
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
addressTo = self._addressTo
messageID = self._messageID = "uuid:%s" %time.time()
... | [
"def",
"setRequest",
"(",
"self",
",",
"endPointReference",
",",
"action",
")",
":",
"self",
".",
"_action",
"=",
"action",
"self",
".",
"header_pyobjs",
"=",
"None",
"pyobjs",
"=",
"[",
"]",
"namespaceURI",
"=",
"self",
".",
"wsAddressURI",
"addressTo",
"... | Call For Request | [
"Call",
"For",
"Request"
] | python | train |
python-diamond/Diamond | src/diamond/handler/g_metric.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/g_metric.py#L60-L72 | def get_default_config(self):
"""
Return the default config for the handler
"""
config = super(GmetricHandler, self).get_default_config()
config.update({
'host': 'localhost',
'port': 8651,
'protocol': 'udp',
})
return config | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"GmetricHandler",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'host'",
":",
"'localhost'",
",",
"'port'",
":",
"8651",
",",
"'... | Return the default config for the handler | [
"Return",
"the",
"default",
"config",
"for",
"the",
"handler"
] | python | train |
jazzband/django-axes | axes/attempts.py | https://github.com/jazzband/django-axes/blob/3e215a174030e43e7ab8c2a79c395eb0eeddc667/axes/attempts.py#L33-L42 | def filter_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet:
"""
Return a queryset of AccessAttempts that match the given request and credentials.
"""
username = get_client_username(request, credentials)
filter_kwargs = get_client_parameters(username, request.axes_ip_a... | [
"def",
"filter_user_attempts",
"(",
"request",
":",
"AxesHttpRequest",
",",
"credentials",
":",
"dict",
"=",
"None",
")",
"->",
"QuerySet",
":",
"username",
"=",
"get_client_username",
"(",
"request",
",",
"credentials",
")",
"filter_kwargs",
"=",
"get_client_para... | Return a queryset of AccessAttempts that match the given request and credentials. | [
"Return",
"a",
"queryset",
"of",
"AccessAttempts",
"that",
"match",
"the",
"given",
"request",
"and",
"credentials",
"."
] | python | train |
linkhub-sdk/popbill.py | popbill/messageService.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/messageService.py#L381-L395 | def getMessagesRN(self, CorpNum, RequestNum, UserID=None):
""" 문자 전송결과 조회
args
CorpNum : 팝빌회원 사업자번호
RequestNum : 전송요청시 할당한 전송요청번호
UserID : 팝빌회원 아이디
return
전송정보 as list
raise
PopbillExcept... | [
"def",
"getMessagesRN",
"(",
"self",
",",
"CorpNum",
",",
"RequestNum",
",",
"UserID",
"=",
"None",
")",
":",
"if",
"RequestNum",
"==",
"None",
"or",
"RequestNum",
"==",
"''",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"요청번호가 입력되지 않았습니다.\... | 문자 전송결과 조회
args
CorpNum : 팝빌회원 사업자번호
RequestNum : 전송요청시 할당한 전송요청번호
UserID : 팝빌회원 아이디
return
전송정보 as list
raise
PopbillException | [
"문자",
"전송결과",
"조회",
"args",
"CorpNum",
":",
"팝빌회원",
"사업자번호",
"RequestNum",
":",
"전송요청시",
"할당한",
"전송요청번호",
"UserID",
":",
"팝빌회원",
"아이디",
"return",
"전송정보",
"as",
"list",
"raise",
"PopbillException"
] | python | train |
yoeo/guesslang | tools/download_github_repo.py | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/download_github_repo.py#L117-L140 | def retry(default=None):
"""Retry functions after failures"""
def decorator(func):
"""Retry decorator"""
@functools.wraps(func)
def _wrapper(*args, **kw):
for pos in range(1, MAX_RETRIES):
try:
return func(*args, **kw)
exc... | [
"def",
"retry",
"(",
"default",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"Retry decorator\"\"\"",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"fo... | Retry functions after failures | [
"Retry",
"functions",
"after",
"failures"
] | python | train |
spyder-ide/spyder | spyder/widgets/tabs.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/tabs.py#L164-L168 | def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() == Qt.LeftButton:
self.__drag_start_pos = QPoint(event.pos())
QTabBar.mousePressEvent(self, event) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"button",
"(",
")",
"==",
"Qt",
".",
"LeftButton",
":",
"self",
".",
"__drag_start_pos",
"=",
"QPoint",
"(",
"event",
".",
"pos",
"(",
")",
")",
"QTabBar",
".",
"mouse... | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | python | train |
Rapptz/discord.py | discord/channel.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/channel.py#L725-L731 | def voice_channels(self):
"""List[:class:`VoiceChannel`]: Returns the voice channels that are under this category."""
ret = [c for c in self.guild.channels
if c.category_id == self.id
and isinstance(c, VoiceChannel)]
ret.sort(key=lambda c: (c.position, c.id))
retu... | [
"def",
"voice_channels",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"guild",
".",
"channels",
"if",
"c",
".",
"category_id",
"==",
"self",
".",
"id",
"and",
"isinstance",
"(",
"c",
",",
"VoiceChannel",
")",
"]",
"re... | List[:class:`VoiceChannel`]: Returns the voice channels that are under this category. | [
"List",
"[",
":",
"class",
":",
"VoiceChannel",
"]",
":",
"Returns",
"the",
"voice",
"channels",
"that",
"are",
"under",
"this",
"category",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/tasks.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L1681-L1693 | def communicate(self, input=None):
"""
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.
Wait for process to terminate. The optional input argument should be a string to be sent to the
child process, or None, if no data should be s... | [
"def",
"communicate",
"(",
"self",
",",
"input",
"=",
"None",
")",
":",
"stdoutdata",
",",
"stderrdata",
"=",
"self",
".",
"process",
".",
"communicate",
"(",
"input",
"=",
"input",
")",
"self",
".",
"_returncode",
"=",
"self",
".",
"process",
".",
"re... | Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.
Wait for process to terminate. The optional input argument should be a string to be sent to the
child process, or None, if no data should be sent to the child.
communicate() returns a tupl... | [
"Interact",
"with",
"process",
":",
"Send",
"data",
"to",
"stdin",
".",
"Read",
"data",
"from",
"stdout",
"and",
"stderr",
"until",
"end",
"-",
"of",
"-",
"file",
"is",
"reached",
".",
"Wait",
"for",
"process",
"to",
"terminate",
".",
"The",
"optional",
... | python | train |
gbiggs/rtsprofile | rtsprofile/utils.py | https://github.com/gbiggs/rtsprofile/blob/fded6eddcb0b25fe9808b1b12336a4413ea00905/rtsprofile/utils.py#L72-L81 | def indent_string(string, num_spaces=2):
'''Add indentation to a string.
Replaces all new lines in the string with a new line followed by the
specified number of spaces, and adds the specified number of spaces to the
start of the string.
'''
indent = ' '.ljust(num_spaces)
return indent + r... | [
"def",
"indent_string",
"(",
"string",
",",
"num_spaces",
"=",
"2",
")",
":",
"indent",
"=",
"' '",
".",
"ljust",
"(",
"num_spaces",
")",
"return",
"indent",
"+",
"re",
".",
"sub",
"(",
"'\\n'",
",",
"'\\n'",
"+",
"indent",
",",
"string",
")"
] | Add indentation to a string.
Replaces all new lines in the string with a new line followed by the
specified number of spaces, and adds the specified number of spaces to the
start of the string. | [
"Add",
"indentation",
"to",
"a",
"string",
"."
] | python | train |
google/mobly | mobly/logger.py | https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/logger.py#L35-L49 | def _parse_logline_timestamp(t):
"""Parses a logline timestamp into a tuple.
Args:
t: Timestamp in logline format.
Returns:
An iterable of date and time elements in the order of month, day, hour,
minute, second, microsecond.
"""
date, time = t.split(' ')
month, day = da... | [
"def",
"_parse_logline_timestamp",
"(",
"t",
")",
":",
"date",
",",
"time",
"=",
"t",
".",
"split",
"(",
"' '",
")",
"month",
",",
"day",
"=",
"date",
".",
"split",
"(",
"'-'",
")",
"h",
",",
"m",
",",
"s",
"=",
"time",
".",
"split",
"(",
"':'"... | Parses a logline timestamp into a tuple.
Args:
t: Timestamp in logline format.
Returns:
An iterable of date and time elements in the order of month, day, hour,
minute, second, microsecond. | [
"Parses",
"a",
"logline",
"timestamp",
"into",
"a",
"tuple",
"."
] | python | train |
ejhigson/nestcheck | nestcheck/plots.py | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/plots.py#L790-L815 | def average_by_key(dict_in, key):
"""Helper function for plot_run_nlive.
Try returning the average of dict_in[key] and, if this does not work or if
key is None, return average of whole dict.
Parameters
----------
dict_in: dict
Values should be arrays.
key: str
Returns
----... | [
"def",
"average_by_key",
"(",
"dict_in",
",",
"key",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"np",
".",
"mean",
"(",
"np",
".",
"concatenate",
"(",
"list",
"(",
"dict_in",
".",
"values",
"(",
")",
")",
")",
")",
"else",
":",
"try",
":... | Helper function for plot_run_nlive.
Try returning the average of dict_in[key] and, if this does not work or if
key is None, return average of whole dict.
Parameters
----------
dict_in: dict
Values should be arrays.
key: str
Returns
-------
average: float | [
"Helper",
"function",
"for",
"plot_run_nlive",
"."
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L6781-L6805 | def hrmint(xvals, yvals, x):
"""
Evaluate a Hermite interpolating polynomial at a specified
abscissa value.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/hrmint_c.html
:param xvals: Abscissa values.
:type xvals: Array of floats
:param yvals: Ordinate and derivative value... | [
"def",
"hrmint",
"(",
"xvals",
",",
"yvals",
",",
"x",
")",
":",
"work",
"=",
"stypes",
".",
"emptyDoubleVector",
"(",
"int",
"(",
"2",
"*",
"len",
"(",
"yvals",
")",
"+",
"1",
")",
")",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"len",
"(",
"xvals... | Evaluate a Hermite interpolating polynomial at a specified
abscissa value.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/hrmint_c.html
:param xvals: Abscissa values.
:type xvals: Array of floats
:param yvals: Ordinate and derivative values.
:type yvals: Array of floats
:... | [
"Evaluate",
"a",
"Hermite",
"interpolating",
"polynomial",
"at",
"a",
"specified",
"abscissa",
"value",
".",
"https",
":",
"//",
"naif",
".",
"jpl",
".",
"nasa",
".",
"gov",
"/",
"pub",
"/",
"naif",
"/",
"toolkit_docs",
"/",
"C",
"/",
"cspice",
"/",
"h... | python | train |
python-gitlab/python-gitlab | gitlab/base.py | https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/base.py#L128-L132 | def get_id(self):
"""Returns the id of the resource."""
if self._id_attr is None or not hasattr(self, self._id_attr):
return None
return getattr(self, self._id_attr) | [
"def",
"get_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"_id_attr",
"is",
"None",
"or",
"not",
"hasattr",
"(",
"self",
",",
"self",
".",
"_id_attr",
")",
":",
"return",
"None",
"return",
"getattr",
"(",
"self",
",",
"self",
".",
"_id_attr",
")"
] | Returns the id of the resource. | [
"Returns",
"the",
"id",
"of",
"the",
"resource",
"."
] | python | train |
numenta/htmresearch | htmresearch/regions/ApicalTMSequenceRegion.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ApicalTMSequenceRegion.py#L450-L459 | def setParameter(self, parameterName, index, parameterValue):
"""
Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explicitly handled here.
"""
if hasattr(self, parameterName):
setat... | [
"def",
"setParameter",
"(",
"self",
",",
"parameterName",
",",
"index",
",",
"parameterValue",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"parameterName",
")",
":",
"setattr",
"(",
"self",
",",
"parameterName",
",",
"parameterValue",
")",
"else",
":",
"r... | Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explicitly handled here. | [
"Set",
"the",
"value",
"of",
"a",
"Spec",
"parameter",
".",
"Most",
"parameters",
"are",
"handled",
"automatically",
"by",
"PyRegion",
"s",
"parameter",
"set",
"mechanism",
".",
"The",
"ones",
"that",
"need",
"special",
"treatment",
"are",
"explicitly",
"handl... | python | train |
log2timeline/dftimewolf | dftimewolf/lib/containers/interface.py | https://github.com/log2timeline/dftimewolf/blob/45f898476a288d73c4256ae8e3836a2a4848c0d7/dftimewolf/lib/containers/interface.py#L65-L77 | def get_attribute_names(self):
"""Retrieves the names of all attributes.
Returns:
list[str]: attribute names.
"""
attribute_names = []
for attribute_name in iter(self.__dict__.keys()):
# Not using startswith to improve performance.
if attribute_name[0] == '_':
continue
... | [
"def",
"get_attribute_names",
"(",
"self",
")",
":",
"attribute_names",
"=",
"[",
"]",
"for",
"attribute_name",
"in",
"iter",
"(",
"self",
".",
"__dict__",
".",
"keys",
"(",
")",
")",
":",
"# Not using startswith to improve performance.",
"if",
"attribute_name",
... | Retrieves the names of all attributes.
Returns:
list[str]: attribute names. | [
"Retrieves",
"the",
"names",
"of",
"all",
"attributes",
".",
"Returns",
":",
"list",
"[",
"str",
"]",
":",
"attribute",
"names",
"."
] | python | train |
F483/btctxstore | btctxstore/api.py | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L282-L285 | def retrieve_data_blob(self, txid):
"""TODO add docstring"""
rawtx = self.retrieve_tx(txid)
return self.get_data_blob(rawtx) | [
"def",
"retrieve_data_blob",
"(",
"self",
",",
"txid",
")",
":",
"rawtx",
"=",
"self",
".",
"retrieve_tx",
"(",
"txid",
")",
"return",
"self",
".",
"get_data_blob",
"(",
"rawtx",
")"
] | TODO add docstring | [
"TODO",
"add",
"docstring"
] | python | train |
saltstack/salt | salt/states/rbenv.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rbenv.py#L150-L172 | def _check_and_uninstall_ruby(ret, ruby, user=None):
'''
Verify that ruby is uninstalled
'''
ret = _ruby_installed(ret, ruby, user=user)
if ret['result']:
if ret['default']:
__salt__['rbenv.default']('system', runas=user)
if __salt__['rbenv.uninstall_ruby'](ruby, runas=u... | [
"def",
"_check_and_uninstall_ruby",
"(",
"ret",
",",
"ruby",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"_ruby_installed",
"(",
"ret",
",",
"ruby",
",",
"user",
"=",
"user",
")",
"if",
"ret",
"[",
"'result'",
"]",
":",
"if",
"ret",
"[",
"'defaul... | Verify that ruby is uninstalled | [
"Verify",
"that",
"ruby",
"is",
"uninstalled"
] | python | train |
edx/edx-drf-extensions | edx_rest_framework_extensions/auth/jwt/middleware.py | https://github.com/edx/edx-drf-extensions/blob/2f4c1682b8471bf894ea566a43fd9f91ba219f83/edx_rest_framework_extensions/auth/jwt/middleware.py#L28-L34 | def _includes_base_class(self, iter_classes, base_class):
"""
Returns whether any class in iter_class is a subclass of the given base_class.
"""
return any(
issubclass(auth_class, base_class) for auth_class in iter_classes,
) | [
"def",
"_includes_base_class",
"(",
"self",
",",
"iter_classes",
",",
"base_class",
")",
":",
"return",
"any",
"(",
"issubclass",
"(",
"auth_class",
",",
"base_class",
")",
"for",
"auth_class",
"in",
"iter_classes",
",",
")"
] | Returns whether any class in iter_class is a subclass of the given base_class. | [
"Returns",
"whether",
"any",
"class",
"in",
"iter_class",
"is",
"a",
"subclass",
"of",
"the",
"given",
"base_class",
"."
] | python | train |
ARMmbed/yotta | yotta/lib/registry_access.py | https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/registry_access.py#L455-L477 | def createFromSource(cls, vs, name, registry):
''' returns a registry component for anything that's a valid package
name (this does not guarantee that the component actually exists in
the registry: use availableVersions() for that).
'''
# we deliberately allow only lowerc... | [
"def",
"createFromSource",
"(",
"cls",
",",
"vs",
",",
"name",
",",
"registry",
")",
":",
"# we deliberately allow only lowercase, hyphen, and (unfortunately)",
"# numbers in package names, to reduce the possibility of confusingly",
"# similar names: if the name doesn't match this then e... | returns a registry component for anything that's a valid package
name (this does not guarantee that the component actually exists in
the registry: use availableVersions() for that). | [
"returns",
"a",
"registry",
"component",
"for",
"anything",
"that",
"s",
"a",
"valid",
"package",
"name",
"(",
"this",
"does",
"not",
"guarantee",
"that",
"the",
"component",
"actually",
"exists",
"in",
"the",
"registry",
":",
"use",
"availableVersions",
"()",... | python | valid |
flatangle/flatlib | flatlib/datetime.py | https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L129-L138 | def time(self):
""" Returns time as list [hh,mm,ss]. """
slist = self.toList()
if slist[0] == '-':
slist[1] *= -1
# We must do a trick if we want to
# make negative zeros explicit
if slist[1] == -0:
slist[1] = -0.0
return s... | [
"def",
"time",
"(",
"self",
")",
":",
"slist",
"=",
"self",
".",
"toList",
"(",
")",
"if",
"slist",
"[",
"0",
"]",
"==",
"'-'",
":",
"slist",
"[",
"1",
"]",
"*=",
"-",
"1",
"# We must do a trick if we want to ",
"# make negative zeros explicit",
"if",
"s... | Returns time as list [hh,mm,ss]. | [
"Returns",
"time",
"as",
"list",
"[",
"hh",
"mm",
"ss",
"]",
"."
] | python | train |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1499-L1506 | def makePath(x_path, y_path, epsilon=1.e-10):
"""
Create closed path.
"""
x_path_closed = np.concatenate([x_path, x_path[::-1]])
y_path_closed = np.concatenate([y_path, epsilon + y_path[::-1]])
path = matplotlib.path.Path(list(zip(x_path_closed, y_path_closed)))
return path | [
"def",
"makePath",
"(",
"x_path",
",",
"y_path",
",",
"epsilon",
"=",
"1.e-10",
")",
":",
"x_path_closed",
"=",
"np",
".",
"concatenate",
"(",
"[",
"x_path",
",",
"x_path",
"[",
":",
":",
"-",
"1",
"]",
"]",
")",
"y_path_closed",
"=",
"np",
".",
"c... | Create closed path. | [
"Create",
"closed",
"path",
"."
] | python | train |
inveniosoftware/invenio-oauthclient | invenio_oauthclient/handlers.py | https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/handlers.py#L202-L211 | def token_delete(remote, token=''):
"""Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token.
"""
session_key = t... | [
"def",
"token_delete",
"(",
"remote",
",",
"token",
"=",
"''",
")",
":",
"session_key",
"=",
"token_session_key",
"(",
"remote",
".",
"name",
")",
"return",
"session",
".",
"pop",
"(",
"session_key",
",",
"None",
")"
] | Remove OAuth access tokens from session.
:param remote: The remote application.
:param token: Type of token to get. Data passed from ``oauth.request()`` to
identify which token to retrieve. (Default: ``''``)
:returns: The token. | [
"Remove",
"OAuth",
"access",
"tokens",
"from",
"session",
"."
] | python | train |
pyamg/pyamg | pyamg/util/BSR_utils.py | https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/util/BSR_utils.py#L9-L61 | def BSR_Get_Row(A, i):
"""Return row i in BSR matrix A.
Only nonzero entries are returned
Parameters
----------
A : bsr_matrix
Input matrix
i : int
Row number
Returns
-------
z : array
Actual nonzero values for row i colindx Array of column indices for the
... | [
"def",
"BSR_Get_Row",
"(",
"A",
",",
"i",
")",
":",
"blocksize",
"=",
"A",
".",
"blocksize",
"[",
"0",
"]",
"BlockIndx",
"=",
"int",
"(",
"i",
"/",
"blocksize",
")",
"rowstart",
"=",
"A",
".",
"indptr",
"[",
"BlockIndx",
"]",
"rowend",
"=",
"A",
... | Return row i in BSR matrix A.
Only nonzero entries are returned
Parameters
----------
A : bsr_matrix
Input matrix
i : int
Row number
Returns
-------
z : array
Actual nonzero values for row i colindx Array of column indices for the
nonzeros of row i
... | [
"Return",
"row",
"i",
"in",
"BSR",
"matrix",
"A",
"."
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L8453-L8468 | def remove_shared_folder(self, name):
"""Removes the global shared folder with the given name previously
created by :py:func:`create_shared_folder` from the collection of
shared folders and stops sharing it.
In the current implementation, this operation is not
implement... | [
"def",
"remove_shared_folder",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type basestring\"",
")",
"self",
".",
"_call",
"(",
"\"removeShare... | Removes the global shared folder with the given name previously
created by :py:func:`create_shared_folder` from the collection of
shared folders and stops sharing it.
In the current implementation, this operation is not
implemented.
in name of type str
Logi... | [
"Removes",
"the",
"global",
"shared",
"folder",
"with",
"the",
"given",
"name",
"previously",
"created",
"by",
":",
"py",
":",
"func",
":",
"create_shared_folder",
"from",
"the",
"collection",
"of",
"shared",
"folders",
"and",
"stops",
"sharing",
"it",
".",
... | python | train |
ssalentin/plip | plip/modules/report.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L275-L281 | def write_section(self, name, features, info, f):
"""Provides formatting for one section (e.g. hydrogen bonds)"""
if not len(info) == 0:
f.write('\n\n### %s ###\n' % name)
f.write('%s\n' % '\t'.join(features))
for line in info:
f.write('%s\n' % '\t'.jo... | [
"def",
"write_section",
"(",
"self",
",",
"name",
",",
"features",
",",
"info",
",",
"f",
")",
":",
"if",
"not",
"len",
"(",
"info",
")",
"==",
"0",
":",
"f",
".",
"write",
"(",
"'\\n\\n### %s ###\\n'",
"%",
"name",
")",
"f",
".",
"write",
"(",
"... | Provides formatting for one section (e.g. hydrogen bonds) | [
"Provides",
"formatting",
"for",
"one",
"section",
"(",
"e",
".",
"g",
".",
"hydrogen",
"bonds",
")"
] | python | train |
Robpol86/colorclass | colorclass/color.py | https://github.com/Robpol86/colorclass/blob/692e2d6f5ad470b6221c8cb9641970dc5563a572/colorclass/color.py#L187-L196 | def bgcyan(cls, string, auto=False):
"""Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
"""
return cls.colorize('bgcyan', stri... | [
"def",
"bgcyan",
"(",
"cls",
",",
"string",
",",
"auto",
"=",
"False",
")",
":",
"return",
"cls",
".",
"colorize",
"(",
"'bgcyan'",
",",
"string",
",",
"auto",
"=",
"auto",
")"
] | Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color | [
"Color",
"-",
"code",
"entire",
"string",
"."
] | python | train |
nickmckay/LiPD-utilities | Matlab/bagit.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L353-L364 | def validate(self, processes=1, fast=False):
"""Checks the structure and contents are valid. If you supply
the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and
accounted for, instead of re-calculating fixities and
comp... | [
"def",
"validate",
"(",
"self",
",",
"processes",
"=",
"1",
",",
"fast",
"=",
"False",
")",
":",
"self",
".",
"_validate_structure",
"(",
")",
"self",
".",
"_validate_bagittxt",
"(",
")",
"self",
".",
"_validate_contents",
"(",
"processes",
"=",
"processes... | Checks the structure and contents are valid. If you supply
the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and
accounted for, instead of re-calculating fixities and
comparing them against the manifest. By default validate()
... | [
"Checks",
"the",
"structure",
"and",
"contents",
"are",
"valid",
".",
"If",
"you",
"supply",
"the",
"parameter",
"fast",
"=",
"True",
"the",
"Payload",
"-",
"Oxum",
"(",
"if",
"present",
")",
"will",
"be",
"used",
"to",
"check",
"that",
"the",
"payload",... | python | train |
tornadoweb/tornado | tornado/iostream.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L817-L837 | def _try_inline_read(self) -> None:
"""Attempt to complete the current read operation from buffered data.
If the read can be completed without blocking, schedules the
read callback on the next IOLoop iteration; otherwise starts
listening for reads on the socket.
"""
# Se... | [
"def",
"_try_inline_read",
"(",
"self",
")",
"->",
"None",
":",
"# See if we've already got the data from a previous read",
"pos",
"=",
"self",
".",
"_find_read_pos",
"(",
")",
"if",
"pos",
"is",
"not",
"None",
":",
"self",
".",
"_read_from_buffer",
"(",
"pos",
... | Attempt to complete the current read operation from buffered data.
If the read can be completed without blocking, schedules the
read callback on the next IOLoop iteration; otherwise starts
listening for reads on the socket. | [
"Attempt",
"to",
"complete",
"the",
"current",
"read",
"operation",
"from",
"buffered",
"data",
"."
] | python | train |
05bit/peewee-async | peewee_async.py | https://github.com/05bit/peewee-async/blob/d15f4629da1d9975da4ec37306188e68d288c862/peewee_async.py#L1496-L1511 | def get_data(self, create=False):
"""Get dict stored for current running task. Return `None`
or an empty dict if no data was found depending on the
`create` argument value.
:param create: if argument is `True`, create empty dict
for task, default: `False`
... | [
"def",
"get_data",
"(",
"self",
",",
"create",
"=",
"False",
")",
":",
"task",
"=",
"asyncio_current_task",
"(",
"loop",
"=",
"self",
".",
"loop",
")",
"if",
"task",
":",
"task_id",
"=",
"id",
"(",
"task",
")",
"if",
"create",
"and",
"task_id",
"not"... | Get dict stored for current running task. Return `None`
or an empty dict if no data was found depending on the
`create` argument value.
:param create: if argument is `True`, create empty dict
for task, default: `False` | [
"Get",
"dict",
"stored",
"for",
"current",
"running",
"task",
".",
"Return",
"None",
"or",
"an",
"empty",
"dict",
"if",
"no",
"data",
"was",
"found",
"depending",
"on",
"the",
"create",
"argument",
"value",
"."
] | python | train |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L211-L234 | def mode(self, mode):
"""Set the operation mode."""
_LOGGER.debug("Setting new mode: %s", mode)
if self.mode == Mode.Boost and mode != Mode.Boost:
self.boost = False
if mode == Mode.Boost:
self.boost = True
return
elif mode == Mode.Away:
... | [
"def",
"mode",
"(",
"self",
",",
"mode",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting new mode: %s\"",
",",
"mode",
")",
"if",
"self",
".",
"mode",
"==",
"Mode",
".",
"Boost",
"and",
"mode",
"!=",
"Mode",
".",
"Boost",
":",
"self",
".",
"boost"... | Set the operation mode. | [
"Set",
"the",
"operation",
"mode",
"."
] | python | train |
tcalmant/ipopo | pelix/ipopo/core.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L597-L604 | def _unregister_all_factories(self):
"""
Unregisters all factories. This method should be called only after the
iPOPO service has been unregistered (that's why it's not locked)
"""
factories = list(self.__factories.keys())
for factory_name in factories:
self.u... | [
"def",
"_unregister_all_factories",
"(",
"self",
")",
":",
"factories",
"=",
"list",
"(",
"self",
".",
"__factories",
".",
"keys",
"(",
")",
")",
"for",
"factory_name",
"in",
"factories",
":",
"self",
".",
"unregister_factory",
"(",
"factory_name",
")"
] | Unregisters all factories. This method should be called only after the
iPOPO service has been unregistered (that's why it's not locked) | [
"Unregisters",
"all",
"factories",
".",
"This",
"method",
"should",
"be",
"called",
"only",
"after",
"the",
"iPOPO",
"service",
"has",
"been",
"unregistered",
"(",
"that",
"s",
"why",
"it",
"s",
"not",
"locked",
")"
] | python | train |
defunkt/pystache | pystache/renderer.py | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/renderer.py#L347-L367 | def _render_object(self, obj, *context, **kwargs):
"""
Render the template associated with the given object.
"""
loader = self._make_loader()
# TODO: consider an approach that does not require using an if
# block here. For example, perhaps this class's loader can be
... | [
"def",
"_render_object",
"(",
"self",
",",
"obj",
",",
"*",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"loader",
"=",
"self",
".",
"_make_loader",
"(",
")",
"# TODO: consider an approach that does not require using an if",
"# block here. For example, perhaps this ... | Render the template associated with the given object. | [
"Render",
"the",
"template",
"associated",
"with",
"the",
"given",
"object",
"."
] | python | train |
makearl/tornado-profile | tornado_profile.py | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L204-L210 | def post(self):
"""Start a new profiler."""
CProfileWrapper.profiler = cProfile.Profile()
CProfileWrapper.profiler.enable()
self.running = True
self.set_status(201)
self.finish() | [
"def",
"post",
"(",
"self",
")",
":",
"CProfileWrapper",
".",
"profiler",
"=",
"cProfile",
".",
"Profile",
"(",
")",
"CProfileWrapper",
".",
"profiler",
".",
"enable",
"(",
")",
"self",
".",
"running",
"=",
"True",
"self",
".",
"set_status",
"(",
"201",
... | Start a new profiler. | [
"Start",
"a",
"new",
"profiler",
"."
] | python | test |
kentik/kentikapi-py | kentikapi/v5/tagging.py | https://github.com/kentik/kentikapi-py/blob/aa94c0b7eaf88409818b97967d7293e309e11bab/kentikapi/v5/tagging.py#L51-L105 | def parts(self):
"""Return an array of batch parts to submit"""
parts = []
upserts = dict()
deletes = []
# we keep track of the batch size as we go (pretty close approximation!) so we can chunk it small enough
# to limit the HTTP posts to under 700KB - server limits to... | [
"def",
"parts",
"(",
"self",
")",
":",
"parts",
"=",
"[",
"]",
"upserts",
"=",
"dict",
"(",
")",
"deletes",
"=",
"[",
"]",
"# we keep track of the batch size as we go (pretty close approximation!) so we can chunk it small enough",
"# to limit the HTTP posts to under 700KB - s... | Return an array of batch parts to submit | [
"Return",
"an",
"array",
"of",
"batch",
"parts",
"to",
"submit"
] | python | train |
Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L367-L393 | def handle_trial_end(self, data):
"""
Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
event: the job's state
hyper_params: the hyperparameters (a str... | [
"def",
"handle_trial_end",
"(",
"self",
",",
"data",
")",
":",
"hyper_params",
"=",
"json_tricks",
".",
"loads",
"(",
"data",
"[",
"'hyper_params'",
"]",
")",
"bracket_id",
",",
"i",
",",
"_",
"=",
"hyper_params",
"[",
"'parameter_id'",
"]",
".",
"split",
... | Parameters
----------
data: dict()
it has three keys: trial_job_id, event, hyper_params
trial_job_id: the id generated by training service
event: the job's state
hyper_params: the hyperparameters (a string) generated and returned by tuner | [
"Parameters",
"----------",
"data",
":",
"dict",
"()",
"it",
"has",
"three",
"keys",
":",
"trial_job_id",
"event",
"hyper_params",
"trial_job_id",
":",
"the",
"id",
"generated",
"by",
"training",
"service",
"event",
":",
"the",
"job",
"s",
"state",
"hyper_para... | python | train |
bspaans/python-mingus | mingus/core/chords.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/chords.py#L390-L398 | def eleventh(note):
"""Build an eleventh chord on note.
Example:
>>> eleventh('C')
['C', 'G', 'Bb', 'F']
"""
return [note, intervals.perfect_fifth(note), intervals.minor_seventh(note),
intervals.perfect_fourth(note)] | [
"def",
"eleventh",
"(",
"note",
")",
":",
"return",
"[",
"note",
",",
"intervals",
".",
"perfect_fifth",
"(",
"note",
")",
",",
"intervals",
".",
"minor_seventh",
"(",
"note",
")",
",",
"intervals",
".",
"perfect_fourth",
"(",
"note",
")",
"]"
] | Build an eleventh chord on note.
Example:
>>> eleventh('C')
['C', 'G', 'Bb', 'F'] | [
"Build",
"an",
"eleventh",
"chord",
"on",
"note",
"."
] | python | train |
LonamiWebs/Telethon | telethon/client/downloads.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/downloads.py#L192-L318 | async def download_file(
self, input_location, file=None, *, part_size_kb=None,
file_size=None, progress_callback=None, dc_id=None):
"""
Downloads the given input location to a file.
Args:
input_location (:tl:`InputFileLocation`):
The file loc... | [
"async",
"def",
"download_file",
"(",
"self",
",",
"input_location",
",",
"file",
"=",
"None",
",",
"*",
",",
"part_size_kb",
"=",
"None",
",",
"file_size",
"=",
"None",
",",
"progress_callback",
"=",
"None",
",",
"dc_id",
"=",
"None",
")",
":",
"if",
... | Downloads the given input location to a file.
Args:
input_location (:tl:`InputFileLocation`):
The file location from which the file will be downloaded.
See `telethon.utils.get_input_location` source for a complete
list of supported types.
... | [
"Downloads",
"the",
"given",
"input",
"location",
"to",
"a",
"file",
"."
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/evaluation.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/evaluation.py#L337-L372 | def confusion_matrix(targets, predictions):
r"""
Compute the confusion matrix for classifier predictions.
Parameters
----------
targets : SArray
Ground truth class labels (cannot be of type float).
predictions : SArray
The prediction that corresponds to each target value.
... | [
"def",
"confusion_matrix",
"(",
"targets",
",",
"predictions",
")",
":",
"_supervised_evaluation_error_checking",
"(",
"targets",
",",
"predictions",
")",
"_check_same_type_not_float",
"(",
"targets",
",",
"predictions",
")",
"return",
"_turicreate",
".",
"extensions",
... | r"""
Compute the confusion matrix for classifier predictions.
Parameters
----------
targets : SArray
Ground truth class labels (cannot be of type float).
predictions : SArray
The prediction that corresponds to each target value.
This vector must have the same length as ``ta... | [
"r",
"Compute",
"the",
"confusion",
"matrix",
"for",
"classifier",
"predictions",
"."
] | python | train |
mikedh/trimesh | trimesh/scene/scene.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/scene/scene.py#L740-L777 | def explode(self, vector=None, origin=None):
"""
Explode a scene around a point and vector.
Parameters
-----------
vector : (3,) float or float
Explode radially around a direction vector or spherically
origin : (3,) float
Point to explode around
... | [
"def",
"explode",
"(",
"self",
",",
"vector",
"=",
"None",
",",
"origin",
"=",
"None",
")",
":",
"if",
"origin",
"is",
"None",
":",
"origin",
"=",
"self",
".",
"centroid",
"if",
"vector",
"is",
"None",
":",
"vector",
"=",
"self",
".",
"scale",
"/",... | Explode a scene around a point and vector.
Parameters
-----------
vector : (3,) float or float
Explode radially around a direction vector or spherically
origin : (3,) float
Point to explode around | [
"Explode",
"a",
"scene",
"around",
"a",
"point",
"and",
"vector",
"."
] | python | train |
dadadel/pyment | pyment/docstring.py | https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L411-L437 | def get_raw_not_managed(self, data):
"""Get elements not managed. They can be used as is.
:param data: the data to proceed
"""
keys = ['also', 'ref', 'note', 'other', 'example', 'method', 'attr']
elems = [self.opt[k] for k in self.opt if k in keys]
data = data.splitline... | [
"def",
"get_raw_not_managed",
"(",
"self",
",",
"data",
")",
":",
"keys",
"=",
"[",
"'also'",
",",
"'ref'",
",",
"'note'",
",",
"'other'",
",",
"'example'",
",",
"'method'",
",",
"'attr'",
"]",
"elems",
"=",
"[",
"self",
".",
"opt",
"[",
"k",
"]",
... | Get elements not managed. They can be used as is.
:param data: the data to proceed | [
"Get",
"elements",
"not",
"managed",
".",
"They",
"can",
"be",
"used",
"as",
"is",
"."
] | python | train |
productml/blurr | blurr/core/base.py | https://github.com/productml/blurr/blob/1b688b2c4a9bbbb2139c58bf0682ddc05a6c24fa/blurr/core/base.py#L78-L82 | def validate_enum_attribute(self, attribute: str,
candidates: Set[Union[str, int, float]]) -> None:
""" Validates that the attribute value is among the candidates """
self.add_errors(
validate_enum_attribute(self.fully_qualified_name, self._spec, attribute, ca... | [
"def",
"validate_enum_attribute",
"(",
"self",
",",
"attribute",
":",
"str",
",",
"candidates",
":",
"Set",
"[",
"Union",
"[",
"str",
",",
"int",
",",
"float",
"]",
"]",
")",
"->",
"None",
":",
"self",
".",
"add_errors",
"(",
"validate_enum_attribute",
"... | Validates that the attribute value is among the candidates | [
"Validates",
"that",
"the",
"attribute",
"value",
"is",
"among",
"the",
"candidates"
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/outgoing_caller_id.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/outgoing_caller_id.py#L141-L150 | def get(self, sid):
"""
Constructs a OutgoingCallerIdContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdCo... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"OutgoingCallerIdContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | Constructs a OutgoingCallerIdContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdContext | [
"Constructs",
"a",
"OutgoingCallerIdContext"
] | python | train |
BlueBrain/NeuroM | neurom/io/neurolucida.py | https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/neurolucida.py#L260-L275 | def read(morph_file, data_wrapper=DataWrapper):
'''return a 'raw_data' np.array with the full neuron, and the format of the file
suitable to be wrapped by DataWrapper
'''
msg = ('This is an experimental reader. '
'There are no guarantees regarding ability to parse '
'Neurolucida .... | [
"def",
"read",
"(",
"morph_file",
",",
"data_wrapper",
"=",
"DataWrapper",
")",
":",
"msg",
"=",
"(",
"'This is an experimental reader. '",
"'There are no guarantees regarding ability to parse '",
"'Neurolucida .asc files or correctness of output.'",
")",
"warnings",
".",
"warn... | return a 'raw_data' np.array with the full neuron, and the format of the file
suitable to be wrapped by DataWrapper | [
"return",
"a",
"raw_data",
"np",
".",
"array",
"with",
"the",
"full",
"neuron",
"and",
"the",
"format",
"of",
"the",
"file",
"suitable",
"to",
"be",
"wrapped",
"by",
"DataWrapper"
] | python | train |
blockstack/virtualchain | virtualchain/lib/indexer.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/indexer.py#L1244-L1340 | def process_ops(self, block_id, ops):
"""
Given a transaction-ordered sequence of parsed operations,
check their validity and give them to the state engine to
affect state changes.
It calls 'db_check' to validate each operation, and 'db_commit'
to add it to the state en... | [
"def",
"process_ops",
"(",
"self",
",",
"block_id",
",",
"ops",
")",
":",
"new_ops",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"op",
"in",
"self",
".",
"opcodes",
":",
"new_ops",
"[",
"op",
"]",
"=",
"[",
"]",
"# transaction-ordered listing of accepted ... | Given a transaction-ordered sequence of parsed operations,
check their validity and give them to the state engine to
affect state changes.
It calls 'db_check' to validate each operation, and 'db_commit'
to add it to the state engine. Gets back a list of state
transitions (ops)... | [
"Given",
"a",
"transaction",
"-",
"ordered",
"sequence",
"of",
"parsed",
"operations",
"check",
"their",
"validity",
"and",
"give",
"them",
"to",
"the",
"state",
"engine",
"to",
"affect",
"state",
"changes",
"."
] | python | train |
common-workflow-language/cwltool | cwltool/process.py | https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/process.py#L383-L402 | def avroize_type(field_type, name_prefix=""):
# type: (Union[List[Dict[Text, Any]], Dict[Text, Any]], Text) -> Any
"""
adds missing information to a type so that CWL types are valid in schema_salad.
"""
if isinstance(field_type, MutableSequence):
for field in field_type:
avroize_... | [
"def",
"avroize_type",
"(",
"field_type",
",",
"name_prefix",
"=",
"\"\"",
")",
":",
"# type: (Union[List[Dict[Text, Any]], Dict[Text, Any]], Text) -> Any",
"if",
"isinstance",
"(",
"field_type",
",",
"MutableSequence",
")",
":",
"for",
"field",
"in",
"field_type",
":",... | adds missing information to a type so that CWL types are valid in schema_salad. | [
"adds",
"missing",
"information",
"to",
"a",
"type",
"so",
"that",
"CWL",
"types",
"are",
"valid",
"in",
"schema_salad",
"."
] | python | train |
mgedmin/check-manifest | check_manifest.py | https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L649-L659 | def read_manifest():
"""Read existing configuration from MANIFEST.in.
We use that to ignore anything the MANIFEST.in ignores.
"""
# XXX modifies global state, which is kind of evil
if not os.path.isfile('MANIFEST.in'):
return
ignore, ignore_regexps = _get_ignore_from_manifest('MANIFEST.... | [
"def",
"read_manifest",
"(",
")",
":",
"# XXX modifies global state, which is kind of evil",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"'MANIFEST.in'",
")",
":",
"return",
"ignore",
",",
"ignore_regexps",
"=",
"_get_ignore_from_manifest",
"(",
"'MANIFEST.in'... | Read existing configuration from MANIFEST.in.
We use that to ignore anything the MANIFEST.in ignores. | [
"Read",
"existing",
"configuration",
"from",
"MANIFEST",
".",
"in",
"."
] | python | train |
econ-ark/HARK | HARK/ConsumptionSaving/ConsPrefShockModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsPrefShockModel.py#L395-L457 | def solveConsPrefShock(solution_next,IncomeDstn,PrefShkDstn,
LivPrb,DiscFac,CRRA,Rfree,PermGroFac,BoroCnstArt,
aXtraGrid,vFuncBool,CubicBool):
'''
Solves a single period of a consumption-saving model with preference shocks
to marginal utility. Problem is solved... | [
"def",
"solveConsPrefShock",
"(",
"solution_next",
",",
"IncomeDstn",
",",
"PrefShkDstn",
",",
"LivPrb",
",",
"DiscFac",
",",
"CRRA",
",",
"Rfree",
",",
"PermGroFac",
",",
"BoroCnstArt",
",",
"aXtraGrid",
",",
"vFuncBool",
",",
"CubicBool",
")",
":",
"solver",... | Solves a single period of a consumption-saving model with preference shocks
to marginal utility. Problem is solved using the method of endogenous gridpoints.
Parameters
----------
solution_next : ConsumerSolution
The solution to the succeeding one period problem.
IncomeDstn : [np.array]
... | [
"Solves",
"a",
"single",
"period",
"of",
"a",
"consumption",
"-",
"saving",
"model",
"with",
"preference",
"shocks",
"to",
"marginal",
"utility",
".",
"Problem",
"is",
"solved",
"using",
"the",
"method",
"of",
"endogenous",
"gridpoints",
"."
] | python | train |
F5Networks/f5-common-python | f5/utils/decorators.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/decorators.py#L28-L47 | def poll_for_exceptionless_callable(callable, attempts, interval):
'''Poll with a given callable for a specified number of times.
:param callable: callable to invoke in loop -- if no exception is raised
the call is considered succeeded
:param attempts: number of iterations to attempt
... | [
"def",
"poll_for_exceptionless_callable",
"(",
"callable",
",",
"attempts",
",",
"interval",
")",
":",
"@",
"wraps",
"(",
"callable",
")",
"def",
"poll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"attempt",
"in",
"range",
"(",
"attempts... | Poll with a given callable for a specified number of times.
:param callable: callable to invoke in loop -- if no exception is raised
the call is considered succeeded
:param attempts: number of iterations to attempt
:param interval: seconds to wait before next attempt | [
"Poll",
"with",
"a",
"given",
"callable",
"for",
"a",
"specified",
"number",
"of",
"times",
"."
] | python | train |
jtwhite79/pyemu | pyemu/pst/pst_controldata.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/pst/pst_controldata.py#L356-L364 | def formatted_values(self):
""" list the entries and current values in the control data section
Returns
-------
formatted_values : pandas.Series
"""
return self._df.apply(lambda x: self.formatters[x["type"]](x["value"]),axis=1) | [
"def",
"formatted_values",
"(",
"self",
")",
":",
"return",
"self",
".",
"_df",
".",
"apply",
"(",
"lambda",
"x",
":",
"self",
".",
"formatters",
"[",
"x",
"[",
"\"type\"",
"]",
"]",
"(",
"x",
"[",
"\"value\"",
"]",
")",
",",
"axis",
"=",
"1",
")... | list the entries and current values in the control data section
Returns
-------
formatted_values : pandas.Series | [
"list",
"the",
"entries",
"and",
"current",
"values",
"in",
"the",
"control",
"data",
"section"
] | python | train |
ungarj/mapchete | mapchete/tile.py | https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/tile.py#L102-L117 | def tiles_from_geom(self, geometry, zoom):
"""
Return all tiles intersecting with input geometry.
Parameters
----------
geometry : ``shapely.geometry``
zoom : integer
zoom level
Yields
------
intersecting tiles : ``BufferedTile``
... | [
"def",
"tiles_from_geom",
"(",
"self",
",",
"geometry",
",",
"zoom",
")",
":",
"for",
"tile",
"in",
"self",
".",
"tile_pyramid",
".",
"tiles_from_geom",
"(",
"geometry",
",",
"zoom",
")",
":",
"yield",
"self",
".",
"tile",
"(",
"*",
"tile",
".",
"id",
... | Return all tiles intersecting with input geometry.
Parameters
----------
geometry : ``shapely.geometry``
zoom : integer
zoom level
Yields
------
intersecting tiles : ``BufferedTile`` | [
"Return",
"all",
"tiles",
"intersecting",
"with",
"input",
"geometry",
"."
] | python | valid |
mikedh/trimesh | trimesh/grouping.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/grouping.py#L595-L635 | def group_distance(values, distance):
"""
Find groups of points which have neighbours closer than radius,
where no two points in a group are farther than distance apart.
Parameters
---------
points : (n, d) float
Points of dimension d
distance : float
Max distance between ... | [
"def",
"group_distance",
"(",
"values",
",",
"distance",
")",
":",
"values",
"=",
"np",
".",
"asanyarray",
"(",
"values",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"consumed",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"values",
")",
",",
"dtype",... | Find groups of points which have neighbours closer than radius,
where no two points in a group are farther than distance apart.
Parameters
---------
points : (n, d) float
Points of dimension d
distance : float
Max distance between points in a cluster
Returns
----------
... | [
"Find",
"groups",
"of",
"points",
"which",
"have",
"neighbours",
"closer",
"than",
"radius",
"where",
"no",
"two",
"points",
"in",
"a",
"group",
"are",
"farther",
"than",
"distance",
"apart",
"."
] | python | train |
qubell/contrib-python-qubell-client | qubell/cli/__main__.py | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/cli/__main__.py#L1210-L1226 | def show_account():
"""
Exports current account configuration in
shell-friendly form. Takes into account
explicit top-level flags like --organization.
"""
click.echo("# tonomi api")
for (key, env) in REVERSE_MAPPING.items():
value = QUBELL.get(key, None)
if value:
... | [
"def",
"show_account",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"# tonomi api\"",
")",
"for",
"(",
"key",
",",
"env",
")",
"in",
"REVERSE_MAPPING",
".",
"items",
"(",
")",
":",
"value",
"=",
"QUBELL",
".",
"get",
"(",
"key",
",",
"None",
")",
"i... | Exports current account configuration in
shell-friendly form. Takes into account
explicit top-level flags like --organization. | [
"Exports",
"current",
"account",
"configuration",
"in",
"shell",
"-",
"friendly",
"form",
".",
"Takes",
"into",
"account",
"explicit",
"top",
"-",
"level",
"flags",
"like",
"--",
"organization",
"."
] | python | train |
presslabs/django-payu-ro | payu/forms.py | https://github.com/presslabs/django-payu-ro/blob/fda9432c57cee7a78789873b6e6f439d912e4c7b/payu/forms.py#L143-L224 | def signature(self):
"""
Compute the ORDER_HASH of the request.
The hashable string is composed by getting the values from:
MERCHANT
ORDER_REF
ORDER_DATE
ORDER_PNAME[]
ORDER_PCODE[]
ORDER_PINFO[]
ORDER_PRICE[]
... | [
"def",
"signature",
"(",
"self",
")",
":",
"hashable_fields",
"=",
"[",
"'MERCHANT'",
",",
"'ORDER_REF'",
",",
"'ORDER_DATE'",
",",
"'ORDER_SHIPPING'",
",",
"'PRICES_CURRENCY'",
",",
"'DISCOUNT'",
",",
"'DESTINATION_CITY'",
",",
"'DESTINATION_STATE'",
",",
"'DESTINA... | Compute the ORDER_HASH of the request.
The hashable string is composed by getting the values from:
MERCHANT
ORDER_REF
ORDER_DATE
ORDER_PNAME[]
ORDER_PCODE[]
ORDER_PINFO[]
ORDER_PRICE[]
ORDER_QTY[]
ORDER_... | [
"Compute",
"the",
"ORDER_HASH",
"of",
"the",
"request",
"."
] | python | train |
tanghaibao/jcvi | jcvi/formats/gff.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/gff.py#L2181-L2231 | def gtf(args):
"""
%prog gtf gffile
Convert gff to gtf file. In gtf, only exon/CDS features are important. The
first 8 columns are the same as gff, but in the attributes field, we need to
specify "gene_id" and "transcript_id".
"""
p = OptionParser(gtf.__doc__)
opts, args = p.parse_args(... | [
"def",
"gtf",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"gtf",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
... | %prog gtf gffile
Convert gff to gtf file. In gtf, only exon/CDS features are important. The
first 8 columns are the same as gff, but in the attributes field, we need to
specify "gene_id" and "transcript_id". | [
"%prog",
"gtf",
"gffile"
] | python | train |
thiagopbueno/rddl2tf | rddl2tf/compiler.py | https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/compiler.py#L647-L676 | def _compile_pvariable_expression(self,
expr: Expression,
scope: Dict[str, TensorFluent],
batch_size: Optional[int] = None,
noise: Optional[List[tf.Tensor]] = None) -> ... | [
"def",
"_compile_pvariable_expression",
"(",
"self",
",",
"expr",
":",
"Expression",
",",
"scope",
":",
"Dict",
"[",
"str",
",",
"TensorFluent",
"]",
",",
"batch_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"noise",
":",
"Optional",
"[",
"L... | Compile a pvariable expression `expr` into a TensorFluent
in the given `scope` with optional batch size.
Args:
expr (:obj:`rddl2tf.expr.Expression`): A RDDL pvariable expression.
scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope.
batch_size (Optio... | [
"Compile",
"a",
"pvariable",
"expression",
"expr",
"into",
"a",
"TensorFluent",
"in",
"the",
"given",
"scope",
"with",
"optional",
"batch",
"size",
"."
] | python | train |
bitshares/python-bitshares | bitshares/dex.py | https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/dex.py#L26-L61 | def returnFees(self):
""" Returns a dictionary of all fees that apply through the
network
Example output:
.. code-block:: js
{'proposal_create': {'fee': 400000.0},
'asset_publish_feed': {'fee': 1000.0}, 'account_create':
{'ba... | [
"def",
"returnFees",
"(",
"self",
")",
":",
"from",
"bitsharesbase",
".",
"operations",
"import",
"operations",
"r",
"=",
"{",
"}",
"obj",
",",
"base",
"=",
"self",
".",
"blockchain",
".",
"rpc",
".",
"get_objects",
"(",
"[",
"\"2.0.0\"",
",",
"\"1.3.0\"... | Returns a dictionary of all fees that apply through the
network
Example output:
.. code-block:: js
{'proposal_create': {'fee': 400000.0},
'asset_publish_feed': {'fee': 1000.0}, 'account_create':
{'basic_fee': 950000.0, 'price_per_kby... | [
"Returns",
"a",
"dictionary",
"of",
"all",
"fees",
"that",
"apply",
"through",
"the",
"network"
] | python | train |
OpenAgInitiative/openag_python | openag/cli/cloud/farm.py | https://github.com/OpenAgInitiative/openag_python/blob/f6202340292bbf7185e1a7d4290188c0dacbb8d0/openag/cli/cloud/farm.py#L37-L58 | def list_farms():
"""
List all farms you can manage. If you have selected a farm already, the
name of that farm will be prefixed with an asterisk in the returned list.
"""
utils.check_for_cloud_server()
utils.check_for_cloud_user()
server = Server(config["cloud_server"]["url"])
server.lo... | [
"def",
"list_farms",
"(",
")",
":",
"utils",
".",
"check_for_cloud_server",
"(",
")",
"utils",
".",
"check_for_cloud_user",
"(",
")",
"server",
"=",
"Server",
"(",
"config",
"[",
"\"cloud_server\"",
"]",
"[",
"\"url\"",
"]",
")",
"server",
".",
"log_in",
"... | List all farms you can manage. If you have selected a farm already, the
name of that farm will be prefixed with an asterisk in the returned list. | [
"List",
"all",
"farms",
"you",
"can",
"manage",
".",
"If",
"you",
"have",
"selected",
"a",
"farm",
"already",
"the",
"name",
"of",
"that",
"farm",
"will",
"be",
"prefixed",
"with",
"an",
"asterisk",
"in",
"the",
"returned",
"list",
"."
] | python | train |
PierreRust/apigpio | apigpio/apigpio.py | https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L990-L1030 | def add_callback(self, user_gpio, edge=RISING_EDGE, func=None):
"""
Calls a user supplied function (a callback) whenever the
specified gpio edge is detected.
user_gpio:= 0-31.
edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
func:= user supplied callback... | [
"def",
"add_callback",
"(",
"self",
",",
"user_gpio",
",",
"edge",
"=",
"RISING_EDGE",
",",
"func",
"=",
"None",
")",
":",
"cb",
"=",
"Callback",
"(",
"self",
".",
"_notify",
",",
"user_gpio",
",",
"edge",
",",
"func",
")",
"yield",
"from",
"self",
"... | Calls a user supplied function (a callback) whenever the
specified gpio edge is detected.
user_gpio:= 0-31.
edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
func:= user supplied callback function.
The user supplied callback receives three parameters, the gpio,
... | [
"Calls",
"a",
"user",
"supplied",
"function",
"(",
"a",
"callback",
")",
"whenever",
"the",
"specified",
"gpio",
"edge",
"is",
"detected",
"."
] | python | train |
theiviaxx/python-perforce | perforce/api.py | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/api.py#L81-L94 | def open(filename, connection=None):
"""Edits or Adds a filename ensuring the file is in perforce and editable
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
res ... | [
"def",
"open",
"(",
"filename",
",",
"connection",
"=",
"None",
")",
":",
"c",
"=",
"connection",
"or",
"connect",
"(",
")",
"res",
"=",
"c",
".",
"ls",
"(",
"filename",
")",
"if",
"res",
"and",
"res",
"[",
"0",
"]",
".",
"revision",
":",
"res",
... | Edits or Adds a filename ensuring the file is in perforce and editable
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection` | [
"Edits",
"or",
"Adds",
"a",
"filename",
"ensuring",
"the",
"file",
"is",
"in",
"perforce",
"and",
"editable"
] | python | train |
thautwarm/RBNF | rbnf/py_tools/unparse.py | https://github.com/thautwarm/RBNF/blob/cceec88c90f7ec95c160cfda01bfc532610985e0/rbnf/py_tools/unparse.py#L101-L108 | def dispatch(self, tree):
"Dispatcher function, dispatching tree type T to method _T."
if isinstance(tree, list):
for t in tree:
self.dispatch(t)
return
meth = getattr(self, "_" + tree.__class__.__name__)
meth(tree) | [
"def",
"dispatch",
"(",
"self",
",",
"tree",
")",
":",
"if",
"isinstance",
"(",
"tree",
",",
"list",
")",
":",
"for",
"t",
"in",
"tree",
":",
"self",
".",
"dispatch",
"(",
"t",
")",
"return",
"meth",
"=",
"getattr",
"(",
"self",
",",
"\"_\"",
"+"... | Dispatcher function, dispatching tree type T to method _T. | [
"Dispatcher",
"function",
"dispatching",
"tree",
"type",
"T",
"to",
"method",
"_T",
"."
] | python | train |
Netflix-Skunkworks/cloudaux | cloudaux/orchestration/aws/lambda_function.py | https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/orchestration/aws/lambda_function.py#L99-L132 | def get_lambda_function(lambda_function, flags=FLAGS.ALL, **conn):
"""Fully describes a lambda function.
Args:
lambda_function: Name, ARN, or dictionary of lambda function. If dictionary, should likely be the return value from list_functions. At a minimum, must contain a key titled 'FunctionName'.
... | [
"def",
"get_lambda_function",
"(",
"lambda_function",
",",
"flags",
"=",
"FLAGS",
".",
"ALL",
",",
"*",
"*",
"conn",
")",
":",
"# Python 2 and 3 support:",
"try",
":",
"basestring",
"except",
"NameError",
"as",
"_",
":",
"basestring",
"=",
"str",
"# If STR is ... | Fully describes a lambda function.
Args:
lambda_function: Name, ARN, or dictionary of lambda function. If dictionary, should likely be the return value from list_functions. At a minimum, must contain a key titled 'FunctionName'.
flags: Flags describing which sections should be included in the r... | [
"Fully",
"describes",
"a",
"lambda",
"function",
".",
"Args",
":",
"lambda_function",
":",
"Name",
"ARN",
"or",
"dictionary",
"of",
"lambda",
"function",
".",
"If",
"dictionary",
"should",
"likely",
"be",
"the",
"return",
"value",
"from",
"list_functions",
"."... | python | valid |
proycon/clam | clam/common/data.py | https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1881-L1887 | def getparent(self, profile):
"""Resolve a parent ID"""
assert self.parent
for inputtemplate in profile.input:
if inputtemplate == self.parent:
return inputtemplate
raise Exception("Parent InputTemplate '"+self.parent+"' not found!") | [
"def",
"getparent",
"(",
"self",
",",
"profile",
")",
":",
"assert",
"self",
".",
"parent",
"for",
"inputtemplate",
"in",
"profile",
".",
"input",
":",
"if",
"inputtemplate",
"==",
"self",
".",
"parent",
":",
"return",
"inputtemplate",
"raise",
"Exception",
... | Resolve a parent ID | [
"Resolve",
"a",
"parent",
"ID"
] | python | train |
ibis-project/ibis | ibis/pandas/execution/generic.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/pandas/execution/generic.py#L290-L301 | def execute_cast_timestamp_to_timestamp(op, data, type, **kwargs):
"""Cast timestamps to other timestamps including timezone if necessary"""
input_timezone = data.tz
target_timezone = type.timezone
if input_timezone == target_timezone:
return data
if input_timezone is None or target_timezo... | [
"def",
"execute_cast_timestamp_to_timestamp",
"(",
"op",
",",
"data",
",",
"type",
",",
"*",
"*",
"kwargs",
")",
":",
"input_timezone",
"=",
"data",
".",
"tz",
"target_timezone",
"=",
"type",
".",
"timezone",
"if",
"input_timezone",
"==",
"target_timezone",
":... | Cast timestamps to other timestamps including timezone if necessary | [
"Cast",
"timestamps",
"to",
"other",
"timestamps",
"including",
"timezone",
"if",
"necessary"
] | python | train |
awslabs/aws-sam-cli | samcli/commands/local/lib/sam_function_provider.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L195-L217 | def _extract_lambda_function_code(resource_properties, code_property_key):
"""
Extracts the Lambda Function Code from the Resource Properties
Parameters
----------
resource_properties dict
Dictionary representing the Properties of the Resource
code_property_k... | [
"def",
"_extract_lambda_function_code",
"(",
"resource_properties",
",",
"code_property_key",
")",
":",
"codeuri",
"=",
"resource_properties",
".",
"get",
"(",
"code_property_key",
",",
"SamFunctionProvider",
".",
"_DEFAULT_CODEURI",
")",
"if",
"isinstance",
"(",
"codeu... | Extracts the Lambda Function Code from the Resource Properties
Parameters
----------
resource_properties dict
Dictionary representing the Properties of the Resource
code_property_key str
Property Key of the code on the Resource
Returns
-------
... | [
"Extracts",
"the",
"Lambda",
"Function",
"Code",
"from",
"the",
"Resource",
"Properties"
] | python | train |
contains-io/rcli | rcli/dispatcher.py | https://github.com/contains-io/rcli/blob/cdd6191a0e0a19bc767f84921650835d099349cf/rcli/dispatcher.py#L107-L123 | def _get_command_and_argv(argv):
# type: (typing.List[str]) -> typing.Tuple[str, typing.List[str]]
"""Extract the command name and arguments to pass to docopt.
Args:
argv: The argument list being used to run the command.
Returns:
A tuple containing the name of the command and the argum... | [
"def",
"_get_command_and_argv",
"(",
"argv",
")",
":",
"# type: (typing.List[str]) -> typing.Tuple[str, typing.List[str]]",
"command_name",
"=",
"argv",
"[",
"0",
"]",
"if",
"not",
"command_name",
":",
"argv",
"=",
"argv",
"[",
"1",
":",
"]",
"elif",
"command_name",... | Extract the command name and arguments to pass to docopt.
Args:
argv: The argument list being used to run the command.
Returns:
A tuple containing the name of the command and the arguments to pass
to docopt. | [
"Extract",
"the",
"command",
"name",
"and",
"arguments",
"to",
"pass",
"to",
"docopt",
"."
] | python | train |
ArangoDB-Community/pyArango | pyArango/collection.py | https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L486-L490 | def simpleQuery(self, queryType, rawResults = False, **queryArgs) :
"""General interface for simple queries. queryType can be something like 'all', 'by-example' etc... everything is in the arango doc.
If rawResults, the query will return dictionaries instead of Document objetcs.
"""
retu... | [
"def",
"simpleQuery",
"(",
"self",
",",
"queryType",
",",
"rawResults",
"=",
"False",
",",
"*",
"*",
"queryArgs",
")",
":",
"return",
"SimpleQuery",
"(",
"self",
",",
"queryType",
",",
"rawResults",
",",
"*",
"*",
"queryArgs",
")"
] | General interface for simple queries. queryType can be something like 'all', 'by-example' etc... everything is in the arango doc.
If rawResults, the query will return dictionaries instead of Document objetcs. | [
"General",
"interface",
"for",
"simple",
"queries",
".",
"queryType",
"can",
"be",
"something",
"like",
"all",
"by",
"-",
"example",
"etc",
"...",
"everything",
"is",
"in",
"the",
"arango",
"doc",
".",
"If",
"rawResults",
"the",
"query",
"will",
"return",
... | python | train |
PonteIneptique/collatinus-python | pycollatinus/lemmatiseur.py | https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L248-L270 | def lemmatise(self, f, pos=False, get_lemma_object=False, lower=True):
""" Lemmatise un mot f
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param lower: Need to check lowercase ver... | [
"def",
"lemmatise",
"(",
"self",
",",
"f",
",",
"pos",
"=",
"False",
",",
"get_lemma_object",
"=",
"False",
",",
"lower",
"=",
"True",
")",
":",
"if",
"lower",
":",
"# We do not run numeral on lower",
"yield",
"from",
"self",
".",
"_lemmatise_roman_numerals",
... | Lemmatise un mot f
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param lower: Need to check lowercase version | [
"Lemmatise",
"un",
"mot",
"f"
] | python | train |
materialsproject/pymatgen | pymatgen/core/surface.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/surface.py#L369-L375 | def normal(self):
"""
Calculates the surface normal vector of the slab
"""
normal = np.cross(self.lattice.matrix[0], self.lattice.matrix[1])
normal /= np.linalg.norm(normal)
return normal | [
"def",
"normal",
"(",
"self",
")",
":",
"normal",
"=",
"np",
".",
"cross",
"(",
"self",
".",
"lattice",
".",
"matrix",
"[",
"0",
"]",
",",
"self",
".",
"lattice",
".",
"matrix",
"[",
"1",
"]",
")",
"normal",
"/=",
"np",
".",
"linalg",
".",
"nor... | Calculates the surface normal vector of the slab | [
"Calculates",
"the",
"surface",
"normal",
"vector",
"of",
"the",
"slab"
] | python | train |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L45-L49 | def check(self, feature):
"""Check that the feature has a fit/transform/fit_tranform interface"""
assert hasattr(feature.transformer, 'fit')
assert hasattr(feature.transformer, 'transform')
assert hasattr(feature.transformer, 'fit_transform') | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"assert",
"hasattr",
"(",
"feature",
".",
"transformer",
",",
"'fit'",
")",
"assert",
"hasattr",
"(",
"feature",
".",
"transformer",
",",
"'transform'",
")",
"assert",
"hasattr",
"(",
"feature",
".",
... | Check that the feature has a fit/transform/fit_tranform interface | [
"Check",
"that",
"the",
"feature",
"has",
"a",
"fit",
"/",
"transform",
"/",
"fit_tranform",
"interface"
] | python | train |
pypa/pipenv | pipenv/vendor/requests/utils.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L767-L790 | def select_proxy(url, proxies):
"""Select a proxy for the url, if applicable.
:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
"""
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
retur... | [
"def",
"select_proxy",
"(",
"url",
",",
"proxies",
")",
":",
"proxies",
"=",
"proxies",
"or",
"{",
"}",
"urlparts",
"=",
"urlparse",
"(",
"url",
")",
"if",
"urlparts",
".",
"hostname",
"is",
"None",
":",
"return",
"proxies",
".",
"get",
"(",
"urlparts"... | Select a proxy for the url, if applicable.
:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs | [
"Select",
"a",
"proxy",
"for",
"the",
"url",
"if",
"applicable",
"."
] | python | train |
DomBennett/TaxonNamesResolver | taxon_names_resolver/gnr_tools.py | https://github.com/DomBennett/TaxonNamesResolver/blob/a2556cc0f8b7442d83990715c92fdf6f787e1f41/taxon_names_resolver/gnr_tools.py#L67-L97 | def search(self, terms, prelim=True):
"""Search terms against GNR. If prelim = False, search other datasources \
for alternative names (i.e. synonyms) with which to search main datasource.\
Return JSON object."""
# TODO: There are now lots of additional data sources, make additional
# searching ... | [
"def",
"search",
"(",
"self",
",",
"terms",
",",
"prelim",
"=",
"True",
")",
":",
"# TODO: There are now lots of additional data sources, make additional",
"# searching optional (11/01/2017)",
"if",
"prelim",
":",
"# preliminary search",
"res",
"=",
"self",
".",
"_resolve... | Search terms against GNR. If prelim = False, search other datasources \
for alternative names (i.e. synonyms) with which to search main datasource.\
Return JSON object. | [
"Search",
"terms",
"against",
"GNR",
".",
"If",
"prelim",
"=",
"False",
"search",
"other",
"datasources",
"\\",
"for",
"alternative",
"names",
"(",
"i",
".",
"e",
".",
"synonyms",
")",
"with",
"which",
"to",
"search",
"main",
"datasource",
".",
"\\",
"Re... | python | train |
minhhoit/yacms | yacms/generic/fields.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/fields.py#L57-L90 | def contribute_to_class(self, cls, name):
"""
Add each of the names and fields in the ``fields`` attribute
to the model the relationship field is applied to, and set up
the related item save and delete signals for calling
``related_items_changed``.
"""
for field i... | [
"def",
"contribute_to_class",
"(",
"self",
",",
"cls",
",",
"name",
")",
":",
"for",
"field",
"in",
"cls",
".",
"_meta",
".",
"many_to_many",
":",
"if",
"isinstance",
"(",
"field",
",",
"self",
".",
"__class__",
")",
":",
"e",
"=",
"\"Multiple %s fields ... | Add each of the names and fields in the ``fields`` attribute
to the model the relationship field is applied to, and set up
the related item save and delete signals for calling
``related_items_changed``. | [
"Add",
"each",
"of",
"the",
"names",
"and",
"fields",
"in",
"the",
"fields",
"attribute",
"to",
"the",
"model",
"the",
"relationship",
"field",
"is",
"applied",
"to",
"and",
"set",
"up",
"the",
"related",
"item",
"save",
"and",
"delete",
"signals",
"for",
... | python | train |
quintusdias/glymur | glymur/codestream.py | https://github.com/quintusdias/glymur/blob/8b8fb091130fff00f1028dc82219e69e3f9baf6d/glymur/codestream.py#L1844-L1852 | def _parse_precinct_size(spcod):
"""Compute precinct size from SPcod or SPcoc."""
spcod = np.frombuffer(spcod, dtype=np.uint8)
precinct_size = []
for item in spcod:
ep2 = (item & 0xF0) >> 4
ep1 = item & 0x0F
precinct_size.append((2 ** ep1, 2 ** ep2))
return tuple(precinct_siz... | [
"def",
"_parse_precinct_size",
"(",
"spcod",
")",
":",
"spcod",
"=",
"np",
".",
"frombuffer",
"(",
"spcod",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"precinct_size",
"=",
"[",
"]",
"for",
"item",
"in",
"spcod",
":",
"ep2",
"=",
"(",
"item",
"&",
... | Compute precinct size from SPcod or SPcoc. | [
"Compute",
"precinct",
"size",
"from",
"SPcod",
"or",
"SPcoc",
"."
] | python | train |
batiste/django-page-cms | pages/templatetags/pages_tags.py | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/templatetags/pages_tags.py#L192-L217 | def show_absolute_url(context, page, lang=None):
"""
Show the url of a page in the right language
Example ::
{% show_absolute_url page_object %}
You can also use the slug of a page::
{% show_absolute_url "my-page-slug" %}
Keyword arguments:
:param page: the page object, slug... | [
"def",
"show_absolute_url",
"(",
"context",
",",
"page",
",",
"lang",
"=",
"None",
")",
":",
"if",
"not",
"lang",
":",
"lang",
"=",
"context",
".",
"get",
"(",
"'lang'",
",",
"pages_settings",
".",
"PAGE_DEFAULT_LANGUAGE",
")",
"page",
"=",
"get_page_from_... | Show the url of a page in the right language
Example ::
{% show_absolute_url page_object %}
You can also use the slug of a page::
{% show_absolute_url "my-page-slug" %}
Keyword arguments:
:param page: the page object, slug or id
:param lang: the wanted language \
(defaul... | [
"Show",
"the",
"url",
"of",
"a",
"page",
"in",
"the",
"right",
"language"
] | python | train |
Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L180-L190 | def _get_async_status(self, response):
"""Attempt to find status info in response body.
:param requests.Response response: latest REST call response.
:rtype: str
:returns: Status if found, else 'None'.
"""
if self._is_empty(response):
return None
body... | [
"def",
"_get_async_status",
"(",
"self",
",",
"response",
")",
":",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"return",
"None",
"body",
"=",
"self",
".",
"_as_json",
"(",
"response",
")",
"return",
"body",
".",
"get",
"(",
"'status'",
... | Attempt to find status info in response body.
:param requests.Response response: latest REST call response.
:rtype: str
:returns: Status if found, else 'None'. | [
"Attempt",
"to",
"find",
"status",
"info",
"in",
"response",
"body",
"."
] | python | train |
CxAalto/gtfspy | gtfspy/util.py | https://github.com/CxAalto/gtfspy/blob/bddba4b74faae6c1b91202f19184811e326547e5/gtfspy/util.py#L31-L43 | def set_process_timezone(TZ):
"""
Parameters
----------
TZ: string
"""
try:
prev_timezone = os.environ['TZ']
except KeyError:
prev_timezone = None
os.environ['TZ'] = TZ
time.tzset() # Cause C-library functions to notice the update.
return prev_timezone | [
"def",
"set_process_timezone",
"(",
"TZ",
")",
":",
"try",
":",
"prev_timezone",
"=",
"os",
".",
"environ",
"[",
"'TZ'",
"]",
"except",
"KeyError",
":",
"prev_timezone",
"=",
"None",
"os",
".",
"environ",
"[",
"'TZ'",
"]",
"=",
"TZ",
"time",
".",
"tzse... | Parameters
----------
TZ: string | [
"Parameters",
"----------",
"TZ",
":",
"string"
] | python | valid |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/breakpoint.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L3972-L4052 | def hook_function(self, pid, address,
preCB = None, postCB = None,
paramCount = None, signature = None):
"""
Sets a function hook at the given address.
If instead of an address you pass a label, the hook may be
deferred until the DLL it points... | [
"def",
"hook_function",
"(",
"self",
",",
"pid",
",",
"address",
",",
"preCB",
"=",
"None",
",",
"postCB",
"=",
"None",
",",
"paramCount",
"=",
"None",
",",
"signature",
"=",
"None",
")",
":",
"try",
":",
"aProcess",
"=",
"self",
".",
"system",
".",
... | Sets a function hook at the given address.
If instead of an address you pass a label, the hook may be
deferred until the DLL it points to is loaded.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of ... | [
"Sets",
"a",
"function",
"hook",
"at",
"the",
"given",
"address",
"."
] | python | train |
toastdriven/alligator | alligator/backends/beanstalk_backend.py | https://github.com/toastdriven/alligator/blob/f18bcb35b350fc6b0886393f5246d69c892b36c7/alligator/backends/beanstalk_backend.py#L55-L72 | def drop_all(self, queue_name):
"""
Drops all the task in the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
"""
# This is very inefficient, but Beanstalk (as of v1.10) doesn't support
... | [
"def",
"drop_all",
"(",
"self",
",",
"queue_name",
")",
":",
"# This is very inefficient, but Beanstalk (as of v1.10) doesn't support",
"# deleting an entire tube.",
"queue_length",
"=",
"self",
".",
"len",
"(",
"queue_name",
")",
"self",
".",
"_only_watch_from",
"(",
"qu... | Drops all the task in the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string | [
"Drops",
"all",
"the",
"task",
"in",
"the",
"queue",
"."
] | python | train |
stevearc/dql | dql/grammar/__init__.py | https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/grammar/__init__.py#L60-L65 | def create_throttle():
""" Create a THROTTLE statement """
throttle_amount = "*" | Combine(number + "%") | number
return Group(
function("throttle", throttle_amount, throttle_amount, caseless=True)
).setResultsName("throttle") | [
"def",
"create_throttle",
"(",
")",
":",
"throttle_amount",
"=",
"\"*\"",
"|",
"Combine",
"(",
"number",
"+",
"\"%\"",
")",
"|",
"number",
"return",
"Group",
"(",
"function",
"(",
"\"throttle\"",
",",
"throttle_amount",
",",
"throttle_amount",
",",
"caseless",... | Create a THROTTLE statement | [
"Create",
"a",
"THROTTLE",
"statement"
] | python | train |
mabuchilab/QNET | src/qnet/algebra/_rules.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/_rules.py#L911-L925 | def _pull_out_perm_lhs(lhs, rest, out_port, in_port):
"""Pull out a permutation from the Feedback of a SeriesProduct with itself.
Args:
lhs (CPermutation): The permutation circuit
rest (tuple): The other SeriesProduct operands
out_port (int): The feedback output port index
in_po... | [
"def",
"_pull_out_perm_lhs",
"(",
"lhs",
",",
"rest",
",",
"out_port",
",",
"in_port",
")",
":",
"out_inv",
",",
"lhs_red",
"=",
"lhs",
".",
"_factor_lhs",
"(",
"out_port",
")",
"return",
"lhs_red",
"<<",
"Feedback",
".",
"create",
"(",
"SeriesProduct",
".... | Pull out a permutation from the Feedback of a SeriesProduct with itself.
Args:
lhs (CPermutation): The permutation circuit
rest (tuple): The other SeriesProduct operands
out_port (int): The feedback output port index
in_port (int): The feedback input port index
Returns:
... | [
"Pull",
"out",
"a",
"permutation",
"from",
"the",
"Feedback",
"of",
"a",
"SeriesProduct",
"with",
"itself",
"."
] | python | train |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/anchor/rrbuilder.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/rrbuilder.py#L329-L397 | async def create_rev_reg(self, rr_id: str, rr_size: int = None) -> None:
"""
Create revocation registry artifacts and new tails file (with association to
corresponding revocation registry identifier via symbolic link name)
for input revocation registry identifier. Symbolic link presence ... | [
"async",
"def",
"create_rev_reg",
"(",
"self",
",",
"rr_id",
":",
"str",
",",
"rr_size",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'RevRegBuilder.create_rev_reg >>> rr_id: %s, rr_size: %s'",
",",
"rr_id",
",",
"rr_size",
")... | Create revocation registry artifacts and new tails file (with association to
corresponding revocation registry identifier via symbolic link name)
for input revocation registry identifier. Symbolic link presence signals completion.
If revocation registry builder operates in a process external to ... | [
"Create",
"revocation",
"registry",
"artifacts",
"and",
"new",
"tails",
"file",
"(",
"with",
"association",
"to",
"corresponding",
"revocation",
"registry",
"identifier",
"via",
"symbolic",
"link",
"name",
")",
"for",
"input",
"revocation",
"registry",
"identifier",... | python | train |
IrvKalb/pygwidgets | pygwidgets/pygwidgets.py | https://github.com/IrvKalb/pygwidgets/blob/a830d8885d4d209e471cb53816277d30db56273c/pygwidgets/pygwidgets.py#L2492-L2506 | def stop(self):
"""Stops a a playing animation. A subsequent call to play will start from the beginning."""
if self.state == PygAnimation.PLAYING:
self.index = 0 # set up for first image in list
self.elapsed = 0
self.nIterationsLeft = 0
elif self.sta... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"PygAnimation",
".",
"PLAYING",
":",
"self",
".",
"index",
"=",
"0",
"# set up for first image in list\r",
"self",
".",
"elapsed",
"=",
"0",
"self",
".",
"nIterationsLeft",
"=",
"0",
... | Stops a a playing animation. A subsequent call to play will start from the beginning. | [
"Stops",
"a",
"a",
"playing",
"animation",
".",
"A",
"subsequent",
"call",
"to",
"play",
"will",
"start",
"from",
"the",
"beginning",
"."
] | python | train |
google/grr | grr/server/grr_response_server/aff4_objects/standard.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L350-L360 | def Flush(self):
"""Flush the data to the index."""
super(LabelSet, self).Flush()
self.to_delete = self.to_delete.difference(self.to_set)
with data_store.DB.GetMutationPool() as mutation_pool:
mutation_pool.LabelUpdateLabels(
self.urn, self.to_set, to_delete=self.to_delete)
self.to... | [
"def",
"Flush",
"(",
"self",
")",
":",
"super",
"(",
"LabelSet",
",",
"self",
")",
".",
"Flush",
"(",
")",
"self",
".",
"to_delete",
"=",
"self",
".",
"to_delete",
".",
"difference",
"(",
"self",
".",
"to_set",
")",
"with",
"data_store",
".",
"DB",
... | Flush the data to the index. | [
"Flush",
"the",
"data",
"to",
"the",
"index",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.