repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/fileclient.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileclient.py#L1304-L1326 | def __hash_and_stat_file(self, path, saltenv='base'):
'''
Common code for hashing and stating files
'''
try:
path = self._check_proto(path)
except MinionError as err:
if not os.path.isfile(path):
log.warning(
'specified ... | [
"def",
"__hash_and_stat_file",
"(",
"self",
",",
"path",
",",
"saltenv",
"=",
"'base'",
")",
":",
"try",
":",
"path",
"=",
"self",
".",
"_check_proto",
"(",
"path",
")",
"except",
"MinionError",
"as",
"err",
":",
"if",
"not",
"os",
".",
"path",
".",
... | Common code for hashing and stating files | [
"Common",
"code",
"for",
"hashing",
"and",
"stating",
"files"
] | python | train | 35.826087 |
bionikspoon/pureyaml | pureyaml/_compat/total_ordering.py | https://github.com/bionikspoon/pureyaml/blob/784830b907ca14525c4cecdb6ae35306f6f8a877/pureyaml/_compat/total_ordering.py#L100-L105 | def _lt_from_ge(self, other):
"""Return a < b. Computed by @total_ordering from (not a >= b)."""
op_result = self.__ge__(other)
if op_result is NotImplemented:
return NotImplemented
return not op_result | [
"def",
"_lt_from_ge",
"(",
"self",
",",
"other",
")",
":",
"op_result",
"=",
"self",
".",
"__ge__",
"(",
"other",
")",
"if",
"op_result",
"is",
"NotImplemented",
":",
"return",
"NotImplemented",
"return",
"not",
"op_result"
] | Return a < b. Computed by @total_ordering from (not a >= b). | [
"Return",
"a",
"<",
"b",
".",
"Computed",
"by"
] | python | train | 37 |
quantumlib/Cirq | examples/phase_estimator.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/examples/phase_estimator.py#L63-L82 | def _decompose_(self, qubits):
"""A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
| ... | [
"def",
"_decompose_",
"(",
"self",
",",
"qubits",
")",
":",
"qubits",
"=",
"list",
"(",
"qubits",
")",
"while",
"len",
"(",
"qubits",
")",
">",
"0",
":",
"q_head",
"=",
"qubits",
".",
"pop",
"(",
"0",
")",
"yield",
"cirq",
".",
"H",
"(",
"q_head"... | A quantum circuit (QFT_inv) with the following structure.
---H--@-------@--------@----------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@-------------------------
| | | |
--------... | [
"A",
"quantum",
"circuit",
"(",
"QFT_inv",
")",
"with",
"the",
"following",
"structure",
"."
] | python | train | 42.6 |
FujiMakoto/AgentML | agentml/parser/init/__init__.py | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/init/__init__.py#L16-L25 | def _parse_substitutions(self, element):
"""
Parse word substitutions
:param element: The XML Element object
:type element: etree._Element
"""
subs = element.findall('sub')
for sub in subs:
self.agentml.set_substitution(attribute(sub, 'word'), sub.te... | [
"def",
"_parse_substitutions",
"(",
"self",
",",
"element",
")",
":",
"subs",
"=",
"element",
".",
"findall",
"(",
"'sub'",
")",
"for",
"sub",
"in",
"subs",
":",
"self",
".",
"agentml",
".",
"set_substitution",
"(",
"attribute",
"(",
"sub",
",",
"'word'"... | Parse word substitutions
:param element: The XML Element object
:type element: etree._Element | [
"Parse",
"word",
"substitutions",
":",
"param",
"element",
":",
"The",
"XML",
"Element",
"object",
":",
"type",
"element",
":",
"etree",
".",
"_Element"
] | python | train | 31.4 |
astropy/astropy-helpers | astropy_helpers/commands/build_ext.py | https://github.com/astropy/astropy-helpers/blob/f5a27d3f84a98ea0eebb85e0cf3e7214c6bc0d09/astropy_helpers/commands/build_ext.py#L15-L37 | def should_build_with_cython(previous_cython_version, is_release):
"""
Returns the previously used Cython version (or 'unknown' if not
previously built) if Cython should be used to build extension modules from
pyx files.
"""
# Only build with Cython if, of course, Cython is installed, we're in ... | [
"def",
"should_build_with_cython",
"(",
"previous_cython_version",
",",
"is_release",
")",
":",
"# Only build with Cython if, of course, Cython is installed, we're in a",
"# development version (i.e. not release) or the Cython-generated source",
"# files haven't been created yet (cython_version ... | Returns the previously used Cython version (or 'unknown' if not
previously built) if Cython should be used to build extension modules from
pyx files. | [
"Returns",
"the",
"previously",
"used",
"Cython",
"version",
"(",
"or",
"unknown",
"if",
"not",
"previously",
"built",
")",
"if",
"Cython",
"should",
"be",
"used",
"to",
"build",
"extension",
"modules",
"from",
"pyx",
"files",
"."
] | python | train | 37.521739 |
ga4gh/ga4gh-server | ga4gh/server/backend.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/backend.py#L289-L302 | def readsGenerator(self, request):
"""
Returns a generator over the (read, nextPageToken) pairs defined
by the specified request
"""
if not request.reference_id:
raise exceptions.UnmappedReadsNotSupported()
if len(request.read_group_ids) < 1:
raise... | [
"def",
"readsGenerator",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"request",
".",
"reference_id",
":",
"raise",
"exceptions",
".",
"UnmappedReadsNotSupported",
"(",
")",
"if",
"len",
"(",
"request",
".",
"read_group_ids",
")",
"<",
"1",
":",
"ra... | Returns a generator over the (read, nextPageToken) pairs defined
by the specified request | [
"Returns",
"a",
"generator",
"over",
"the",
"(",
"read",
"nextPageToken",
")",
"pairs",
"defined",
"by",
"the",
"specified",
"request"
] | python | train | 41 |
itsnauman/termrule | tr/termrule.py | https://github.com/itsnauman/termrule/blob/62b8cc7e9a7fc4476ccdaf84fe2685eb529dc48c/tr/termrule.py#L108-L125 | def tr(self, args, color=None):
"""
Method to print ASCII patterns to terminal
"""
width = self._term_size()[1]
if not args:
if color is not None:
print(self._echo("#" * width, color))
else:
print(self._echo("#" * width, "gr... | [
"def",
"tr",
"(",
"self",
",",
"args",
",",
"color",
"=",
"None",
")",
":",
"width",
"=",
"self",
".",
"_term_size",
"(",
")",
"[",
"1",
"]",
"if",
"not",
"args",
":",
"if",
"color",
"is",
"not",
"None",
":",
"print",
"(",
"self",
".",
"_echo",... | Method to print ASCII patterns to terminal | [
"Method",
"to",
"print",
"ASCII",
"patterns",
"to",
"terminal"
] | python | train | 35.222222 |
python-xlib/python-xlib | Xlib/ext/nvcontrol.py | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L63-L73 | def query_string_attribute(self, target, display_mask, attr):
"""Return the value of a string attribute"""
reply = NVCtrlQueryStringAttributeReplyRequest(display=self.display,
opcode=self.display.get_extension_major(extname),
... | [
"def",
"query_string_attribute",
"(",
"self",
",",
"target",
",",
"display_mask",
",",
"attr",
")",
":",
"reply",
"=",
"NVCtrlQueryStringAttributeReplyRequest",
"(",
"display",
"=",
"self",
".",
"display",
",",
"opcode",
"=",
"self",
".",
"display",
".",
"get_... | Return the value of a string attribute | [
"Return",
"the",
"value",
"of",
"a",
"string",
"attribute"
] | python | train | 61.545455 |
wright-group/WrightTools | WrightTools/collection/_collection.py | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/collection/_collection.py#L75-L103 | def create_collection(self, name="collection", position=None, **kwargs):
"""Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
... | [
"def",
"create_collection",
"(",
"self",
",",
"name",
"=",
"\"collection\"",
",",
"position",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"in",
"self",
".",
"item_names",
":",
"wt_exceptions",
".",
"ObjectExistsWarning",
".",
"warn",
"(",... | Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child collection instantiation.
Returns
... | [
"Create",
"a",
"new",
"child",
"colleciton",
"."
] | python | train | 33.310345 |
chrippa/python-librtmp | librtmp/rtmp.py | https://github.com/chrippa/python-librtmp/blob/6efefd5edd76cad7a3b53f7c87c1c7350448224d/librtmp/rtmp.py#L172-L191 | def connect(self, packet=None):
"""Connect to the server.
:param packet: RTMPPacket, this packet will be sent instead
of the regular "connect" packet.
Raises :exc:`RTMPError` if the connect attempt fails.
"""
if isinstance(packet, RTMPPacket):
... | [
"def",
"connect",
"(",
"self",
",",
"packet",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"packet",
",",
"RTMPPacket",
")",
":",
"packet",
"=",
"packet",
".",
"packet",
"else",
":",
"packet",
"=",
"ffi",
".",
"NULL",
"res",
"=",
"librtmp",
".",
... | Connect to the server.
:param packet: RTMPPacket, this packet will be sent instead
of the regular "connect" packet.
Raises :exc:`RTMPError` if the connect attempt fails. | [
"Connect",
"to",
"the",
"server",
"."
] | python | train | 26.5 |
earwig/mwparserfromhell | mwparserfromhell/parser/tokenizer.py | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L705-L717 | def _handle_tag_text(self, text):
"""Handle regular *text* inside of an HTML open tag."""
next = self._read(1)
if not self._can_recurse() or text not in self.MARKERS:
self._emit_text(text)
elif text == next == "{":
self._parse_template_or_argument()
elif t... | [
"def",
"_handle_tag_text",
"(",
"self",
",",
"text",
")",
":",
"next",
"=",
"self",
".",
"_read",
"(",
"1",
")",
"if",
"not",
"self",
".",
"_can_recurse",
"(",
")",
"or",
"text",
"not",
"in",
"self",
".",
"MARKERS",
":",
"self",
".",
"_emit_text",
... | Handle regular *text* inside of an HTML open tag. | [
"Handle",
"regular",
"*",
"text",
"*",
"inside",
"of",
"an",
"HTML",
"open",
"tag",
"."
] | python | train | 35.846154 |
couchbase/couchbase-python-client | couchbase/subdocument.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/subdocument.py#L34-L46 | def _gen_3spec(op, path, xattr=False):
"""
Returns a Spec tuple suitable for passing to the underlying C extension.
This variant is called for operations that lack an input value.
:param str path: The path to fetch
:param bool xattr: Whether this is an extended attribute
:return: a spec suitabl... | [
"def",
"_gen_3spec",
"(",
"op",
",",
"path",
",",
"xattr",
"=",
"False",
")",
":",
"flags",
"=",
"0",
"if",
"xattr",
":",
"flags",
"|=",
"_P",
".",
"SDSPEC_F_XATTR",
"return",
"Spec",
"(",
"op",
",",
"path",
",",
"flags",
")"
] | Returns a Spec tuple suitable for passing to the underlying C extension.
This variant is called for operations that lack an input value.
:param str path: The path to fetch
:param bool xattr: Whether this is an extended attribute
:return: a spec suitable for passing to the underlying C extension | [
"Returns",
"a",
"Spec",
"tuple",
"suitable",
"for",
"passing",
"to",
"the",
"underlying",
"C",
"extension",
".",
"This",
"variant",
"is",
"called",
"for",
"operations",
"that",
"lack",
"an",
"input",
"value",
"."
] | python | train | 35 |
janpipek/physt | physt/compat/geant4.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/compat/geant4.py#L43-L49 | def _get(pseudodict, key, single=True):
"""Helper method for getting values from "multi-dict"s"""
matches = [item[1] for item in pseudodict if item[0] == key]
if single:
return matches[0]
else:
return matches | [
"def",
"_get",
"(",
"pseudodict",
",",
"key",
",",
"single",
"=",
"True",
")",
":",
"matches",
"=",
"[",
"item",
"[",
"1",
"]",
"for",
"item",
"in",
"pseudodict",
"if",
"item",
"[",
"0",
"]",
"==",
"key",
"]",
"if",
"single",
":",
"return",
"matc... | Helper method for getting values from "multi-dict"s | [
"Helper",
"method",
"for",
"getting",
"values",
"from",
"multi",
"-",
"dict",
"s"
] | python | train | 33.428571 |
spacetelescope/stsci.tools | lib/stsci/tools/for2to3.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/for2to3.py#L53-L71 | def tobytes(s, encoding='ascii'):
""" Convert string s to the 'bytes' type, in all Pythons, even
back before Python 2.6. What 'str' means varies by PY3K or not.
In Pythons before 3.0, this is technically the same as the str type
in terms of the character data in memory. """
# NOTE: after we abandon... | [
"def",
"tobytes",
"(",
"s",
",",
"encoding",
"=",
"'ascii'",
")",
":",
"# NOTE: after we abandon 2.5, we might simply instead use \"bytes(s)\"",
"# NOTE: after we abandon all 2.*, del this and prepend byte strings with 'b'",
"if",
"PY3K",
":",
"if",
"isinstance",
"(",
"s",
",",... | Convert string s to the 'bytes' type, in all Pythons, even
back before Python 2.6. What 'str' means varies by PY3K or not.
In Pythons before 3.0, this is technically the same as the str type
in terms of the character data in memory. | [
"Convert",
"string",
"s",
"to",
"the",
"bytes",
"type",
"in",
"all",
"Pythons",
"even",
"back",
"before",
"Python",
"2",
".",
"6",
".",
"What",
"str",
"means",
"varies",
"by",
"PY3K",
"or",
"not",
".",
"In",
"Pythons",
"before",
"3",
".",
"0",
"this"... | python | train | 41.210526 |
drdoctr/doctr | doctr/travis.py | https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/travis.py#L49-L95 | def setup_deploy_key(keypath='github_deploy_key', key_ext='.enc', env_name='DOCTR_DEPLOY_ENCRYPTION_KEY'):
"""
Decrypts the deploy key and configures it with ssh
The key is assumed to be encrypted as keypath + key_ext, and the
encryption key is assumed to be set in the environment variable
``env_na... | [
"def",
"setup_deploy_key",
"(",
"keypath",
"=",
"'github_deploy_key'",
",",
"key_ext",
"=",
"'.enc'",
",",
"env_name",
"=",
"'DOCTR_DEPLOY_ENCRYPTION_KEY'",
")",
":",
"key",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"env_name",
",",
"os",
".",
"environ",
"... | Decrypts the deploy key and configures it with ssh
The key is assumed to be encrypted as keypath + key_ext, and the
encryption key is assumed to be set in the environment variable
``env_name``. If ``env_name`` is not set, it falls back to
``DOCTR_DEPLOY_ENCRYPTION_KEY`` for backwards compatibility.
... | [
"Decrypts",
"the",
"deploy",
"key",
"and",
"configures",
"it",
"with",
"ssh"
] | python | train | 42.93617 |
flo-compbio/genometools | genometools/ontology/util.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/util.py#L53-L59 | def download_release(download_file, release=None):
"""Downloads the "go-basic.obo" file for the specified release."""
if release is None:
release = get_latest_release()
url = 'http://viewvc.geneontology.org/viewvc/GO-SVN/ontology-releases/%s/go-basic.obo' % release
#download_file = 'go-basic_%s.... | [
"def",
"download_release",
"(",
"download_file",
",",
"release",
"=",
"None",
")",
":",
"if",
"release",
"is",
"None",
":",
"release",
"=",
"get_latest_release",
"(",
")",
"url",
"=",
"'http://viewvc.geneontology.org/viewvc/GO-SVN/ontology-releases/%s/go-basic.obo'",
"%... | Downloads the "go-basic.obo" file for the specified release. | [
"Downloads",
"the",
"go",
"-",
"basic",
".",
"obo",
"file",
"for",
"the",
"specified",
"release",
"."
] | python | train | 53 |
arviz-devs/arviz | arviz/plots/ppcplot.py | https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/plots/ppcplot.py#L20-L480 | def plot_ppc(
data,
kind="density",
alpha=None,
mean=True,
figsize=None,
textsize=None,
data_pairs=None,
var_names=None,
coords=None,
flatten=None,
flatten_pp=None,
num_pp_samples=None,
random_seed=None,
jitter=None,
animated=False,
animation_kwargs=None,
... | [
"def",
"plot_ppc",
"(",
"data",
",",
"kind",
"=",
"\"density\"",
",",
"alpha",
"=",
"None",
",",
"mean",
"=",
"True",
",",
"figsize",
"=",
"None",
",",
"textsize",
"=",
"None",
",",
"data_pairs",
"=",
"None",
",",
"var_names",
"=",
"None",
",",
"coor... | Plot for posterior predictive checks.
Parameters
----------
data : az.InferenceData object
InferenceData object containing the observed and posterior
predictive data.
kind : str
Type of plot to display (density, cumulative, or scatter). Defaults to density.
alpha : float
... | [
"Plot",
"for",
"posterior",
"predictive",
"checks",
"."
] | python | train | 35.442516 |
apache/incubator-mxnet | python/mxnet/ndarray/ndarray.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L3333-L3393 | def greater_equal(lhs, rhs):
"""Returns the result of element-wise **greater than or equal to** (>=) comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,
otherwise return 0(false).
Equivalent to ``lhs >= rhs`` and `... | [
"def",
"greater_equal",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"return",
"_ufunc_helper",
"(",
"lhs",
",",
"rhs",
",",
"op",
".",
"broadcast_greater_equal",
",",
"lambda",
"x",
",",
"y",
":",
"1",
"if",
"x",
">=",
... | Returns the result of element-wise **greater than or equal to** (>=) comparison
operation with broadcasting.
For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs,
otherwise return 0(false).
Equivalent to ``lhs >= rhs`` and ``mx.nd.broadcast_greater_equal(lhs, ... | [
"Returns",
"the",
"result",
"of",
"element",
"-",
"wise",
"**",
"greater",
"than",
"or",
"equal",
"to",
"**",
"(",
">",
"=",
")",
"comparison",
"operation",
"with",
"broadcasting",
"."
] | python | train | 30.540984 |
databio/pypiper | pypiper/ngstk.py | https://github.com/databio/pypiper/blob/00e6c2b94033c4187d47ff14c5580bbfc2ff097f/pypiper/ngstk.py#L1706-L1715 | def get_peak_number(self, sample):
"""
Counts number of peaks from a sample's peak file.
:param pipelines.Sample sample: Sample object with "peaks" attribute.
"""
proc = subprocess.Popen(["wc", "-l", sample.peaks], stdout=subprocess.PIPE)
out, err = proc.communicate()
... | [
"def",
"get_peak_number",
"(",
"self",
",",
"sample",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"wc\"",
",",
"\"-l\"",
",",
"sample",
".",
"peaks",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
... | Counts number of peaks from a sample's peak file.
:param pipelines.Sample sample: Sample object with "peaks" attribute. | [
"Counts",
"number",
"of",
"peaks",
"from",
"a",
"sample",
"s",
"peak",
"file",
"."
] | python | train | 38.5 |
google/grr | grr/core/grr_response_core/lib/config_lib.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/config_lib.py#L1509-L1514 | def DEFINE_choice(self, name, default, choices, help, constant=False):
"""A helper for defining choice string options."""
self.AddOption(
type_info.Choice(
name=name, default=default, choices=choices, description=help),
constant=constant) | [
"def",
"DEFINE_choice",
"(",
"self",
",",
"name",
",",
"default",
",",
"choices",
",",
"help",
",",
"constant",
"=",
"False",
")",
":",
"self",
".",
"AddOption",
"(",
"type_info",
".",
"Choice",
"(",
"name",
"=",
"name",
",",
"default",
"=",
"default",... | A helper for defining choice string options. | [
"A",
"helper",
"for",
"defining",
"choice",
"string",
"options",
"."
] | python | train | 44.833333 |
heuer/segno | segno/encoder.py | https://github.com/heuer/segno/blob/64d912a2bd17d0b5ff3e8b5d37098edfc663c2b3/segno/encoder.py#L1206-L1242 | def make_matrix(version, reserve_regions=True, add_timing=True):
"""\
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The... | [
"def",
"make_matrix",
"(",
"version",
",",
"reserve_regions",
"=",
"True",
",",
"add_timing",
"=",
"True",
")",
":",
"size",
"=",
"calc_matrix_size",
"(",
"version",
")",
"row",
"=",
"[",
"0x2",
"]",
"*",
"size",
"matrix",
"=",
"tuple",
"(",
"[",
"byte... | \
Creates a matrix of the provided `size` (w x h) initialized with the
(illegal) value 0x2.
The "timing pattern" is already added to the matrix and the version
and format areas are initialized with 0x0.
:param int version: The (Micro) QR Code version
:rtype: tuple of bytearrays | [
"\\",
"Creates",
"a",
"matrix",
"of",
"the",
"provided",
"size",
"(",
"w",
"x",
"h",
")",
"initialized",
"with",
"the",
"(",
"illegal",
")",
"value",
"0x2",
"."
] | python | train | 35.27027 |
programa-stic/barf-project | barf/core/smt/smttranslator.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L251-L257 | def _translate_dst_oprnd(self, operand):
"""Translate destination operand to a SMT expression.
"""
if isinstance(operand, ReilRegisterOperand):
return self._translate_dst_register_oprnd(operand)
else:
raise Exception("Invalid operand type") | [
"def",
"_translate_dst_oprnd",
"(",
"self",
",",
"operand",
")",
":",
"if",
"isinstance",
"(",
"operand",
",",
"ReilRegisterOperand",
")",
":",
"return",
"self",
".",
"_translate_dst_register_oprnd",
"(",
"operand",
")",
"else",
":",
"raise",
"Exception",
"(",
... | Translate destination operand to a SMT expression. | [
"Translate",
"destination",
"operand",
"to",
"a",
"SMT",
"expression",
"."
] | python | train | 41.428571 |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/util.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/util.py#L56-L97 | def separate_groups(groups, key, total):
"""Separate the group into overloaded and under-loaded groups.
The revised over-loaded groups increases the choice space for future
selection of most suitable group based on search criteria.
For example:
Given the groups (a:4, b:4, c:3, d:2) where the numbe... | [
"def",
"separate_groups",
"(",
"groups",
",",
"key",
",",
"total",
")",
":",
"optimum",
",",
"extra",
"=",
"compute_optimum",
"(",
"len",
"(",
"groups",
")",
",",
"total",
")",
"over_loaded",
",",
"under_loaded",
",",
"optimal",
"=",
"_smart_separate_groups"... | Separate the group into overloaded and under-loaded groups.
The revised over-loaded groups increases the choice space for future
selection of most suitable group based on search criteria.
For example:
Given the groups (a:4, b:4, c:3, d:2) where the number represents the number
of elements for each... | [
"Separate",
"the",
"group",
"into",
"overloaded",
"and",
"under",
"-",
"loaded",
"groups",
"."
] | python | train | 39.857143 |
pre-commit/pre-commit-mirror-maker | pre_commit_mirror_maker/main.py | https://github.com/pre-commit/pre-commit-mirror-maker/blob/8bafa3b87e67d291d5a747f0137b921a170a1723/pre_commit_mirror_maker/main.py#L12-L28 | def split_by_commas(maybe_s: str) -> Tuple[str, ...]:
"""Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas
"""
if not maybe_s:
return ()
parts: List[str] = []
split_by_backslash = maybe_s.split(r'\,')
fo... | [
"def",
"split_by_commas",
"(",
"maybe_s",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"if",
"not",
"maybe_s",
":",
"return",
"(",
")",
"parts",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"split_by_backslash",
"=",
"maybe_s",
... | Split a string by commas, but allow escaped commas.
- If maybe_s is falsey, returns an empty tuple
- Ignore backslashed commas | [
"Split",
"a",
"string",
"by",
"commas",
"but",
"allow",
"escaped",
"commas",
".",
"-",
"If",
"maybe_s",
"is",
"falsey",
"returns",
"an",
"empty",
"tuple",
"-",
"Ignore",
"backslashed",
"commas"
] | python | train | 35.176471 |
pandas-dev/pandas | pandas/core/frame.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/frame.py#L5332-L5406 | def combine_first(self, other):
"""
Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting DataFrame will be the... | [
"def",
"combine_first",
"(",
"self",
",",
"other",
")",
":",
"import",
"pandas",
".",
"core",
".",
"computation",
".",
"expressions",
"as",
"expressions",
"def",
"extract_values",
"(",
"arr",
")",
":",
"# Does two things:",
"# 1. maybe gets the values from the Serie... | Update null elements with value in the same location in `other`.
Combine two DataFrame objects by filling null values in one DataFrame
with non-null values from other DataFrame. The row and column indexes
of the resulting DataFrame will be the union of the two.
Parameters
-----... | [
"Update",
"null",
"elements",
"with",
"value",
"in",
"the",
"same",
"location",
"in",
"other",
"."
] | python | train | 31.053333 |
johntruckenbrodt/spatialist | spatialist/raster.py | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L590-L607 | def is_valid(self):
"""
Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
... | [
"def",
"is_valid",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"raster",
".",
"RasterCount",
")",
":",
"try",
":",
"checksum",
"=",
"self",
".",
"raster",
".",
"GetRasterBand",
"(",
"i",
"+",
"1",
")",
".",
"Checksum",
"(",
... | Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
-------
bool
i... | [
"Check",
"image",
"integrity",
".",
"Tries",
"to",
"compute",
"the",
"checksum",
"for",
"each",
"raster",
"layer",
"and",
"returns",
"False",
"if",
"this",
"fails",
".",
"See",
"this",
"forum",
"entry",
":",
"How",
"to",
"check",
"if",
"image",
"is",
"va... | python | train | 32.833333 |
benspaulding/django-faq | faq/views/normal.py | https://github.com/benspaulding/django-faq/blob/9a744e7c1943fd05bfa42c84b2ce003367c58e6e/faq/views/normal.py#L11-L30 | def topic_detail(request, slug):
"""
A detail view of a Topic
Templates:
:template:`faq/topic_detail.html`
Context:
topic
An :model:`faq.Topic` object.
question_list
A list of all published :model:`faq.Question` objects that relate
to the give... | [
"def",
"topic_detail",
"(",
"request",
",",
"slug",
")",
":",
"extra_context",
"=",
"{",
"'question_list'",
":",
"Question",
".",
"objects",
".",
"published",
"(",
")",
".",
"filter",
"(",
"topic__slug",
"=",
"slug",
")",
",",
"}",
"return",
"object_detail... | A detail view of a Topic
Templates:
:template:`faq/topic_detail.html`
Context:
topic
An :model:`faq.Topic` object.
question_list
A list of all published :model:`faq.Question` objects that relate
to the given :model:`faq.Topic`. | [
"A",
"detail",
"view",
"of",
"a",
"Topic"
] | python | train | 29.4 |
PmagPy/PmagPy | programs/demag_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L6067-L6153 | def update_selection(self):
"""
Convenience function update display (figures, text boxes and
statistics windows) with a new selection of specimen
"""
self.clear_boxes()
# commented out to allow propogation of higher level viewing state
self.clear_high_level_pars(... | [
"def",
"update_selection",
"(",
"self",
")",
":",
"self",
".",
"clear_boxes",
"(",
")",
"# commented out to allow propogation of higher level viewing state",
"self",
".",
"clear_high_level_pars",
"(",
")",
"if",
"self",
".",
"UPPER_LEVEL_SHOW",
"!=",
"\"specimens\"",
":... | Convenience function update display (figures, text boxes and
statistics windows) with a new selection of specimen | [
"Convenience",
"function",
"update",
"display",
"(",
"figures",
"text",
"boxes",
"and",
"statistics",
"windows",
")",
"with",
"a",
"new",
"selection",
"of",
"specimen"
] | python | train | 37.356322 |
mickybart/python-atlasbroker | atlasbroker/service.py | https://github.com/mickybart/python-atlasbroker/blob/5b741c1348a6d33b342e0852a8a8900fa9ebf00a/atlasbroker/service.py#L74-L93 | def provision(self, instance_id: str, service_details: ProvisionDetails, async_allowed: bool) -> ProvisionedServiceSpec:
"""Provision the new instance
see openbrokerapi documentation
Returns:
ProvisionedServiceSpec
"""
if service_details.pla... | [
"def",
"provision",
"(",
"self",
",",
"instance_id",
":",
"str",
",",
"service_details",
":",
"ProvisionDetails",
",",
"async_allowed",
":",
"bool",
")",
"->",
"ProvisionedServiceSpec",
":",
"if",
"service_details",
".",
"plan_id",
"==",
"self",
".",
"_backend",... | Provision the new instance
see openbrokerapi documentation
Returns:
ProvisionedServiceSpec | [
"Provision",
"the",
"new",
"instance",
"see",
"openbrokerapi",
"documentation",
"Returns",
":",
"ProvisionedServiceSpec"
] | python | train | 39 |
dfm/george | george/solvers/basic.py | https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/solvers/basic.py#L89-L102 | def dot_solve(self, y):
r"""
Compute the inner product of a vector with the inverse of the
covariance matrix applied to itself:
.. math::
y\,K^{-1}\,y
Args:
y (ndarray[nsamples]): The vector :math:`y`.
"""
return np.dot(y.T, cho_solve(s... | [
"def",
"dot_solve",
"(",
"self",
",",
"y",
")",
":",
"return",
"np",
".",
"dot",
"(",
"y",
".",
"T",
",",
"cho_solve",
"(",
"self",
".",
"_factor",
",",
"y",
")",
")"
] | r"""
Compute the inner product of a vector with the inverse of the
covariance matrix applied to itself:
.. math::
y\,K^{-1}\,y
Args:
y (ndarray[nsamples]): The vector :math:`y`. | [
"r",
"Compute",
"the",
"inner",
"product",
"of",
"a",
"vector",
"with",
"the",
"inverse",
"of",
"the",
"covariance",
"matrix",
"applied",
"to",
"itself",
":"
] | python | train | 23.071429 |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1049-L1074 | def _extract_services_list_helper(services):
"""Extract a OrderedDict of {service: [ports]} of the supplied services
for use by the other functions.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optional... | [
"def",
"_extract_services_list_helper",
"(",
"services",
")",
":",
"if",
"services",
"is",
"None",
":",
"return",
"{",
"}",
"if",
"isinstance",
"(",
"services",
",",
"dict",
")",
":",
"services",
"=",
"services",
".",
"values",
"(",
")",
"# either extract th... | Extract a OrderedDict of {service: [ports]} of the supplied services
for use by the other functions.
The services object can either be:
- None : no services were passed (an empty dict is returned)
- a list of strings
- A dictionary (optionally OrderedDict) {service_name: {'service': ..}}
... | [
"Extract",
"a",
"OrderedDict",
"of",
"{",
"service",
":",
"[",
"ports",
"]",
"}",
"of",
"the",
"supplied",
"services",
"for",
"use",
"by",
"the",
"other",
"functions",
"."
] | python | train | 36.730769 |
lmjohns3/theanets | theanets/feedforward.py | https://github.com/lmjohns3/theanets/blob/79db9f878ef2071f2f576a1cf5d43a752a55894a/theanets/feedforward.py#L363-L374 | def monitors(self, **kwargs):
'''Return expressions that should be computed to monitor training.
Returns
-------
monitors : list of (name, expression) pairs
A list of named monitor expressions to compute for this network.
'''
monitors = super(Classifier, self... | [
"def",
"monitors",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"monitors",
"=",
"super",
"(",
"Classifier",
",",
"self",
")",
".",
"monitors",
"(",
"*",
"*",
"kwargs",
")",
"regs",
"=",
"regularizers",
".",
"from_kwargs",
"(",
"self",
",",
"*",
... | Return expressions that should be computed to monitor training.
Returns
-------
monitors : list of (name, expression) pairs
A list of named monitor expressions to compute for this network. | [
"Return",
"expressions",
"that",
"should",
"be",
"computed",
"to",
"monitor",
"training",
"."
] | python | test | 41.583333 |
bitesofcode/projexui | projexui/widgets/xtoolbutton.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtoolbutton.py#L94-L110 | def blink(self, state=True):
"""
Starts or stops the blinking state for this button. This only
works for when the toolbutton is in Shadowed or Colored mode.
:param state | <bool>
:return <bool> | success
"""
if self._blinking =... | [
"def",
"blink",
"(",
"self",
",",
"state",
"=",
"True",
")",
":",
"if",
"self",
".",
"_blinking",
"==",
"state",
":",
"return",
"True",
"elif",
"not",
"self",
".",
"graphicsEffect",
"(",
")",
":",
"return",
"False",
"else",
":",
"self",
".",
"_blinki... | Starts or stops the blinking state for this button. This only
works for when the toolbutton is in Shadowed or Colored mode.
:param state | <bool>
:return <bool> | success | [
"Starts",
"or",
"stops",
"the",
"blinking",
"state",
"for",
"this",
"button",
".",
"This",
"only",
"works",
"for",
"when",
"the",
"toolbutton",
"is",
"in",
"Shadowed",
"or",
"Colored",
"mode",
".",
":",
"param",
"state",
"|",
"<bool",
">",
":",
"return",... | python | train | 31.352941 |
apache/incubator-mxnet | python/mxnet/module/python_module.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/python_module.py#L285-L302 | def forward(self, data_batch, is_train=None):
"""Forward computation. Here we do nothing but to keep a reference to
the scores and the labels so that we can do backward computation.
Parameters
----------
data_batch : DataBatch
Could be anything with similar API imple... | [
"def",
"forward",
"(",
"self",
",",
"data_batch",
",",
"is_train",
"=",
"None",
")",
":",
"self",
".",
"_scores",
"=",
"data_batch",
".",
"data",
"[",
"0",
"]",
"if",
"is_train",
"is",
"None",
":",
"is_train",
"=",
"self",
".",
"for_training",
"if",
... | Forward computation. Here we do nothing but to keep a reference to
the scores and the labels so that we can do backward computation.
Parameters
----------
data_batch : DataBatch
Could be anything with similar API implemented.
is_train : bool
Default is ``... | [
"Forward",
"computation",
".",
"Here",
"we",
"do",
"nothing",
"but",
"to",
"keep",
"a",
"reference",
"to",
"the",
"scores",
"and",
"the",
"labels",
"so",
"that",
"we",
"can",
"do",
"backward",
"computation",
"."
] | python | train | 34.777778 |
tanghaibao/goatools | goatools/cli/compare_gos.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L214-L218 | def get_grouped(self, go_ntsets, go_all, gosubdag, **kws):
"""Get Grouped object."""
kws_grpd = {k:v for k, v in kws.items() if k in Grouped.kws_dict}
kws_grpd['go2nt'] = self._init_go2ntpresent(go_ntsets, go_all, gosubdag)
return Grouped(gosubdag, self.godag.version, **kws_grpd) | [
"def",
"get_grouped",
"(",
"self",
",",
"go_ntsets",
",",
"go_all",
",",
"gosubdag",
",",
"*",
"*",
"kws",
")",
":",
"kws_grpd",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kws",
".",
"items",
"(",
")",
"if",
"k",
"in",
"Grouped",
"."... | Get Grouped object. | [
"Get",
"Grouped",
"object",
"."
] | python | train | 61.6 |
sjkingo/python-freshdesk | freshdesk/v2/api.py | https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L461-L464 | def _delete(self, url):
"""Wrapper around request.delete() to use the API prefix. Returns a JSON response."""
req = self._session.delete(self._api_prefix + url)
return self._action(req) | [
"def",
"_delete",
"(",
"self",
",",
"url",
")",
":",
"req",
"=",
"self",
".",
"_session",
".",
"delete",
"(",
"self",
".",
"_api_prefix",
"+",
"url",
")",
"return",
"self",
".",
"_action",
"(",
"req",
")"
] | Wrapper around request.delete() to use the API prefix. Returns a JSON response. | [
"Wrapper",
"around",
"request",
".",
"delete",
"()",
"to",
"use",
"the",
"API",
"prefix",
".",
"Returns",
"a",
"JSON",
"response",
"."
] | python | train | 51.5 |
mcieslik-mctp/papy | src/papy/graph.py | https://github.com/mcieslik-mctp/papy/blob/708e50827b5db46bbea081982cb74b9b0e464064/src/papy/graph.py#L228-L237 | def rank_width(self):
"""
Returns the width of each rank in the graph. #TODO
"""
rank_width = defaultdict(int)
node_rank = self.node_rank()
for rank in node_rank.values():
rank_width[rank] += 1
return dict(rank_width) | [
"def",
"rank_width",
"(",
"self",
")",
":",
"rank_width",
"=",
"defaultdict",
"(",
"int",
")",
"node_rank",
"=",
"self",
".",
"node_rank",
"(",
")",
"for",
"rank",
"in",
"node_rank",
".",
"values",
"(",
")",
":",
"rank_width",
"[",
"rank",
"]",
"+=",
... | Returns the width of each rank in the graph. #TODO | [
"Returns",
"the",
"width",
"of",
"each",
"rank",
"in",
"the",
"graph",
".",
"#TODO"
] | python | train | 28.5 |
couchbase/couchbase-python-client | couchbase/connstr.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/connstr.py#L156-L170 | def _build_connstr(host, port, bucket):
"""
Converts a 1.x host:port specification to a connection string
"""
hostlist = []
if isinstance(host, (tuple, list)):
for curhost in host:
if isinstance(curhost, (list, tuple)):
hostlist.append(_fmthost(*curhost))
... | [
"def",
"_build_connstr",
"(",
"host",
",",
"port",
",",
"bucket",
")",
":",
"hostlist",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"host",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"curhost",
"in",
"host",
":",
"if",
"isinstance",
"(",
"cu... | Converts a 1.x host:port specification to a connection string | [
"Converts",
"a",
"1",
".",
"x",
"host",
":",
"port",
"specification",
"to",
"a",
"connection",
"string"
] | python | train | 31.733333 |
Miserlou/Zappa | zappa/core.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L866-L909 | def get_manylinux_wheel_url(self, package_name, package_version):
"""
For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b5688... | [
"def",
"get_manylinux_wheel_url",
"(",
"self",
",",
"package_name",
",",
"package_version",
")",
":",
"cached_pypi_info_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'cached_pypi_info'",
")",
"if",
"not",
"os",
... | For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae
This function downloads metadata JSON of `package_name` from Pypi
... | [
"For",
"a",
"given",
"package",
"name",
"returns",
"a",
"link",
"to",
"the",
"download",
"URL",
"else",
"returns",
"None",
"."
] | python | train | 46.545455 |
ministryofjustice/money-to-prisoners-common | build_tasks.py | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/build_tasks.py#L140-L173 | def set_version(context: Context, version=None, bump=False):
"""
Updates the version of MTP-common
"""
if bump and version:
raise TaskError('You cannot bump and set a specific version')
if bump:
from mtp_common import VERSION
version = list(VERSION)
version[-1] += 1
... | [
"def",
"set_version",
"(",
"context",
":",
"Context",
",",
"version",
"=",
"None",
",",
"bump",
"=",
"False",
")",
":",
"if",
"bump",
"and",
"version",
":",
"raise",
"TaskError",
"(",
"'You cannot bump and set a specific version'",
")",
"if",
"bump",
":",
"f... | Updates the version of MTP-common | [
"Updates",
"the",
"version",
"of",
"MTP",
"-",
"common"
] | python | train | 35.058824 |
apache/airflow | airflow/contrib/operators/gcp_transfer_operator.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/gcp_transfer_operator.py#L106-L110 | def _convert_date_to_dict(field_date):
"""
Convert native python ``datetime.date`` object to a format supported by the API
"""
return {DAY: field_date.day, MONTH: field_date.month, YEAR: field_date.year} | [
"def",
"_convert_date_to_dict",
"(",
"field_date",
")",
":",
"return",
"{",
"DAY",
":",
"field_date",
".",
"day",
",",
"MONTH",
":",
"field_date",
".",
"month",
",",
"YEAR",
":",
"field_date",
".",
"year",
"}"
] | Convert native python ``datetime.date`` object to a format supported by the API | [
"Convert",
"native",
"python",
"datetime",
".",
"date",
"object",
"to",
"a",
"format",
"supported",
"by",
"the",
"API"
] | python | test | 46.4 |
jsommers/switchyard | switchyard/lib/topo/topobuild.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/topo/topobuild.py#L393-L412 | def union(self, other, rename=False):
'''
Union/add two topologies together to form a larger topology.
If rename is False, the method assumes that node names
don't clash (i.e., you've called addNodeLabelPrefix or
you've explicitly chosen names to avoid clashes).
If r... | [
"def",
"union",
"(",
"self",
",",
"other",
",",
"rename",
"=",
"False",
")",
":",
"if",
"rename",
":",
"self",
".",
"nxgraph",
"=",
"Topology",
".",
"__relabel_graph",
"(",
"self",
".",
"__nxgraph",
",",
"self",
".",
"name",
")",
"other",
".",
"nxgra... | Union/add two topologies together to form a larger topology.
If rename is False, the method assumes that node names
don't clash (i.e., you've called addNodeLabelPrefix or
you've explicitly chosen names to avoid clashes).
If rename is True, nodes/links are relabeled such that the
... | [
"Union",
"/",
"add",
"two",
"topologies",
"together",
"to",
"form",
"a",
"larger",
"topology",
"."
] | python | train | 49.6 |
mkouhei/bootstrap-py | bootstrap_py/control.py | https://github.com/mkouhei/bootstrap-py/blob/95d56ed98ef409fd9f019dc352fd1c3711533275/bootstrap_py/control.py#L39-L47 | def check_repository_existence(params):
"""Check repository existence.
:param argparse.Namespace params: parameters
"""
repodir = os.path.join(params.outdir, params.name)
if os.path.isdir(repodir):
raise Conflict(
'Package repository "{0}" has already exists.'.format(repodir)) | [
"def",
"check_repository_existence",
"(",
"params",
")",
":",
"repodir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"params",
".",
"outdir",
",",
"params",
".",
"name",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"repodir",
")",
":",
"raise",
"Co... | Check repository existence.
:param argparse.Namespace params: parameters | [
"Check",
"repository",
"existence",
"."
] | python | train | 34.444444 |
googleads/googleads-python-lib | googleads/common.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/common.py#L1096-L1110 | def egress(self, envelope, http_headers, operation, binding_options):
"""Overriding the egress function to set our headers.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An... | [
"def",
"egress",
"(",
"self",
",",
"envelope",
",",
"http_headers",
",",
"operation",
",",
"binding_options",
")",
":",
"custom_headers",
"=",
"self",
".",
"_header_handler",
".",
"GetHTTPHeaders",
"(",
")",
"http_headers",
".",
"update",
"(",
"custom_headers",
... | Overriding the egress function to set our headers.
Args:
envelope: An Element with the SOAP request data.
http_headers: A dict of the current http headers.
operation: The SoapOperation instance.
binding_options: An options dict for the SOAP binding.
Returns:
A tuple of the envelo... | [
"Overriding",
"the",
"egress",
"function",
"to",
"set",
"our",
"headers",
"."
] | python | train | 35.933333 |
developersociety/django-glitter | glitter/blocks/video/validators.py | https://github.com/developersociety/django-glitter/blob/2c0280ec83afee80deee94ee3934fc54239c2e87/glitter/blocks/video/validators.py#L45-L48 | def validate_url(value):
""" Validate url. """
if not re.match(VIMEO_URL_RE, value) and not re.match(YOUTUBE_URL_RE, value):
raise ValidationError('Invalid URL - only Youtube, Vimeo can be used.') | [
"def",
"validate_url",
"(",
"value",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"VIMEO_URL_RE",
",",
"value",
")",
"and",
"not",
"re",
".",
"match",
"(",
"YOUTUBE_URL_RE",
",",
"value",
")",
":",
"raise",
"ValidationError",
"(",
"'Invalid URL - only Y... | Validate url. | [
"Validate",
"url",
"."
] | python | train | 52.25 |
ActivisionGameScience/assertpy | assertpy/assertpy.py | https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L339-L346 | def does_not_contain_duplicates(self):
"""Asserts that val is iterable and does not contain any duplicate items."""
try:
if len(self.val) == len(set(self.val)):
return self
except TypeError:
raise TypeError('val is not iterable')
self._err('Expecte... | [
"def",
"does_not_contain_duplicates",
"(",
"self",
")",
":",
"try",
":",
"if",
"len",
"(",
"self",
".",
"val",
")",
"==",
"len",
"(",
"set",
"(",
"self",
".",
"val",
")",
")",
":",
"return",
"self",
"except",
"TypeError",
":",
"raise",
"TypeError",
"... | Asserts that val is iterable and does not contain any duplicate items. | [
"Asserts",
"that",
"val",
"is",
"iterable",
"and",
"does",
"not",
"contain",
"any",
"duplicate",
"items",
"."
] | python | valid | 46 |
caseyjlaw/rtpipe | rtpipe/parsecal.py | https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/parsecal.py#L413-L422 | def flagants(self, threshold=50):
""" Flags solutions with amplitude more than threshold larger than median.
"""
# identify very low gain amps not already flagged
badsols = n.where( (n.median(self.amp)/self.amp > threshold) & (self.flagged == False))[0]
if len(badsols):
... | [
"def",
"flagants",
"(",
"self",
",",
"threshold",
"=",
"50",
")",
":",
"# identify very low gain amps not already flagged",
"badsols",
"=",
"n",
".",
"where",
"(",
"(",
"n",
".",
"median",
"(",
"self",
".",
"amp",
")",
"/",
"self",
".",
"amp",
">",
"thre... | Flags solutions with amplitude more than threshold larger than median. | [
"Flags",
"solutions",
"with",
"amplitude",
"more",
"than",
"threshold",
"larger",
"than",
"median",
"."
] | python | train | 56.1 |
bachiraoun/pysimplelog | SimpleLog.py | https://github.com/bachiraoun/pysimplelog/blob/2681ed5b1b8d7e66c3fff3ec3cca2b14ac571238/SimpleLog.py#L872-L883 | def set_log_type_name(self, logType, name):
"""
Set a logtype name.
:Parameters:
#. logType (string): A defined logging type.
#. name (string): The logtype new name.
"""
assert logType in self.__logTypeStdoutFlags.keys(), "logType '%s' not defined" %logType... | [
"def",
"set_log_type_name",
"(",
"self",
",",
"logType",
",",
"name",
")",
":",
"assert",
"logType",
"in",
"self",
".",
"__logTypeStdoutFlags",
".",
"keys",
"(",
")",
",",
"\"logType '%s' not defined\"",
"%",
"logType",
"assert",
"isinstance",
"(",
"name",
","... | Set a logtype name.
:Parameters:
#. logType (string): A defined logging type.
#. name (string): The logtype new name. | [
"Set",
"a",
"logtype",
"name",
"."
] | python | train | 37.25 |
manahl/arctic | arctic/chunkstore/chunkstore.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/chunkstore/chunkstore.py#L306-L404 | def write(self, symbol, item, metadata=None, chunker=DateChunker(), audit=None, **kwargs):
"""
Writes data from item to symbol in the database
Parameters
----------
symbol: str
the symbol that will be used to reference the written data
item: Dataframe or Seri... | [
"def",
"write",
"(",
"self",
",",
"symbol",
",",
"item",
",",
"metadata",
"=",
"None",
",",
"chunker",
"=",
"DateChunker",
"(",
")",
",",
"audit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"(",
"... | Writes data from item to symbol in the database
Parameters
----------
symbol: str
the symbol that will be used to reference the written data
item: Dataframe or Series
the data to write the database
metadata: ?
optional per symbol metadata
... | [
"Writes",
"data",
"from",
"item",
"to",
"symbol",
"in",
"the",
"database"
] | python | train | 41.767677 |
edx/edx-enterprise | enterprise/admin/forms.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L388-L398 | def clean(self):
"""
Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field.
"""
cleaned_data = super(EnterpriseCustomerAdminForm, self).clean()
if 'catalog' in cle... | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"EnterpriseCustomerAdminForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"if",
"'catalog'",
"in",
"cleaned_data",
"and",
"not",
"cleaned_data",
"[",
"'catalog'",
"]",
":",
"cleaned_dat... | Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field. | [
"Clean",
"form",
"fields",
"prior",
"to",
"database",
"entry",
"."
] | python | valid | 38.454545 |
fastai/fastai | fastai/torch_core.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L377-L381 | def flatten_check(out:Tensor, targ:Tensor) -> Tensor:
"Check that `out` and `targ` have the same number of elements and flatten them."
out,targ = out.contiguous().view(-1),targ.contiguous().view(-1)
assert len(out) == len(targ), f"Expected output and target to have the same number of elements but got {len(o... | [
"def",
"flatten_check",
"(",
"out",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"out",
",",
"targ",
"=",
"out",
".",
"contiguous",
"(",
")",
".",
"view",
"(",
"-",
"1",
")",
",",
"targ",
".",
"contiguous",
"(",
")",
".",
... | Check that `out` and `targ` have the same number of elements and flatten them. | [
"Check",
"that",
"out",
"and",
"targ",
"have",
"the",
"same",
"number",
"of",
"elements",
"and",
"flatten",
"them",
"."
] | python | train | 71.6 |
knipknap/SpiffWorkflow | SpiffWorkflow/task.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/task.py#L584-L590 | def complete(self):
"""
Called by the associated task to let us know that its state
has changed (e.g. from FUTURE to COMPLETED.)
"""
self._set_state(self.COMPLETED)
return self.task_spec._on_complete(self) | [
"def",
"complete",
"(",
"self",
")",
":",
"self",
".",
"_set_state",
"(",
"self",
".",
"COMPLETED",
")",
"return",
"self",
".",
"task_spec",
".",
"_on_complete",
"(",
"self",
")"
] | Called by the associated task to let us know that its state
has changed (e.g. from FUTURE to COMPLETED.) | [
"Called",
"by",
"the",
"associated",
"task",
"to",
"let",
"us",
"know",
"that",
"its",
"state",
"has",
"changed",
"(",
"e",
".",
"g",
".",
"from",
"FUTURE",
"to",
"COMPLETED",
".",
")"
] | python | valid | 35.285714 |
Zitrax/nose-dep | nosedep.py | https://github.com/Zitrax/nose-dep/blob/fd29c95e0e5eb2dbd821f6566b72dfcf42631226/nosedep.py#L195-L198 | def split_on_condition(seq, condition):
"""Split a sequence into two iterables without looping twice"""
l1, l2 = tee((condition(item), item) for item in seq)
return (i for p, i in l1 if p), (i for p, i in l2 if not p) | [
"def",
"split_on_condition",
"(",
"seq",
",",
"condition",
")",
":",
"l1",
",",
"l2",
"=",
"tee",
"(",
"(",
"condition",
"(",
"item",
")",
",",
"item",
")",
"for",
"item",
"in",
"seq",
")",
"return",
"(",
"i",
"for",
"p",
",",
"i",
"in",
"l1",
... | Split a sequence into two iterables without looping twice | [
"Split",
"a",
"sequence",
"into",
"two",
"iterables",
"without",
"looping",
"twice"
] | python | train | 56.5 |
gabstopper/smc-python | smc/elements/situations.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/situations.py#L291-L302 | def parameter_values(self):
"""
Parameter values for this inspection situation. This correlate to
the the situation_context.
:rtype: list(SituationParameterValue)
"""
for param in self.data.get('parameter_values', []):
cache = ElementCache(data=self.m... | [
"def",
"parameter_values",
"(",
"self",
")",
":",
"for",
"param",
"in",
"self",
".",
"data",
".",
"get",
"(",
"'parameter_values'",
",",
"[",
"]",
")",
":",
"cache",
"=",
"ElementCache",
"(",
"data",
"=",
"self",
".",
"make_request",
"(",
"href",
"=",
... | Parameter values for this inspection situation. This correlate to
the the situation_context.
:rtype: list(SituationParameterValue) | [
"Parameter",
"values",
"for",
"this",
"inspection",
"situation",
".",
"This",
"correlate",
"to",
"the",
"the",
"situation_context",
".",
":",
"rtype",
":",
"list",
"(",
"SituationParameterValue",
")"
] | python | train | 44.833333 |
ronaldguillen/wave | wave/serializers.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/serializers.py#L1078-L1124 | def build_standard_field(self, field_name, model_field):
"""
Create regular model fields.
"""
field_mapping = ClassLookupDict(self.serializer_field_mapping)
field_class = field_mapping[model_field]
field_kwargs = get_field_kwargs(field_name, model_field)
if 'cho... | [
"def",
"build_standard_field",
"(",
"self",
",",
"field_name",
",",
"model_field",
")",
":",
"field_mapping",
"=",
"ClassLookupDict",
"(",
"self",
".",
"serializer_field_mapping",
")",
"field_class",
"=",
"field_mapping",
"[",
"model_field",
"]",
"field_kwargs",
"="... | Create regular model fields. | [
"Create",
"regular",
"model",
"fields",
"."
] | python | train | 46.021277 |
Spinmob/spinmob | _data.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_data.py#L1022-L1055 | def pop_header(self, hkey, ignore_error=False):
"""
This will remove and return the specified header value.
Parameters
----------
hkey
Header key you wish to pop.
You can specify either a key string or an index.
ignore_error=False
Whe... | [
"def",
"pop_header",
"(",
"self",
",",
"hkey",
",",
"ignore_error",
"=",
"False",
")",
":",
"# try the integer approach first to allow negative values",
"if",
"type",
"(",
"hkey",
")",
"is",
"not",
"str",
":",
"try",
":",
"return",
"self",
".",
"headers",
".",... | This will remove and return the specified header value.
Parameters
----------
hkey
Header key you wish to pop.
You can specify either a key string or an index.
ignore_error=False
Whether to quietly ignore any errors (i.e., hkey not found). | [
"This",
"will",
"remove",
"and",
"return",
"the",
"specified",
"header",
"value",
"."
] | python | train | 32.352941 |
klmitch/turnstile | turnstile/limits.py | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/limits.py#L509-L513 | def messages(self):
"""Return remaining messages before limiting."""
return int(math.floor(((self.limit.unit_value - self.level) /
self.limit.unit_value) * self.limit.value)) | [
"def",
"messages",
"(",
"self",
")",
":",
"return",
"int",
"(",
"math",
".",
"floor",
"(",
"(",
"(",
"self",
".",
"limit",
".",
"unit_value",
"-",
"self",
".",
"level",
")",
"/",
"self",
".",
"limit",
".",
"unit_value",
")",
"*",
"self",
".",
"li... | Return remaining messages before limiting. | [
"Return",
"remaining",
"messages",
"before",
"limiting",
"."
] | python | train | 43.6 |
bastibe/SoundFile | soundfile.py | https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1273-L1282 | def _check_buffer(self, data, ctype):
"""Convert buffer to cdata and check for valid size."""
assert ctype in _ffi_types.values()
if not isinstance(data, bytes):
data = _ffi.from_buffer(data)
frames, remainder = divmod(len(data),
self.channe... | [
"def",
"_check_buffer",
"(",
"self",
",",
"data",
",",
"ctype",
")",
":",
"assert",
"ctype",
"in",
"_ffi_types",
".",
"values",
"(",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",
"=",
"_ffi",
".",
"from_buffer",
"(",
"d... | Convert buffer to cdata and check for valid size. | [
"Convert",
"buffer",
"to",
"cdata",
"and",
"check",
"for",
"valid",
"size",
"."
] | python | train | 46 |
Alignak-monitoring/alignak | alignak/http/arbiter_interface.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L820-L955 | def realms(self, details=False):
"""Return the realms / satellites configuration
Returns an object containing the hierarchical realms configuration with the main
information about each realm:
{
All: {
satellites: {
pollers: [
... | [
"def",
"realms",
"(",
"self",
",",
"details",
"=",
"False",
")",
":",
"def",
"get_realm_info",
"(",
"realm",
",",
"realms",
",",
"satellites",
",",
"details",
"=",
"False",
")",
":",
"\"\"\"Get the realm and its children information\n\n :return: None\n ... | Return the realms / satellites configuration
Returns an object containing the hierarchical realms configuration with the main
information about each realm:
{
All: {
satellites: {
pollers: [
"poller-master"
... | [
"Return",
"the",
"realms",
"/",
"satellites",
"configuration"
] | python | train | 39.397059 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_heliplane.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_heliplane.py#L31-L100 | def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
type = msg.get_type()
master = self.master
# add some status fields
if type in [ 'RC_CHANNELS' ]:
ilock = self.get_rc_input(msg, self.interlock_channel)
if ilock <= 0:
... | [
"def",
"mavlink_packet",
"(",
"self",
",",
"msg",
")",
":",
"type",
"=",
"msg",
".",
"get_type",
"(",
")",
"master",
"=",
"self",
".",
"master",
"# add some status fields",
"if",
"type",
"in",
"[",
"'RC_CHANNELS'",
"]",
":",
"ilock",
"=",
"self",
".",
... | handle an incoming mavlink packet | [
"handle",
"an",
"incoming",
"mavlink",
"packet"
] | python | train | 43.671429 |
dmwm/DBS | Server/Python/src/dbs/web/DBSReaderModel.py | https://github.com/dmwm/DBS/blob/9619bafce3783b3e77f0415f8f9a258e33dd1e6f/Server/Python/src/dbs/web/DBSReaderModel.py#L800-L850 | def listBlockSummaries(self, block_name="", dataset="", detail=False):
"""
API that returns summary information like total size and total number of events in a dataset or a list of blocks
:param block_name: list block summaries for block_name(s)
:type block_name: str, list
:para... | [
"def",
"listBlockSummaries",
"(",
"self",
",",
"block_name",
"=",
"\"\"",
",",
"dataset",
"=",
"\"\"",
",",
"detail",
"=",
"False",
")",
":",
"if",
"bool",
"(",
"dataset",
")",
"+",
"bool",
"(",
"block_name",
")",
"!=",
"1",
":",
"dbsExceptionHandler",
... | API that returns summary information like total size and total number of events in a dataset or a list of blocks
:param block_name: list block summaries for block_name(s)
:type block_name: str, list
:param dataset: list block summaries for all blocks in dataset
:type dataset: str
... | [
"API",
"that",
"returns",
"summary",
"information",
"like",
"total",
"size",
"and",
"total",
"number",
"of",
"events",
"in",
"a",
"dataset",
"or",
"a",
"list",
"of",
"blocks"
] | python | train | 51.764706 |
gamechanger/dusty | dusty/systems/docker/compose.py | https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/docker/compose.py#L64-L93 | def _compose_restart(services):
"""Well, this is annoying. Compose 1.2 shipped with the
restart functionality fucking broken, so we can't set a faster
timeout than 10 seconds (which is way too long) using Compose.
We are therefore resigned to trying to hack this together
ourselves. Lame.
Releva... | [
"def",
"_compose_restart",
"(",
"services",
")",
":",
"def",
"_restart_container",
"(",
"client",
",",
"container",
")",
":",
"log_to_client",
"(",
"'Restarting {}'",
".",
"format",
"(",
"get_canonical_container_name",
"(",
"container",
")",
")",
")",
"client",
... | Well, this is annoying. Compose 1.2 shipped with the
restart functionality fucking broken, so we can't set a faster
timeout than 10 seconds (which is way too long) using Compose.
We are therefore resigned to trying to hack this together
ourselves. Lame.
Relevant fix which will make it into the next... | [
"Well",
"this",
"is",
"annoying",
".",
"Compose",
"1",
".",
"2",
"shipped",
"with",
"the",
"restart",
"functionality",
"fucking",
"broken",
"so",
"we",
"can",
"t",
"set",
"a",
"faster",
"timeout",
"than",
"10",
"seconds",
"(",
"which",
"is",
"way",
"too"... | python | valid | 48.4 |
aiidateam/aiida-codtools | aiida_codtools/cli/workflows/cif_clean.py | https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/cli/workflows/cif_clean.py#L46-L176 | def launch_cif_clean(cif_filter, cif_select, group_cif_raw, group_cif_clean, group_structure, group_workchain, node,
max_entries, skip_check, parse_engine, daemon):
"""Run the `CifCleanWorkChain` on the entries in a group with raw imported CifData nodes.
It will use the `cif_filter` and `cif_select` script... | [
"def",
"launch_cif_clean",
"(",
"cif_filter",
",",
"cif_select",
",",
"group_cif_raw",
",",
"group_cif_clean",
",",
"group_structure",
",",
"group_workchain",
",",
"node",
",",
"max_entries",
",",
"skip_check",
",",
"parse_engine",
",",
"daemon",
")",
":",
"# pyli... | Run the `CifCleanWorkChain` on the entries in a group with raw imported CifData nodes.
It will use the `cif_filter` and `cif_select` scripts of `cod-tools` to clean the input cif file. Additionally, if
the `group-structure` option is passed, the workchain will also attempt to use the given parse engine to pars... | [
"Run",
"the",
"CifCleanWorkChain",
"on",
"the",
"entries",
"in",
"a",
"group",
"with",
"raw",
"imported",
"CifData",
"nodes",
"."
] | python | train | 40.427481 |
djgagne/hagelslag | hagelslag/evaluation/ProbabilityMetrics.py | https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/evaluation/ProbabilityMetrics.py#L108-L118 | def merge(self, other_roc):
"""
Ingest the values of another DistributedROC object into this one and update the statistics inplace.
Args:
other_roc: another DistributedROC object.
"""
if other_roc.thresholds.size == self.thresholds.size and np.all(other_roc.threshold... | [
"def",
"merge",
"(",
"self",
",",
"other_roc",
")",
":",
"if",
"other_roc",
".",
"thresholds",
".",
"size",
"==",
"self",
".",
"thresholds",
".",
"size",
"and",
"np",
".",
"all",
"(",
"other_roc",
".",
"thresholds",
"==",
"self",
".",
"thresholds",
")"... | Ingest the values of another DistributedROC object into this one and update the statistics inplace.
Args:
other_roc: another DistributedROC object. | [
"Ingest",
"the",
"values",
"of",
"another",
"DistributedROC",
"object",
"into",
"this",
"one",
"and",
"update",
"the",
"statistics",
"inplace",
"."
] | python | train | 42.909091 |
Legobot/Legobot | Legobot/Connectors/Discord.py | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L109-L122 | def create_message(self, channel_id, text):
"""
Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message
"""
baseurl = self.rest_baseurl + \
'/ch... | [
"def",
"create_message",
"(",
"self",
",",
"channel_id",
",",
"text",
")",
":",
"baseurl",
"=",
"self",
".",
"rest_baseurl",
"+",
"'/channels/{}/messages'",
".",
"format",
"(",
"channel_id",
")",
"requests",
".",
"post",
"(",
"baseurl",
",",
"headers",
"=",
... | Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message | [
"Sends",
"a",
"message",
"to",
"a",
"Discord",
"channel",
"or",
"user",
"via",
"REST",
"API"
] | python | train | 34.142857 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py#L399-L408 | def OSPFNeighborState_NeighborState(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
OSPFNeighborState = ET.SubElement(config, "OSPFNeighborState", xmlns="http://brocade.com/ns/brocade-notification-stream")
NeighborState = ET.SubElement(OSPFNeighborState,... | [
"def",
"OSPFNeighborState_NeighborState",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"OSPFNeighborState",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"OSPFNeighborState\"",
",",
"xmlns",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 47.6 |
jobovy/galpy | galpy/potential/verticalPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/verticalPotential.py#L129-L184 | def toVerticalPotential(Pot,R,phi=None):
"""
NAME:
toVerticalPotential
PURPOSE:
convert a Potential to a vertical potential at a given R
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric radius at which to evaluate the vertical potential (can ... | [
"def",
"toVerticalPotential",
"(",
"Pot",
",",
"R",
",",
"phi",
"=",
"None",
")",
":",
"Pot",
"=",
"flatten",
"(",
"Pot",
")",
"if",
"_APY_LOADED",
":",
"if",
"isinstance",
"(",
"R",
",",
"units",
".",
"Quantity",
")",
":",
"if",
"hasattr",
"(",
"P... | NAME:
toVerticalPotential
PURPOSE:
convert a Potential to a vertical potential at a given R
INPUT:
Pot - Potential instance or list of such instances
R - Galactocentric radius at which to evaluate the vertical potential (can be Quantity)
phi= (None) Galactocentric azimu... | [
"NAME",
":"
] | python | train | 33.053571 |
tcalmant/ipopo | pelix/ipopo/core.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L560-L595 | def _register_factory(self, factory_name, factory, override):
# type: (str, type, bool) -> None
"""
Registers a component factory
:param factory_name: The name of the factory
:param factory: The factory class object
:param override: If true, previous factory is overridde... | [
"def",
"_register_factory",
"(",
"self",
",",
"factory_name",
",",
"factory",
",",
"override",
")",
":",
"# type: (str, type, bool) -> None",
"if",
"not",
"factory_name",
"or",
"not",
"is_string",
"(",
"factory_name",
")",
":",
"raise",
"ValueError",
"(",
"\"A fac... | Registers a component factory
:param factory_name: The name of the factory
:param factory: The factory class object
:param override: If true, previous factory is overridden, else an
exception is risen if a previous factory with that
name already... | [
"Registers",
"a",
"component",
"factory"
] | python | train | 38.555556 |
phaethon/kamene | kamene/packet.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/packet.py#L415-L424 | def pdfdump(self, filename=None, **kargs):
"""pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called."""
canvas = self.canvas_dump(**kargs)
if filename is None:
fname ... | [
"def",
"pdfdump",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"canvas",
"=",
"self",
".",
"canvas_dump",
"(",
"*",
"*",
"kargs",
")",
"if",
"filename",
"is",
"None",
":",
"fname",
"=",
"get_temp_file",
"(",
"autoext",... | pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called. | [
"pdfdump",
"(",
"filename",
"=",
"None",
"layer_shift",
"=",
"0",
"rebuild",
"=",
"1",
")",
"Creates",
"a",
"PDF",
"file",
"describing",
"a",
"packet",
".",
"If",
"filename",
"is",
"not",
"provided",
"a",
"temporary",
"file",
"is",
"created",
"and",
"xpd... | python | train | 50.3 |
coordt/django-alphabetfilter | alphafilter/templatetags/alphafilter.py | https://github.com/coordt/django-alphabetfilter/blob/a7bc21c0ea985c2021a4668241bf643c615c6c1f/alphafilter/templatetags/alphafilter.py#L177-L202 | def qs_alphabet_filter(parser, token):
"""
The parser/tokenizer for the queryset alphabet filter.
{% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %}
{% qs_alphabet_filter objects lastname myapp/template.html %}
The template name is optional and uses... | [
"def",
"qs_alphabet_filter",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"3",
":",
"return",
"AlphabetFilterNode",
"(",
"bits",
"[",
"1",
"]",
",",
"bits",
"[",
"2... | The parser/tokenizer for the queryset alphabet filter.
{% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %}
{% qs_alphabet_filter objects lastname myapp/template.html %}
The template name is optional and uses alphafilter/alphabet.html if not
specified | [
"The",
"parser",
"/",
"tokenizer",
"for",
"the",
"queryset",
"alphabet",
"filter",
"."
] | python | train | 39.192308 |
shoebot/shoebot | shoebot/sbio/shell.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/sbio/shell.py#L234-L239 | def do_rewind(self, line):
"""
rewind
"""
self.print_response("Rewinding from frame %s to 0" % self.bot._frame)
self.bot._frame = 0 | [
"def",
"do_rewind",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"print_response",
"(",
"\"Rewinding from frame %s to 0\"",
"%",
"self",
".",
"bot",
".",
"_frame",
")",
"self",
".",
"bot",
".",
"_frame",
"=",
"0"
] | rewind | [
"rewind"
] | python | valid | 27.666667 |
Azure/azure-sdk-for-python | azure-servicebus/azure/servicebus/servicebus_client.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/servicebus_client.py#L433-L469 | def list_sessions(self, updated_since=None, max_results=100, skip=0, **kwargs):
"""List session IDs.
List the Session IDs with pending messages in the queue where the state of the session
has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
I... | [
"def",
"list_sessions",
"(",
"self",
",",
"updated_since",
"=",
"None",
",",
"max_results",
"=",
"100",
",",
"skip",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"entity",
"and",
"not",
"self",
".",
"requires_session",
":",
"raise",
... | List session IDs.
List the Session IDs with pending messages in the queue where the state of the session
has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
If the state of a session has never been set, it will not be returned regardless of whether
... | [
"List",
"session",
"IDs",
"."
] | python | test | 49.135135 |
JohannesBuchner/jbopt | jbopt/mcmc.py | https://github.com/JohannesBuchner/jbopt/blob/11b721ea001625ad7820f71ff684723c71216646/jbopt/mcmc.py#L65-L112 | def mcmc(transform, loglikelihood, parameter_names, nsteps=40000, nburn=400,
stdevs=0.1, start = 0.5, **problem):
"""
**Metropolis Hastings MCMC**
with automatic step width adaption.
Burnin period is also used to guess steps.
:param nburn: number of burnin steps
:param stdevs: step widths to start with
"... | [
"def",
"mcmc",
"(",
"transform",
",",
"loglikelihood",
",",
"parameter_names",
",",
"nsteps",
"=",
"40000",
",",
"nburn",
"=",
"400",
",",
"stdevs",
"=",
"0.1",
",",
"start",
"=",
"0.5",
",",
"*",
"*",
"problem",
")",
":",
"if",
"'seed'",
"in",
"prob... | **Metropolis Hastings MCMC**
with automatic step width adaption.
Burnin period is also used to guess steps.
:param nburn: number of burnin steps
:param stdevs: step widths to start with | [
"**",
"Metropolis",
"Hastings",
"MCMC",
"**"
] | python | valid | 30.958333 |
CalebBell/fluids | fluids/two_phase.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L1539-L1634 | def Wang_Chiang_Lu(m, x, rhol, rhog, mul, mug, D, roughness=0, L=1):
r'''Calculates two-phase pressure drop with the Wang, Chiang, and Lu (1997)
correlation given in [1]_ and reviewed in [2]_ and [3]_.
.. math::
\Delta P = \Delta P_{g} \phi_g^2
.. math::
\phi_g^2 = 1 + 9.397X^{0.62} + ... | [
"def",
"Wang_Chiang_Lu",
"(",
"m",
",",
"x",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
",",
"D",
",",
"roughness",
"=",
"0",
",",
"L",
"=",
"1",
")",
":",
"G_tp",
"=",
"m",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"# Ac... | r'''Calculates two-phase pressure drop with the Wang, Chiang, and Lu (1997)
correlation given in [1]_ and reviewed in [2]_ and [3]_.
.. math::
\Delta P = \Delta P_{g} \phi_g^2
.. math::
\phi_g^2 = 1 + 9.397X^{0.62} + 0.564X^{2.45} \text{ for } G >= 200 kg/m^2/s
.. math::
\phi_... | [
"r",
"Calculates",
"two",
"-",
"phase",
"pressure",
"drop",
"with",
"the",
"Wang",
"Chiang",
"and",
"Lu",
"(",
"1997",
")",
"correlation",
"given",
"in",
"[",
"1",
"]",
"_",
"and",
"reviewed",
"in",
"[",
"2",
"]",
"_",
"and",
"[",
"3",
"]",
"_",
... | python | train | 32.510417 |
vbwagner/ctypescrypto | ctypescrypto/digest.py | https://github.com/vbwagner/ctypescrypto/blob/33c32904cf5e04901f87f90e2499634b8feecd3e/ctypescrypto/digest.py#L117-L135 | def update(self, data, length=None):
"""
Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes
"""
if self.digest_finalized:
raise DigestError("No upda... | [
"def",
"update",
"(",
"self",
",",
"data",
",",
"length",
"=",
"None",
")",
":",
"if",
"self",
".",
"digest_finalized",
":",
"raise",
"DigestError",
"(",
"\"No updates allowed\"",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bintype",
")",
":",
"ra... | Hashes given byte string
@param data - string to hash
@param length - if not specifed, entire string is hashed,
otherwise only first length bytes | [
"Hashes",
"given",
"byte",
"string"
] | python | train | 39.157895 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/scene/events.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/events.py#L50-L57 | def press_event(self):
""" The mouse press event that initiated a mouse drag, if any.
"""
if self.mouse_event.press_event is None:
return None
ev = self.copy()
ev.mouse_event = self.mouse_event.press_event
return ev | [
"def",
"press_event",
"(",
"self",
")",
":",
"if",
"self",
".",
"mouse_event",
".",
"press_event",
"is",
"None",
":",
"return",
"None",
"ev",
"=",
"self",
".",
"copy",
"(",
")",
"ev",
".",
"mouse_event",
"=",
"self",
".",
"mouse_event",
".",
"press_eve... | The mouse press event that initiated a mouse drag, if any. | [
"The",
"mouse",
"press",
"event",
"that",
"initiated",
"a",
"mouse",
"drag",
"if",
"any",
"."
] | python | train | 33.5 |
tensorflow/probability | tensorflow_probability/python/sts/regression.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/regression.py#L40-L47 | def _observe_timeseries_fn(timeseries):
"""Build an observation_noise_fn that observes a Tensor timeseries."""
def observation_noise_fn(t):
current_slice = timeseries[..., t, :]
return tfd.MultivariateNormalDiag(
loc=current_slice,
scale_diag=tf.zeros_like(current_slice))
return observatio... | [
"def",
"_observe_timeseries_fn",
"(",
"timeseries",
")",
":",
"def",
"observation_noise_fn",
"(",
"t",
")",
":",
"current_slice",
"=",
"timeseries",
"[",
"...",
",",
"t",
",",
":",
"]",
"return",
"tfd",
".",
"MultivariateNormalDiag",
"(",
"loc",
"=",
"curren... | Build an observation_noise_fn that observes a Tensor timeseries. | [
"Build",
"an",
"observation_noise_fn",
"that",
"observes",
"a",
"Tensor",
"timeseries",
"."
] | python | test | 40.375 |
SBRG/ssbio | ssbio/protein/structure/utils/foldx.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/utils/foldx.py#L216-L244 | def get_ddG_results(self):
"""Parse the results from BuildModel and get the delta delta G's.
A positive ddG means that the mutation(s) is destabilzing, negative means stabilizing.
- highly stabilising (ΔΔG < −1.84 kcal/mol);
- stabilising (−1.84 kcal/mol ≤ ΔΔG < −0.92 kcal/mol)... | [
"def",
"get_ddG_results",
"(",
"self",
")",
":",
"foldx_avg_df",
"=",
"self",
".",
"df_mutation_ddG_avg",
"foldx_avg_ddG",
"=",
"{",
"}",
"results",
"=",
"foldx_avg_df",
"[",
"[",
"'Pdb'",
",",
"'total energy'",
",",
"'SD'",
"]",
"]",
".",
"T",
".",
"to_di... | Parse the results from BuildModel and get the delta delta G's.
A positive ddG means that the mutation(s) is destabilzing, negative means stabilizing.
- highly stabilising (ΔΔG < −1.84 kcal/mol);
- stabilising (−1.84 kcal/mol ≤ ΔΔG < −0.92 kcal/mol);
- slightly stabilising (... | [
"Parse",
"the",
"results",
"from",
"BuildModel",
"and",
"get",
"the",
"delta",
"delta",
"G",
"s",
"."
] | python | train | 39.413793 |
robehickman/simple-http-file-sync | shttpfs/versioned_storage.py | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/versioned_storage.py#L46-L64 | def build_dir_tree(self, files):
""" Convert a flat file dict into the tree format used for storage """
def helper(split_files):
this_dir = {'files' : {}, 'dirs' : {}}
dirs = defaultdict(list)
for fle in split_files:
index = fle[0]; fileinfo = fle[1]... | [
"def",
"build_dir_tree",
"(",
"self",
",",
"files",
")",
":",
"def",
"helper",
"(",
"split_files",
")",
":",
"this_dir",
"=",
"{",
"'files'",
":",
"{",
"}",
",",
"'dirs'",
":",
"{",
"}",
"}",
"dirs",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"fl... | Convert a flat file dict into the tree format used for storage | [
"Convert",
"a",
"flat",
"file",
"dict",
"into",
"the",
"tree",
"format",
"used",
"for",
"storage"
] | python | train | 44.105263 |
JohnVinyard/featureflow | featureflow/extractor.py | https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/extractor.py#L189-L218 | def version(self):
"""
Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified
"""
try:
f = self... | [
"def",
"version",
"(",
"self",
")",
":",
"try",
":",
"f",
"=",
"self",
".",
"func",
".",
"__call__",
".",
"__code__",
"except",
"AttributeError",
":",
"f",
"=",
"self",
".",
"func",
".",
"__code__",
"h",
"=",
"md5",
"(",
")",
"h",
".",
"update",
... | Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified | [
"Compute",
"the",
"version",
"identifier",
"for",
"this",
"functional",
"node",
"using",
"the",
"func",
"code",
"and",
"local",
"names",
".",
"Optionally",
"also",
"allow",
"closed",
"-",
"over",
"variable",
"values",
"to",
"affect",
"the",
"version",
"number"... | python | train | 29.733333 |
brainiak/brainiak | brainiak/funcalign/srm.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/funcalign/srm.py#L789-L846 | def _srm(self, data):
"""Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-... | [
"def",
"_srm",
"(",
"self",
",",
"data",
")",
":",
"subjects",
"=",
"len",
"(",
"data",
")",
"self",
".",
"random_state_",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"self",
".",
"rand_seed",
")",
"random_states",
"=",
"[",
"np",
".",
"random... | Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-------
w : list of array... | [
"Expectation",
"-",
"Maximization",
"algorithm",
"for",
"fitting",
"the",
"probabilistic",
"SRM",
"."
] | python | train | 39 |
saltstack/salt | salt/modules/opkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L336-L356 | def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgradi... | [
"def",
"_parse_reported_packages_from_install_output",
"(",
"output",
")",
":",
"reported_pkgs",
"=",
"{",
"}",
"install_pattern",
"=",
"re",
".",
"compile",
"(",
"r'Installing\\s(?P<package>.*?)\\s\\((?P<version>.*?)\\)\\son\\s(?P<target>.*?)'",
")",
"upgrade_pattern",
"=",
... | Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root | [
"Parses",
"the",
"output",
"of",
"opkg",
"install",
"to",
"determine",
"what",
"packages",
"would",
"have",
"been",
"installed",
"by",
"an",
"operation",
"run",
"with",
"the",
"--",
"noaction",
"flag",
"."
] | python | train | 43.857143 |
AtomHash/evernode | evernode/classes/form_data.py | https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/classes/form_data.py#L63-L78 | def parse(self, fail_callback=None):
""" Parse text fields and file fields for values and files """
# get text fields
for field in self.field_arguments:
self.values[field['name']] = self.__get_value(field['name'])
if self.values[field['name']] is None and field['requ... | [
"def",
"parse",
"(",
"self",
",",
"fail_callback",
"=",
"None",
")",
":",
"# get text fields\r",
"for",
"field",
"in",
"self",
".",
"field_arguments",
":",
"self",
".",
"values",
"[",
"field",
"[",
"'name'",
"]",
"]",
"=",
"self",
".",
"__get_value",
"("... | Parse text fields and file fields for values and files | [
"Parse",
"text",
"fields",
"and",
"file",
"fields",
"for",
"values",
"and",
"files"
] | python | train | 49.5625 |
readbeyond/aeneas | aeneas/syncmap/smfsmil.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfsmil.py#L55-L89 | def parse(self, input_text, syncmap):
"""
Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be popul... | [
"def",
"parse",
"(",
"self",
",",
"input_text",
",",
"syncmap",
")",
":",
"from",
"lxml",
"import",
"etree",
"smil_ns",
"=",
"\"{http://www.w3.org/ns/SMIL}\"",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"gf",
".",
"safe_bytes",
"(",
"input_text",
")",
")"... | Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated | [
"Read",
"from",
"SMIL",
"file",
"."
] | python | train | 41.657143 |
Tinche/cattrs | src/cattr/multistrategy_dispatch.py | https://github.com/Tinche/cattrs/blob/481bc9bdb69b2190d699b54f331c8c5c075506d5/src/cattr/multistrategy_dispatch.py#L46-L52 | def register_func_list(self, func_and_handler):
""" register a function to determine if the handle
should be used for the type
"""
for func, handler in func_and_handler:
self._function_dispatch.register(func, handler)
self.dispatch.cache_clear() | [
"def",
"register_func_list",
"(",
"self",
",",
"func_and_handler",
")",
":",
"for",
"func",
",",
"handler",
"in",
"func_and_handler",
":",
"self",
".",
"_function_dispatch",
".",
"register",
"(",
"func",
",",
"handler",
")",
"self",
".",
"dispatch",
".",
"ca... | register a function to determine if the handle
should be used for the type | [
"register",
"a",
"function",
"to",
"determine",
"if",
"the",
"handle",
"should",
"be",
"used",
"for",
"the",
"type"
] | python | train | 42.142857 |
takluyver/backcall | backcall/backcall.py | https://github.com/takluyver/backcall/blob/cff13f5e4bd2a2af82fc5174e38cca0f9b7c21d2/backcall/backcall.py#L27-L109 | def callback_prototype(prototype):
"""Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype.adapt`` attribute
whic... | [
"def",
"callback_prototype",
"(",
"prototype",
")",
":",
"protosig",
"=",
"signature",
"(",
"prototype",
")",
"positional",
",",
"keyword",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"name",
",",
"param",
"in",
"protosig",
".",
"parameters",
".",
"items",
"(",... | Decorator to process a callback prototype.
A callback prototype is a function whose signature includes all the values
that will be passed by the callback API in question.
The original function will be returned, with a ``prototype.adapt`` attribute
which can be used to prepare third party callb... | [
"Decorator",
"to",
"process",
"a",
"callback",
"prototype",
".",
"A",
"callback",
"prototype",
"is",
"a",
"function",
"whose",
"signature",
"includes",
"all",
"the",
"values",
"that",
"will",
"be",
"passed",
"by",
"the",
"callback",
"API",
"in",
"question",
... | python | train | 38.120482 |
rakanalh/pocket-api | pocket/__init__.py | https://github.com/rakanalh/pocket-api/blob/d8222dd34e3aa5e545f9b8ba407fa277c734ab82/pocket/__init__.py#L329-L360 | def _make_exception(self, response):
"""
In case of exception, construct the exception
object that holds all important values returned by
the response.
:return: The exception instance
:rtype: PocketException
"""
headers = response.headers
limit_he... | [
"def",
"_make_exception",
"(",
"self",
",",
"response",
")",
":",
"headers",
"=",
"response",
".",
"headers",
"limit_headers",
"=",
"[",
"]",
"if",
"'X-Limit-User-Limit'",
"in",
"headers",
":",
"limit_headers",
"=",
"[",
"headers",
"[",
"'X-Limit-User-Limit'",
... | In case of exception, construct the exception
object that holds all important values returned by
the response.
:return: The exception instance
:rtype: PocketException | [
"In",
"case",
"of",
"exception",
"construct",
"the",
"exception",
"object",
"that",
"holds",
"all",
"important",
"values",
"returned",
"by",
"the",
"response",
".",
":",
"return",
":",
"The",
"exception",
"instance",
":",
"rtype",
":",
"PocketException"
] | python | train | 31.03125 |
MolSSI-BSE/basis_set_exchange | basis_set_exchange/api.py | https://github.com/MolSSI-BSE/basis_set_exchange/blob/e79110aaeb65f392ed5032420322dee3336948f7/basis_set_exchange/api.py#L481-L490 | def _basis_notes_path(name, data_dir):
'''Form a path to the notes for a basis set'''
data_dir = fix_data_dir(data_dir)
bs_data = _get_basis_metadata(name, data_dir)
# the notes file is the same as the base file name, with a .notes extension
filebase = bs_data['basename']
file_path = os.path.j... | [
"def",
"_basis_notes_path",
"(",
"name",
",",
"data_dir",
")",
":",
"data_dir",
"=",
"fix_data_dir",
"(",
"data_dir",
")",
"bs_data",
"=",
"_get_basis_metadata",
"(",
"name",
",",
"data_dir",
")",
"# the notes file is the same as the base file name, with a .notes extensio... | Form a path to the notes for a basis set | [
"Form",
"a",
"path",
"to",
"the",
"notes",
"for",
"a",
"basis",
"set"
] | python | train | 36.6 |
inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/trimmedstring.py | https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/schemas/fields/trimmedstring.py#L19-L22 | def _deserialize(self, value, attr, data):
"""Deserialize string value."""
value = super(TrimmedString, self)._deserialize(value, attr, data)
return value.strip() | [
"def",
"_deserialize",
"(",
"self",
",",
"value",
",",
"attr",
",",
"data",
")",
":",
"value",
"=",
"super",
"(",
"TrimmedString",
",",
"self",
")",
".",
"_deserialize",
"(",
"value",
",",
"attr",
",",
"data",
")",
"return",
"value",
".",
"strip",
"(... | Deserialize string value. | [
"Deserialize",
"string",
"value",
"."
] | python | train | 45.75 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py#L177-L189 | def police_priority_map_exceed_map_pri3_exceed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map, ... | [
"def",
"police_priority_map_exceed_map_pri3_exceed",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"police_priority_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"police-priority-map\"",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 49.153846 |
wdm0006/git-pandas | gitpandas/utilities/plotting.py | https://github.com/wdm0006/git-pandas/blob/e56b817b1d66b8296d1d5e703d5db0e181d25899/gitpandas/utilities/plotting.py#L22-L73 | def plot_punchcard(df, metric='lines', title='punchcard', by=None):
"""
Uses modified plotting code from https://bitbucket.org/birkenfeld/hgpunchcard
:param df:
:param metric:
:param title:
:return:
"""
if not HAS_MPL:
raise ImportError('Must have matplotlib installed to use th... | [
"def",
"plot_punchcard",
"(",
"df",
",",
"metric",
"=",
"'lines'",
",",
"title",
"=",
"'punchcard'",
",",
"by",
"=",
"None",
")",
":",
"if",
"not",
"HAS_MPL",
":",
"raise",
"ImportError",
"(",
"'Must have matplotlib installed to use the plotting functions'",
")",
... | Uses modified plotting code from https://bitbucket.org/birkenfeld/hgpunchcard
:param df:
:param metric:
:param title:
:return: | [
"Uses",
"modified",
"plotting",
"code",
"from",
"https",
":",
"//",
"bitbucket",
".",
"org",
"/",
"birkenfeld",
"/",
"hgpunchcard"
] | python | train | 37.403846 |
deschler/django-modeltranslation | modeltranslation/fields.py | https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/fields.py#L406-L412 | def cache_name(self):
"""
Used in django 1.x
"""
lang = get_language()
cache = build_localized_fieldname(self.accessor, lang)
return "_%s_cache" % cache | [
"def",
"cache_name",
"(",
"self",
")",
":",
"lang",
"=",
"get_language",
"(",
")",
"cache",
"=",
"build_localized_fieldname",
"(",
"self",
".",
"accessor",
",",
"lang",
")",
"return",
"\"_%s_cache\"",
"%",
"cache"
] | Used in django 1.x | [
"Used",
"in",
"django",
"1",
".",
"x"
] | python | train | 27.714286 |
DLR-RM/RAFCON | source/rafcon/core/states/execution_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/execution_state.py#L104-L130 | def _execute(self, execute_inputs, execute_outputs, backward_execution=False):
"""Calls the custom execute function of the script.py of the state
"""
self._script.build_module()
outcome_item = self._script.execute(self, execute_inputs, execute_outputs, backward_execution)
# in... | [
"def",
"_execute",
"(",
"self",
",",
"execute_inputs",
",",
"execute_outputs",
",",
"backward_execution",
"=",
"False",
")",
":",
"self",
".",
"_script",
".",
"build_module",
"(",
")",
"outcome_item",
"=",
"self",
".",
"_script",
".",
"execute",
"(",
"self",... | Calls the custom execute function of the script.py of the state | [
"Calls",
"the",
"custom",
"execute",
"function",
"of",
"the",
"script",
".",
"py",
"of",
"the",
"state"
] | python | train | 37.259259 |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L704-L769 | def length_of_national_destination_code(numobj):
"""Return length of the national destination code code for a number.
Gets the length of the national destination code (NDC) from the
PhoneNumber object passed in, so that clients could use it to split a
national significant number into NDC and subscriber... | [
"def",
"length_of_national_destination_code",
"(",
"numobj",
")",
":",
"if",
"numobj",
".",
"extension",
"is",
"not",
"None",
":",
"# We don't want to alter the object given to us, but we don't want to",
"# include the extension when we format it, so we copy it and clear the",
"# ext... | Return length of the national destination code code for a number.
Gets the length of the national destination code (NDC) from the
PhoneNumber object passed in, so that clients could use it to split a
national significant number into NDC and subscriber number. The NDC of a
phone number is normally the f... | [
"Return",
"length",
"of",
"the",
"national",
"destination",
"code",
"code",
"for",
"a",
"number",
"."
] | python | train | 43.833333 |
bkg/greenwich | greenwich/raster.py | https://github.com/bkg/greenwich/blob/57ec644dadfe43ce0ecf2cfd32a2de71e0c8c141/greenwich/raster.py#L474-L488 | def get_offset(self, envelope):
"""Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope
"""
if isinstance(envelope, collections.Sequence):
envelope = Envelope(envelope)
if not (self.en... | [
"def",
"get_offset",
"(",
"self",
",",
"envelope",
")",
":",
"if",
"isinstance",
"(",
"envelope",
",",
"collections",
".",
"Sequence",
")",
":",
"envelope",
"=",
"Envelope",
"(",
"envelope",
")",
"if",
"not",
"(",
"self",
".",
"envelope",
".",
"contains"... | Returns a 4-tuple pixel window (x_offset, y_offset, x_size, y_size).
Arguments:
envelope -- coordinate extent tuple or Envelope | [
"Returns",
"a",
"4",
"-",
"tuple",
"pixel",
"window",
"(",
"x_offset",
"y_offset",
"x_size",
"y_size",
")",
"."
] | python | test | 45.466667 |
push-things/wallabag_api | wallabag_api/wallabag.py | https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L208-L220 | async def get_entry(self, entry):
"""
GET /api/entries/{entry}.{_format}
Retrieve a single entry
:param entry: \w+ an integer The Entry ID
:return data related to the ext
"""
params = {'access_token': self.token}
url = '/api/entries/{entry}.{ext}'.format... | [
"async",
"def",
"get_entry",
"(",
"self",
",",
"entry",
")",
":",
"params",
"=",
"{",
"'access_token'",
":",
"self",
".",
"token",
"}",
"url",
"=",
"'/api/entries/{entry}.{ext}'",
".",
"format",
"(",
"entry",
"=",
"entry",
",",
"ext",
"=",
"self",
".",
... | GET /api/entries/{entry}.{_format}
Retrieve a single entry
:param entry: \w+ an integer The Entry ID
:return data related to the ext | [
"GET",
"/",
"api",
"/",
"entries",
"/",
"{",
"entry",
"}",
".",
"{",
"_format",
"}"
] | python | train | 34 |
boolangery/py-lua-parser | luaparser/builder.py | https://github.com/boolangery/py-lua-parser/blob/578f2bf75f6f84c4b52c2affba56a4ec569d7ce7/luaparser/builder.py#L793-L815 | def parse_func_body(self):
"""If success, return a tuple (args, body)"""
self.save()
self._expected = []
if self.next_is_rc(Tokens.OPAR, False): # do not render right hidden
self.handle_hidden_right() # render hidden after new level
args = self.parse_param_list(... | [
"def",
"parse_func_body",
"(",
"self",
")",
":",
"self",
".",
"save",
"(",
")",
"self",
".",
"_expected",
"=",
"[",
"]",
"if",
"self",
".",
"next_is_rc",
"(",
"Tokens",
".",
"OPAR",
",",
"False",
")",
":",
"# do not render right hidden",
"self",
".",
"... | If success, return a tuple (args, body) | [
"If",
"success",
"return",
"a",
"tuple",
"(",
"args",
"body",
")"
] | python | train | 45.391304 |
yero13/na3x | na3x/validation/validator.py | https://github.com/yero13/na3x/blob/b31ef801ea574081125020a7d0f9c4242f8f8b02/na3x/validation/validator.py#L261-L273 | def no_intersection(to_validate, constraint, violation_cfg):
"""
Returns violation message if validated and constraint sets have no intersection
:param to_validate:
:param constraint:
:param violation_cfg:
:return:
"""
if len(constraint) == 0 or len(set(constraint).intersection(to_valida... | [
"def",
"no_intersection",
"(",
"to_validate",
",",
"constraint",
",",
"violation_cfg",
")",
":",
"if",
"len",
"(",
"constraint",
")",
"==",
"0",
"or",
"len",
"(",
"set",
"(",
"constraint",
")",
".",
"intersection",
"(",
"to_validate",
")",
")",
">",
"0",... | Returns violation message if validated and constraint sets have no intersection
:param to_validate:
:param constraint:
:param violation_cfg:
:return: | [
"Returns",
"violation",
"message",
"if",
"validated",
"and",
"constraint",
"sets",
"have",
"no",
"intersection",
":",
"param",
"to_validate",
":",
":",
"param",
"constraint",
":",
":",
"param",
"violation_cfg",
":",
":",
"return",
":"
] | python | train | 37.769231 |
FutunnOpen/futuquant | futuquant/trade/trade_query.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/trade/trade_query.py#L259-L284 | def pack_req(cls, trd_side, order_type, price, qty,
code, adjust_limit, trd_env, sec_mkt_str, acc_id, trd_mkt, conn_id):
"""Convert from user request for place order to PLS request"""
from futuquant.common.pb.Trd_PlaceOrder_pb2 import Request
req = Request()
serial_no = ... | [
"def",
"pack_req",
"(",
"cls",
",",
"trd_side",
",",
"order_type",
",",
"price",
",",
"qty",
",",
"code",
",",
"adjust_limit",
",",
"trd_env",
",",
"sec_mkt_str",
",",
"acc_id",
",",
"trd_mkt",
",",
"conn_id",
")",
":",
"from",
"futuquant",
".",
"common"... | Convert from user request for place order to PLS request | [
"Convert",
"from",
"user",
"request",
"for",
"place",
"order",
"to",
"PLS",
"request"
] | python | train | 47.038462 |
mbedmicro/pyOCD | pyocd/__main__.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/__main__.py#L463-L485 | def do_erase(self):
"""! @brief Handle 'erase' subcommand."""
self._increase_logging(["pyocd.tools.loader", "pyocd"])
session = ConnectHelper.session_with_chosen_probe(
project_dir=self._args.project_dir,
config_file=self._args.con... | [
"def",
"do_erase",
"(",
"self",
")",
":",
"self",
".",
"_increase_logging",
"(",
"[",
"\"pyocd.tools.loader\"",
",",
"\"pyocd\"",
"]",
")",
"session",
"=",
"ConnectHelper",
".",
"session_with_chosen_probe",
"(",
"project_dir",
"=",
"self",
".",
"_args",
".",
"... | ! @brief Handle 'erase' subcommand. | [
"!"
] | python | train | 47.565217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.