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 |
|---|---|---|---|---|---|---|---|---|---|
astropy/photutils | photutils/datasets/make.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L691-L749 | def make_100gaussians_image(noise=True):
"""
Make an example image containing 100 2D Gaussians plus a constant
background.
The background has a mean of 5.
If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a
standard deviation of 2 is added to the output image.
Parameters
... | [
"def",
"make_100gaussians_image",
"(",
"noise",
"=",
"True",
")",
":",
"n_sources",
"=",
"100",
"flux_range",
"=",
"[",
"500",
",",
"1000",
"]",
"xmean_range",
"=",
"[",
"0",
",",
"500",
"]",
"ymean_range",
"=",
"[",
"0",
",",
"300",
"]",
"xstddev_rang... | Make an example image containing 100 2D Gaussians plus a constant
background.
The background has a mean of 5.
If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a
standard deviation of 2 is added to the output image.
Parameters
----------
noise : bool, optional
Wheth... | [
"Make",
"an",
"example",
"image",
"containing",
"100",
"2D",
"Gaussians",
"plus",
"a",
"constant",
"background",
"."
] | python | train | 27.372881 |
erikrose/nose-progressive | noseprogressive/tracebacks.py | https://github.com/erikrose/nose-progressive/blob/42853f11290cfaac8aa3d204714b71e27cc4ec07/noseprogressive/tracebacks.py#L131-L134 | def _unicode_decode_extracted_tb(extracted_tb):
"""Return a traceback with the string elements translated into Unicode."""
return [(_decode(file), line_number, _decode(function), _decode(text))
for file, line_number, function, text in extracted_tb] | [
"def",
"_unicode_decode_extracted_tb",
"(",
"extracted_tb",
")",
":",
"return",
"[",
"(",
"_decode",
"(",
"file",
")",
",",
"line_number",
",",
"_decode",
"(",
"function",
")",
",",
"_decode",
"(",
"text",
")",
")",
"for",
"file",
",",
"line_number",
",",
... | Return a traceback with the string elements translated into Unicode. | [
"Return",
"a",
"traceback",
"with",
"the",
"string",
"elements",
"translated",
"into",
"Unicode",
"."
] | python | train | 66.25 |
tensorflow/tensorboard | tensorboard/compat/tensorflow_stub/io/gfile.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L89-L110 | def read(self, filename, binary_mode=False, size=None, offset=None):
"""Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
... | [
"def",
"read",
"(",
"self",
",",
"filename",
",",
"binary_mode",
"=",
"False",
",",
"size",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"mode",
"=",
"\"rb\"",
"if",
"binary_mode",
"else",
"\"r\"",
"with",
"io",
".",
"open",
"(",
"filename",
",... | Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: in... | [
"Reads",
"contents",
"of",
"a",
"file",
"to",
"a",
"string",
"."
] | python | train | 38.090909 |
apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L363-L378 | def print_action(self, test_succeed, action):
'''
Print the detailed info of failed or always print tests.
'''
#self.info_print(">>> {0}",action.keys())
if not test_succeed or action['info']['always_show_run_output']:
output = action['output'].strip()
if o... | [
"def",
"print_action",
"(",
"self",
",",
"test_succeed",
",",
"action",
")",
":",
"#self.info_print(\">>> {0}\",action.keys())",
"if",
"not",
"test_succeed",
"or",
"action",
"[",
"'info'",
"]",
"[",
"'always_show_run_output'",
"]",
":",
"output",
"=",
"action",
"[... | Print the detailed info of failed or always print tests. | [
"Print",
"the",
"detailed",
"info",
"of",
"failed",
"or",
"always",
"print",
"tests",
"."
] | python | train | 45.125 |
olitheolix/qtmacs | qtmacs/qtmacsmain.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain.py#L2472-L2596 | def qteRemoveAppletFromLayout(self, applet: (QtmacsApplet, str)):
"""
Remove ``applet`` from the window layout.
This method removes ``applet`` and implicitly deletes
obsolete (ie. half-full) splitters in the process. If
``applet`` is the only visible applet in the layout then it... | [
"def",
"qteRemoveAppletFromLayout",
"(",
"self",
",",
"applet",
":",
"(",
"QtmacsApplet",
",",
"str",
")",
")",
":",
"# If ``applet`` was specified by its ID (ie. a string) then",
"# fetch the associated ``QtmacsApplet`` instance. If",
"# ``applet`` is already an instance of ``Qtmacs... | Remove ``applet`` from the window layout.
This method removes ``applet`` and implicitly deletes
obsolete (ie. half-full) splitters in the process. If
``applet`` is the only visible applet in the layout then it
will be replaced with the first invisible applet. If no
invisible app... | [
"Remove",
"applet",
"from",
"the",
"window",
"layout",
"."
] | python | train | 41.352 |
gwastro/pycbc | pycbc/transforms.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/transforms.py#L498-L506 | def inverse_jacobian(self, maps):
"""Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta.
"""
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)
eta = conversions.eta_from_mass1_mass2(m1... | [
"def",
"inverse_jacobian",
"(",
"self",
",",
"maps",
")",
":",
"m1",
"=",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
"m2",
"=",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
"mchirp",
"=",
"conversions",
".",
"mchirp_from_mass1_mass2",
"(",
"m1",
",",... | Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta. | [
"Returns",
"the",
"Jacobian",
"for",
"transforming",
"mass1",
"and",
"mass2",
"to",
"mchirp",
"and",
"eta",
"."
] | python | train | 39.888889 |
chaimleib/intervaltree | intervaltree/interval.py | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/interval.py#L112-L131 | def distance_to(self, other):
"""
Returns the size of the gap between intervals, or 0
if they touch or overlap.
:param other: Interval or point
:return: distance
:rtype: Number
"""
if self.overlaps(other):
return 0
try:
if ... | [
"def",
"distance_to",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"overlaps",
"(",
"other",
")",
":",
"return",
"0",
"try",
":",
"if",
"self",
".",
"begin",
"<",
"other",
".",
"begin",
":",
"return",
"other",
".",
"begin",
"-",
"self",
... | Returns the size of the gap between intervals, or 0
if they touch or overlap.
:param other: Interval or point
:return: distance
:rtype: Number | [
"Returns",
"the",
"size",
"of",
"the",
"gap",
"between",
"intervals",
"or",
"0",
"if",
"they",
"touch",
"or",
"overlap",
".",
":",
"param",
"other",
":",
"Interval",
"or",
"point",
":",
"return",
":",
"distance",
":",
"rtype",
":",
"Number"
] | python | train | 29.3 |
minhhoit/yacms | yacms/twitter/admin.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/twitter/admin.py#L31-L50 | def formfield_for_dbfield(self, db_field, **kwargs):
"""
Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and the... | [
"def",
"formfield_for_dbfield",
"(",
"self",
",",
"db_field",
",",
"*",
"*",
"kwargs",
")",
":",
"formfield",
"=",
"super",
"(",
"TweetableAdminMixin",
",",
"self",
")",
".",
"formfield_for_dbfield",
"(",
"db_field",
",",
"*",
"*",
"kwargs",
")",
"if",
"Ap... | Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and then adding it to the
formssets attribute of the admin class fell ap... | [
"Adds",
"the",
"Send",
"to",
"Twitter",
"checkbox",
"after",
"the",
"status",
"field",
"provided",
"by",
"any",
"Displayable",
"models",
".",
"The",
"approach",
"here",
"is",
"quite",
"a",
"hack",
"however",
"the",
"sane",
"approach",
"of",
"using",
"a",
"... | python | train | 48.8 |
StackStorm/pybind | pybind/nos/v7_2_0/interface/port_channel/switchport/port_security/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/interface/port_channel/switchport/port_security/__init__.py#L140-L163 | def _set_port_sec_violation(self, v, load=False):
"""
Setter method for port_sec_violation, mapped from YANG variable /interface/port_channel/switchport/port_security/port_sec_violation (port-sec-violation)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_sec_violati... | [
"def",
"_set_port_sec_violation",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
","... | Setter method for port_sec_violation, mapped from YANG variable /interface/port_channel/switchport/port_security/port_sec_violation (port-sec-violation)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_sec_violation is considered as a private
method. Backends looking to ... | [
"Setter",
"method",
"for",
"port_sec_violation",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"port_channel",
"/",
"switchport",
"/",
"port_security",
"/",
"port_sec_violation",
"(",
"port",
"-",
"sec",
"-",
"violation",
")",
"If",
"this",
"varia... | python | train | 94.333333 |
rikrd/inspire | inspirespeech/__init__.py | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/__init__.py#L552-L584 | def evaluate(self, password=''):
"""Evaluates the development set.
The passwords is sent as plain text.
:return: the evaluation results.
"""
# Make a copy only keeping the development set
dev_submission = self
if self['metadata'].get('evaluation_setting', {}).g... | [
"def",
"evaluate",
"(",
"self",
",",
"password",
"=",
"''",
")",
":",
"# Make a copy only keeping the development set",
"dev_submission",
"=",
"self",
"if",
"self",
"[",
"'metadata'",
"]",
".",
"get",
"(",
"'evaluation_setting'",
",",
"{",
"}",
")",
".",
"get"... | Evaluates the development set.
The passwords is sent as plain text.
:return: the evaluation results. | [
"Evaluates",
"the",
"development",
"set",
"."
] | python | train | 38.787879 |
lcharleux/argiope | argiope/mesh.py | https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/mesh.py#L714-L776 | def read_msh(path):
"""
Reads a GMSH MSH file and returns a :class:`Mesh` instance.
:arg path: path to MSH file.
:type path: str
"""
elementMap = { 15:"point1",
1:"line2",
2:"tri3",
3:"quad4",
4:"tetra4",
5:"hexa8",
... | [
"def",
"read_msh",
"(",
"path",
")",
":",
"elementMap",
"=",
"{",
"15",
":",
"\"point1\"",
",",
"1",
":",
"\"line2\"",
",",
"2",
":",
"\"tri3\"",
",",
"3",
":",
"\"quad4\"",
",",
"4",
":",
"\"tetra4\"",
",",
"5",
":",
"\"hexa8\"",
",",
"6",
":",
... | Reads a GMSH MSH file and returns a :class:`Mesh` instance.
:arg path: path to MSH file.
:type path: str | [
"Reads",
"a",
"GMSH",
"MSH",
"file",
"and",
"returns",
"a",
":",
"class",
":",
"Mesh",
"instance",
".",
":",
"arg",
"path",
":",
"path",
"to",
"MSH",
"file",
".",
":",
"type",
"path",
":",
"str"
] | python | test | 31.52381 |
pyamg/pyamg | pyamg/util/linalg.py | https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/util/linalg.py#L453-L493 | def cond(A):
"""Return condition number of A.
Parameters
----------
A : {dense or sparse matrix}
e.g. array, matrix, csr_matrix, ...
Returns
-------
2-norm condition number through use of the SVD
Use for small to moderate sized dense matrices.
For large sparse matrices, u... | [
"def",
"cond",
"(",
"A",
")",
":",
"if",
"A",
".",
"shape",
"[",
"0",
"]",
"!=",
"A",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'expected square matrix'",
")",
"if",
"sparse",
".",
"isspmatrix",
"(",
"A",
")",
":",
"A",
"=",
... | Return condition number of A.
Parameters
----------
A : {dense or sparse matrix}
e.g. array, matrix, csr_matrix, ...
Returns
-------
2-norm condition number through use of the SVD
Use for small to moderate sized dense matrices.
For large sparse matrices, use condest.
Not... | [
"Return",
"condition",
"number",
"of",
"A",
"."
] | python | train | 24.926829 |
reingart/pyafipws | wslpg.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L1521-L1582 | def AnalizarAjuste(self, aut, base=True):
"Método interno para analizar la respuesta de AFIP (ajustes)"
self.__ajuste_base = None
self.__ajuste_debito = None
self.__ajuste_credito = None
# para compatibilidad con la generacion de PDF (completo datos)
if hasattr(... | [
"def",
"AnalizarAjuste",
"(",
"self",
",",
"aut",
",",
"base",
"=",
"True",
")",
":",
"self",
".",
"__ajuste_base",
"=",
"None",
"self",
".",
"__ajuste_debito",
"=",
"None",
"self",
".",
"__ajuste_credito",
"=",
"None",
"# para compatibilidad con la generacion d... | Método interno para analizar la respuesta de AFIP (ajustes) | [
"Método",
"interno",
"para",
"analizar",
"la",
"respuesta",
"de",
"AFIP",
"(",
"ajustes",
")"
] | python | train | 54.370968 |
wakatime/wakatime | wakatime/packages/pygments/lexer.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexer.py#L429-L433 | def _process_token(cls, token):
"""Preprocess the token component of a token definition."""
assert type(token) is _TokenType or callable(token), \
'token type must be simple type or callable, not %r' % (token,)
return token | [
"def",
"_process_token",
"(",
"cls",
",",
"token",
")",
":",
"assert",
"type",
"(",
"token",
")",
"is",
"_TokenType",
"or",
"callable",
"(",
"token",
")",
",",
"'token type must be simple type or callable, not %r'",
"%",
"(",
"token",
",",
")",
"return",
"toke... | Preprocess the token component of a token definition. | [
"Preprocess",
"the",
"token",
"component",
"of",
"a",
"token",
"definition",
"."
] | python | train | 51 |
ayust/kitnirc | kitnirc/client.py | https://github.com/ayust/kitnirc/blob/cf19fe39219da75f053e1a3976bf21331b6fefea/kitnirc/client.py#L307-L326 | def run(self):
"""Process events such as incoming data.
This method blocks indefinitely. It will only return after the
connection to the server is closed.
"""
self._stop = False # Allow re-starting the event loop
while not self._stop:
try:
sel... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_stop",
"=",
"False",
"# Allow re-starting the event loop",
"while",
"not",
"self",
".",
"_stop",
":",
"try",
":",
"self",
".",
"_buffer",
"+=",
"self",
".",
"socket",
".",
"recv",
"(",
"4096",
")",
"e... | Process events such as incoming data.
This method blocks indefinitely. It will only return after the
connection to the server is closed. | [
"Process",
"events",
"such",
"as",
"incoming",
"data",
"."
] | python | train | 37.55 |
vaexio/vaex | packages/vaex-core/vaex/__init__.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/__init__.py#L407-L413 | def from_csv(filename_or_buffer, copy_index=True, **kwargs):
"""Shortcut to read a csv file using pandas and convert to a DataFrame directly.
:rtype: DataFrame
"""
import pandas as pd
return from_pandas(pd.read_csv(filename_or_buffer, **kwargs), copy_index=copy_index) | [
"def",
"from_csv",
"(",
"filename_or_buffer",
",",
"copy_index",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pandas",
"as",
"pd",
"return",
"from_pandas",
"(",
"pd",
".",
"read_csv",
"(",
"filename_or_buffer",
",",
"*",
"*",
"kwargs",
")",
... | Shortcut to read a csv file using pandas and convert to a DataFrame directly.
:rtype: DataFrame | [
"Shortcut",
"to",
"read",
"a",
"csv",
"file",
"using",
"pandas",
"and",
"convert",
"to",
"a",
"DataFrame",
"directly",
"."
] | python | test | 40.428571 |
JNRowe/upoints | upoints/kml.py | https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/kml.py#L69-L93 | def tokml(self):
"""Generate a KML Placemark element subtree.
Returns:
etree.Element: KML Placemark element
"""
placemark = create_elem('Placemark')
if self.name:
placemark.set('id', self.name)
placemark.name = create_elem('name', text=self.na... | [
"def",
"tokml",
"(",
"self",
")",
":",
"placemark",
"=",
"create_elem",
"(",
"'Placemark'",
")",
"if",
"self",
".",
"name",
":",
"placemark",
".",
"set",
"(",
"'id'",
",",
"self",
".",
"name",
")",
"placemark",
".",
"name",
"=",
"create_elem",
"(",
"... | Generate a KML Placemark element subtree.
Returns:
etree.Element: KML Placemark element | [
"Generate",
"a",
"KML",
"Placemark",
"element",
"subtree",
"."
] | python | train | 36.92 |
kdeldycke/chessboard | chessboard/pieces.py | https://github.com/kdeldycke/chessboard/blob/ac7a14dc7b6905701e3f6d4e01e8fe1869241bed/chessboard/pieces.py#L169-L178 | def territory(self):
""" Return the cached territory occupied by the piece. """
cache_key = (
self.board.length, self.board.height, self.uid, self.index)
if cache_key not in self.territory_cache:
vector = self.compute_territory()
self.territory_cache[cache_key... | [
"def",
"territory",
"(",
"self",
")",
":",
"cache_key",
"=",
"(",
"self",
".",
"board",
".",
"length",
",",
"self",
".",
"board",
".",
"height",
",",
"self",
".",
"uid",
",",
"self",
".",
"index",
")",
"if",
"cache_key",
"not",
"in",
"self",
".",
... | Return the cached territory occupied by the piece. | [
"Return",
"the",
"cached",
"territory",
"occupied",
"by",
"the",
"piece",
"."
] | python | train | 41 |
torchbox/wagtail-import-export | wagtailimportexport/views.py | https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L21-L60 | def import_from_api(request):
"""
Import a part of a source site's page tree via a direct API request from
this Wagtail Admin to the source site
The source site's base url and the source page id of the point in the
tree to import defined what to import and the destination parent page
defines wh... | [
"def",
"import_from_api",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"ImportFromAPIForm",
"(",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"# remove trailing slash from base url",
... | Import a part of a source site's page tree via a direct API request from
this Wagtail Admin to the source site
The source site's base url and the source page id of the point in the
tree to import defined what to import and the destination parent page
defines where to import it to. | [
"Import",
"a",
"part",
"of",
"a",
"source",
"site",
"s",
"page",
"tree",
"via",
"a",
"direct",
"API",
"request",
"from",
"this",
"Wagtail",
"Admin",
"to",
"the",
"source",
"site"
] | python | train | 38.6 |
kwlzn/blast | blast/main.py | https://github.com/kwlzn/blast/blob/ae18a19182a6884c453bf9b2a3c6386bd3b2655a/blast/main.py#L53-L63 | def iterplayables():
''' fast iterator of playable file object/dicts found on disk '''
ls = DirScanner(stripdot=True)
## filter out just mp3 files (and dirs to support recursion)
filt = lambda x: ( os.path.isdir(x) or x[-4:].lower() in ALLOWED_TYPES )
## take the last two segments of the path as the... | [
"def",
"iterplayables",
"(",
")",
":",
"ls",
"=",
"DirScanner",
"(",
"stripdot",
"=",
"True",
")",
"## filter out just mp3 files (and dirs to support recursion)",
"filt",
"=",
"lambda",
"x",
":",
"(",
"os",
".",
"path",
".",
"isdir",
"(",
"x",
")",
"or",
"x"... | fast iterator of playable file object/dicts found on disk | [
"fast",
"iterator",
"of",
"playable",
"file",
"object",
"/",
"dicts",
"found",
"on",
"disk"
] | python | train | 57.090909 |
bitesofcode/projexui | projexui/widgets/xscintillaedit/xscintillaedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xscintillaedit/xscintillaedit.py#L311-L361 | def initOptions(self, options):
"""
Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions>
"""
self.setAutoIndent( options.value('autoIndent'))
self.setIndentationsUseTabs( options.value('indentationsU... | [
"def",
"initOptions",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"setAutoIndent",
"(",
"options",
".",
"value",
"(",
"'autoIndent'",
")",
")",
"self",
".",
"setIndentationsUseTabs",
"(",
"options",
".",
"value",
"(",
"'indentationsUseTabs'",
")",
")... | Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions> | [
"Initializes",
"the",
"edit",
"with",
"the",
"inputed",
"options",
"data",
"set",
".",
":",
"param",
"options",
"|",
"<XScintillaEditOptions",
">"
] | python | train | 40.058824 |
gwpy/gwpy | gwpy/signal/qtransform.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/qtransform.py#L585-L624 | def table(self, snrthresh=5.5):
"""Represent this `QPlane` as an `EventTable`
Parameters
----------
snrthresh : `float`, optional
lower inclusive threshold on individual tile SNR to keep in the
table, default: 5.5
Returns
-------
out : `~... | [
"def",
"table",
"(",
"self",
",",
"snrthresh",
"=",
"5.5",
")",
":",
"from",
".",
".",
"table",
"import",
"EventTable",
"# get plane properties",
"freqs",
"=",
"self",
".",
"plane",
".",
"frequencies",
"bws",
"=",
"2",
"*",
"(",
"freqs",
"-",
"self",
"... | Represent this `QPlane` as an `EventTable`
Parameters
----------
snrthresh : `float`, optional
lower inclusive threshold on individual tile SNR to keep in the
table, default: 5.5
Returns
-------
out : `~gwpy.table.EventTable`
a table ... | [
"Represent",
"this",
"QPlane",
"as",
"an",
"EventTable"
] | python | train | 37.75 |
eirannejad/Revit-Journal-Maker | rjm/__init__.py | https://github.com/eirannejad/Revit-Journal-Maker/blob/09a4f27da6d183f63a2c93ed99dca8a8590d5241/rjm/__init__.py#L134-L145 | def new_model(self, template_name='<None>'):
"""Append a new model from .rft entry to the journal.
This instructs Revit to create a new model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
... | [
"def",
"new_model",
"(",
"self",
",",
"template_name",
"=",
"'<None>'",
")",
":",
"self",
".",
"_add_entry",
"(",
"templates",
".",
"NEW_MODEL",
".",
"format",
"(",
"template_name",
"=",
"template_name",
")",
")"
] | Append a new model from .rft entry to the journal.
This instructs Revit to create a new model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
to be used. default value is <None> | [
"Append",
"a",
"new",
"model",
"from",
".",
"rft",
"entry",
"to",
"the",
"journal",
"."
] | python | train | 39.333333 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/classtracker.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/classtracker.py#L341-L346 | def _restore_constructor(self, cls):
"""
Restore the original constructor, lose track of class.
"""
cls.__init__ = self._observers[cls].init
del self._observers[cls] | [
"def",
"_restore_constructor",
"(",
"self",
",",
"cls",
")",
":",
"cls",
".",
"__init__",
"=",
"self",
".",
"_observers",
"[",
"cls",
"]",
".",
"init",
"del",
"self",
".",
"_observers",
"[",
"cls",
"]"
] | Restore the original constructor, lose track of class. | [
"Restore",
"the",
"original",
"constructor",
"lose",
"track",
"of",
"class",
"."
] | python | train | 33.333333 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L383-L386 | def set_exception(self, exception):
''' set the exception message and set the status to failed '''
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._set_status(enumAsperaControllerStatus.FAILED, exception) | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"logger",
".",
"error",
"(",
"\"%s : %s\"",
"%",
"(",
"exception",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"exception",
")",
")",
")",
"self",
".",
"_set_status",
"(",
"enumAspe... | set the exception message and set the status to failed | [
"set",
"the",
"exception",
"message",
"and",
"set",
"the",
"status",
"to",
"failed"
] | python | train | 63.75 |
pydata/xarray | xarray/core/utils.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/utils.py#L295-L319 | def ordered_dict_intersection(first_dict: Mapping[K, V],
second_dict: Mapping[K, V],
compat: Callable[[V, V], bool] = equivalent
) -> MutableMapping[K, V]:
"""Return the intersection of two dictionaries as a new OrderedDict.
... | [
"def",
"ordered_dict_intersection",
"(",
"first_dict",
":",
"Mapping",
"[",
"K",
",",
"V",
"]",
",",
"second_dict",
":",
"Mapping",
"[",
"K",
",",
"V",
"]",
",",
"compat",
":",
"Callable",
"[",
"[",
"V",
",",
"V",
"]",
",",
"bool",
"]",
"=",
"equiv... | Return the intersection of two dictionaries as a new OrderedDict.
Items are retained if their keys are found in both dictionaries and the
values are compatible.
Parameters
----------
first_dict, second_dict : dict-like
Mappings to merge.
compat : function, optional
Binary opera... | [
"Return",
"the",
"intersection",
"of",
"two",
"dictionaries",
"as",
"a",
"new",
"OrderedDict",
"."
] | python | train | 34.44 |
google/transitfeed | transitfeed/trip.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/trip.py#L327-L343 | def GetFrequencyStartTimes(self):
"""Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list."""
start_times = []
# for each headway period of the trip
... | [
"def",
"GetFrequencyStartTimes",
"(",
"self",
")",
":",
"start_times",
"=",
"[",
"]",
"# for each headway period of the trip",
"for",
"freq_tuple",
"in",
"self",
".",
"GetFrequencyTuples",
"(",
")",
":",
"(",
"start_secs",
",",
"end_secs",
",",
"headway_secs",
")"... | Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list. | [
"Return",
"a",
"list",
"of",
"start",
"time",
"for",
"each",
"headway",
"-",
"based",
"run",
"."
] | python | train | 39.352941 |
apache/incubator-mxnet | plugin/opencv/opencv.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/plugin/opencv/opencv.py#L131-L153 | def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
"""Randomly crop src with size. Randomize area and aspect ratio"""
h, w, _ = src.shape
area = w*h
for _ in range(10):
new_area = random.uniform(min_area, 1.0) * area
new_ratio = random.uniform(*ratio)
new_w... | [
"def",
"random_size_crop",
"(",
"src",
",",
"size",
",",
"min_area",
"=",
"0.25",
",",
"ratio",
"=",
"(",
"3.0",
"/",
"4.0",
",",
"4.0",
"/",
"3.0",
")",
")",
":",
"h",
",",
"w",
",",
"_",
"=",
"src",
".",
"shape",
"area",
"=",
"w",
"*",
"h",... | Randomly crop src with size. Randomize area and aspect ratio | [
"Randomly",
"crop",
"src",
"with",
"size",
".",
"Randomize",
"area",
"and",
"aspect",
"ratio"
] | python | train | 31.521739 |
fastai/fastai | fastai/callbacks/tensorboard.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L282-L285 | def write(self, model:nn.Module, iteration:int, tbwriter:SummaryWriter, name:str='model')->None:
"Writes model histograms to Tensorboard."
request = HistogramTBRequest(model=model, iteration=iteration, tbwriter=tbwriter, name=name)
asyncTBWriter.request_write(request) | [
"def",
"write",
"(",
"self",
",",
"model",
":",
"nn",
".",
"Module",
",",
"iteration",
":",
"int",
",",
"tbwriter",
":",
"SummaryWriter",
",",
"name",
":",
"str",
"=",
"'model'",
")",
"->",
"None",
":",
"request",
"=",
"HistogramTBRequest",
"(",
"model... | Writes model histograms to Tensorboard. | [
"Writes",
"model",
"histograms",
"to",
"Tensorboard",
"."
] | python | train | 72.25 |
aliyun/aliyun-odps-python-sdk | odps/console.py | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/console.py#L480-L495 | def _decode_preferred_encoding(s):
"""Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8.
"""
enc = locale.getpr... | [
"def",
"_decode_preferred_encoding",
"(",
"s",
")",
":",
"enc",
"=",
"locale",
".",
"getpreferredencoding",
"(",
")",
"try",
":",
"try",
":",
"return",
"s",
".",
"decode",
"(",
"enc",
")",
"except",
"LookupError",
":",
"enc",
"=",
"_DEFAULT_ENCODING",
"ret... | Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8. | [
"Decode",
"the",
"supplied",
"byte",
"string",
"using",
"the",
"preferred",
"encoding",
"for",
"the",
"locale",
"(",
"locale",
".",
"getpreferredencoding",
")",
"or",
"if",
"the",
"default",
"encoding",
"is",
"invalid",
"fall",
"back",
"first",
"on",
"utf",
... | python | train | 33.5 |
bivab/smbus-cffi | smbus/smbus.py | https://github.com/bivab/smbus-cffi/blob/7486931edf55fcdde84db38356331c65851a40b1/smbus/smbus.py#L172-L189 | def process_call(self, addr, cmd, val):
"""process_call(addr, cmd, val)
Perform SMBus Process Call transaction.
Note: although i2c_smbus_process_call returns a value, according to
smbusmodule.c this method does not return a value by default.
Set _compat = False on the SMBus in... | [
"def",
"process_call",
"(",
"self",
",",
"addr",
",",
"cmd",
",",
"val",
")",
":",
"self",
".",
"_set_addr",
"(",
"addr",
")",
"ret",
"=",
"SMBUS",
".",
"i2c_smbus_process_call",
"(",
"self",
".",
"_fd",
",",
"ffi",
".",
"cast",
"(",
"\"__u8\"",
",",... | process_call(addr, cmd, val)
Perform SMBus Process Call transaction.
Note: although i2c_smbus_process_call returns a value, according to
smbusmodule.c this method does not return a value by default.
Set _compat = False on the SMBus instance to get a return value. | [
"process_call",
"(",
"addr",
"cmd",
"val",
")"
] | python | test | 37 |
Jaymon/endpoints | endpoints/http.py | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L535-L560 | def controller(self, *paths, **query_kwargs):
"""create a new url object using the controller path as a base
if you have a controller `foo.BarController` then this would create a new
Url instance with `host/foo/bar` as the base path, so any *paths will be
appended to `/foo/bar`
... | [
"def",
"controller",
"(",
"self",
",",
"*",
"paths",
",",
"*",
"*",
"query_kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_normalize_params",
"(",
"*",
"paths",
",",
"*",
"*",
"query_kwargs",
")",
"if",
"self",
".",
"controller_path",
":",
"if",
"\"pa... | create a new url object using the controller path as a base
if you have a controller `foo.BarController` then this would create a new
Url instance with `host/foo/bar` as the base path, so any *paths will be
appended to `/foo/bar`
:example:
# controller foo.BarController
... | [
"create",
"a",
"new",
"url",
"object",
"using",
"the",
"controller",
"path",
"as",
"a",
"base"
] | python | train | 42.230769 |
Karaage-Cluster/python-tldap | tldap/backend/fake_transactions.py | https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/backend/fake_transactions.py#L197-L213 | def add(self, dn: str, mod_list: dict) -> None:
"""
Add a DN to the LDAP database; See ldap module. Doesn't return a result
if transactions enabled.
"""
_debug("add", self, dn, mod_list)
# if rollback of add required, delete it
def on_commit(obj):
ob... | [
"def",
"add",
"(",
"self",
",",
"dn",
":",
"str",
",",
"mod_list",
":",
"dict",
")",
"->",
"None",
":",
"_debug",
"(",
"\"add\"",
",",
"self",
",",
"dn",
",",
"mod_list",
")",
"# if rollback of add required, delete it",
"def",
"on_commit",
"(",
"obj",
")... | Add a DN to the LDAP database; See ldap module. Doesn't return a result
if transactions enabled. | [
"Add",
"a",
"DN",
"to",
"the",
"LDAP",
"database",
";",
"See",
"ldap",
"module",
".",
"Doesn",
"t",
"return",
"a",
"result",
"if",
"transactions",
"enabled",
"."
] | python | train | 27.705882 |
hubo1016/vlcp | vlcp/event/core.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/event/core.py#L529-L536 | def syscall_generator(generator):
'''
Directly process events from a generator function. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in generator():
processor(e)
return _syscall | [
"def",
"syscall_generator",
"(",
"generator",
")",
":",
"def",
"_syscall",
"(",
"scheduler",
",",
"processor",
")",
":",
"for",
"e",
"in",
"generator",
"(",
")",
":",
"processor",
"(",
"e",
")",
"return",
"_syscall"
] | Directly process events from a generator function. This should never be used for normal events. | [
"Directly",
"process",
"events",
"from",
"a",
"generator",
"function",
".",
"This",
"should",
"never",
"be",
"used",
"for",
"normal",
"events",
"."
] | python | train | 32.125 |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L511-L515 | def getx(self, name, *args):
"""
Return value of one of parameter(s) or NULL is it has no value (or was not specified)
"""
return lib.zargs_getx(self._as_parameter_, name, *args) | [
"def",
"getx",
"(",
"self",
",",
"name",
",",
"*",
"args",
")",
":",
"return",
"lib",
".",
"zargs_getx",
"(",
"self",
".",
"_as_parameter_",
",",
"name",
",",
"*",
"args",
")"
] | Return value of one of parameter(s) or NULL is it has no value (or was not specified) | [
"Return",
"value",
"of",
"one",
"of",
"parameter",
"(",
"s",
")",
"or",
"NULL",
"is",
"it",
"has",
"no",
"value",
"(",
"or",
"was",
"not",
"specified",
")"
] | python | train | 41.2 |
daler/gffutils | gffutils/interface.py | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L873-L928 | def add_relation(self, parent, child, level, parent_func=None,
child_func=None):
"""
Manually add relations to the database.
Parameters
----------
parent : str or Feature instance
Parent feature to add.
child : str or Feature instance
... | [
"def",
"add_relation",
"(",
"self",
",",
"parent",
",",
"child",
",",
"level",
",",
"parent_func",
"=",
"None",
",",
"child_func",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"parent",
",",
"six",
".",
"string_types",
")",
":",
"parent",
"=",
"self... | Manually add relations to the database.
Parameters
----------
parent : str or Feature instance
Parent feature to add.
child : str or Feature instance
Child feature to add
level : int
Level of the relation. For example, if parent is a gene ... | [
"Manually",
"add",
"relations",
"to",
"the",
"database",
"."
] | python | train | 34.446429 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_run.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_run.py#L1564-L1577 | def stage_tc_batch_xid(xid_type, xid_value, owner):
"""Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description]
"""
xid_string = '{... | [
"def",
"stage_tc_batch_xid",
"(",
"xid_type",
",",
"xid_value",
",",
"owner",
")",
":",
"xid_string",
"=",
"'{}-{}-{}'",
".",
"format",
"(",
"xid_type",
",",
"xid_value",
",",
"owner",
")",
"hash_object",
"=",
"hashlib",
".",
"sha256",
"(",
"xid_string",
"."... | Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description] | [
"Create",
"an",
"xid",
"for",
"a",
"batch",
"job",
"."
] | python | train | 32.428571 |
facelessuser/backrefs | tools/unipropgen.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/tools/unipropgen.py#L948-L1212 | def gen_properties(output, ascii_props=False, append=False):
"""Generate the property table and dump it to the provided file."""
files = {
'gc': os.path.join(output, 'generalcategory.py'),
'blk': os.path.join(output, 'block.py'),
'sc': os.path.join(output, 'script.py'),
'bc': os... | [
"def",
"gen_properties",
"(",
"output",
",",
"ascii_props",
"=",
"False",
",",
"append",
"=",
"False",
")",
":",
"files",
"=",
"{",
"'gc'",
":",
"os",
".",
"path",
".",
"join",
"(",
"output",
",",
"'generalcategory.py'",
")",
",",
"'blk'",
":",
"os",
... | Generate the property table and dump it to the provided file. | [
"Generate",
"the",
"property",
"table",
"and",
"dump",
"it",
"to",
"the",
"provided",
"file",
"."
] | python | train | 37.071698 |
PyGithub/PyGithub | github/Repository.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/Repository.py#L1436-L1470 | def get_commits(self, sha=github.GithubObject.NotSet, path=github.GithubObject.NotSet, since=github.GithubObject.NotSet, until=github.GithubObject.NotSet, author=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/commits <http://developer.github.com/v3/repos/commits>`_
:param sha:... | [
"def",
"get_commits",
"(",
"self",
",",
"sha",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"path",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"since",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"until",
"=",
"github"... | :calls: `GET /repos/:owner/:repo/commits <http://developer.github.com/v3/repos/commits>`_
:param sha: string
:param path: string
:param since: datetime.datetime
:param until: datetime.datetime
:param author: string or :class:`github.NamedUser.NamedUser` or :class:`github.Authenti... | [
":",
"calls",
":",
"GET",
"/",
"repos",
"/",
":",
"owner",
"/",
":",
"repo",
"/",
"commits",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"repos",
"/",
"commits",
">",
"_",
":",
"param",
"sha",
":",
"string",
":",
... | python | train | 60.514286 |
lucasmaystre/choix | choix/utils.py | https://github.com/lucasmaystre/choix/blob/05a57a10bb707338113a9d91601ca528ead7a881/choix/utils.py#L260-L283 | def generate_params(n_items, interval=5.0, ordered=False):
r"""Generate random model parameters.
This function samples a parameter independently and uniformly for each
item. ``interval`` defines the width of the uniform distribution.
Parameters
----------
n_items : int
Number of distin... | [
"def",
"generate_params",
"(",
"n_items",
",",
"interval",
"=",
"5.0",
",",
"ordered",
"=",
"False",
")",
":",
"params",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"low",
"=",
"0",
",",
"high",
"=",
"interval",
",",
"size",
"=",
"n_items",
")",
... | r"""Generate random model parameters.
This function samples a parameter independently and uniformly for each
item. ``interval`` defines the width of the uniform distribution.
Parameters
----------
n_items : int
Number of distinct items.
interval : float
Sampling interval.
o... | [
"r",
"Generate",
"random",
"model",
"parameters",
"."
] | python | train | 28.125 |
gmr/rejected | rejected/connection.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/connection.py#L326-L362 | def on_return(self, channel, method, properties, body):
"""Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame... | [
"def",
"on_return",
"(",
"self",
",",
"channel",
",",
"method",
",",
"properties",
",",
"body",
")",
":",
"pending",
"=",
"self",
".",
"pending_confirmations",
"(",
")",
"if",
"not",
"pending",
":",
"# Exit early if there are no pending messages",
"self",
".",
... | Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
... | [
"Invoked",
"by",
"RabbitMQ",
"when",
"it",
"returns",
"a",
"message",
"that",
"was",
"published",
"."
] | python | train | 47.945946 |
gapato/livestreamer-curses | src/livestreamer_curses/streamlist.py | https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L594-L606 | def redraw_current_line(self):
""" Redraw the highlighted line """
if self.no_streams:
return
row = self.pads[self.current_pad].getyx()[0]
s = self.filtered_streams[row]
pad = self.pads['streams']
pad.move(row, 0)
pad.clrtoeol()
pad.addstr(row,... | [
"def",
"redraw_current_line",
"(",
"self",
")",
":",
"if",
"self",
".",
"no_streams",
":",
"return",
"row",
"=",
"self",
".",
"pads",
"[",
"self",
".",
"current_pad",
"]",
".",
"getyx",
"(",
")",
"[",
"0",
"]",
"s",
"=",
"self",
".",
"filtered_stream... | Redraw the highlighted line | [
"Redraw",
"the",
"highlighted",
"line"
] | python | train | 34.846154 |
iotile/coretools | iotilegateway/iotilegateway/supervisor/service_manager.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/service_manager.py#L157-L170 | def service_messages(self, short_name):
"""Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service
"""
if sh... | [
"def",
"service_messages",
"(",
"self",
",",
"short_name",
")",
":",
"if",
"short_name",
"not",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Unknown service name\"",
",",
"short_name",
"=",
"short_name",
")",
"return",
"list",
"(",
"se... | Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service | [
"Get",
"the",
"messages",
"stored",
"for",
"a",
"service",
"."
] | python | train | 34.428571 |
saltstack/salt | salt/modules/cimc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cimc.py#L860-L908 | def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The... | [
"def",
"set_user",
"(",
"uid",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"priv",
"=",
"None",
",",
"status",
"=",
"None",
")",
":",
"conf",
"=",
"\"\"",
"if",
"not",
"uid",
":",
"raise",
"salt",
".",
"exceptions"... | Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
... | [
"Sets",
"a",
"CIMC",
"user",
"with",
"specified",
"configurations",
"."
] | python | train | 24.918367 |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Environment.py#L525-L533 | def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None):
"""Calls through to SCons.Subst.scons_subst_list(). See
the documentation for that function."""
gvars = self.gvars()
lvars = self.lvars()
lvars['__env__'] = self
if executor:
... | [
"def",
"subst_list",
"(",
"self",
",",
"string",
",",
"raw",
"=",
"0",
",",
"target",
"=",
"None",
",",
"source",
"=",
"None",
",",
"conv",
"=",
"None",
",",
"executor",
"=",
"None",
")",
":",
"gvars",
"=",
"self",
".",
"gvars",
"(",
")",
"lvars"... | Calls through to SCons.Subst.scons_subst_list(). See
the documentation for that function. | [
"Calls",
"through",
"to",
"SCons",
".",
"Subst",
".",
"scons_subst_list",
"()",
".",
"See",
"the",
"documentation",
"for",
"that",
"function",
"."
] | python | train | 50 |
portfors-lab/sparkle | sparkle/stim/auto_parameter_model.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/stim/auto_parameter_model.py#L131-L150 | def nStepsForParam(self, param):
"""Gets the number of steps *parameter* will yeild
:param param: parameter to get the expansion count for
:type param: dict
"""
if param['parameter'] == 'filename':
return len(param['names'])
else:
if param['step']... | [
"def",
"nStepsForParam",
"(",
"self",
",",
"param",
")",
":",
"if",
"param",
"[",
"'parameter'",
"]",
"==",
"'filename'",
":",
"return",
"len",
"(",
"param",
"[",
"'names'",
"]",
")",
"else",
":",
"if",
"param",
"[",
"'step'",
"]",
">",
"0",
":",
"... | Gets the number of steps *parameter* will yeild
:param param: parameter to get the expansion count for
:type param: dict | [
"Gets",
"the",
"number",
"of",
"steps",
"*",
"parameter",
"*",
"will",
"yeild"
] | python | train | 38.25 |
cnobile2012/pololu-motors | pololu/motors/qik.py | https://github.com/cnobile2012/pololu-motors/blob/453d2283a63cfe15cda96cad6dffa73372d52a7c/pololu/motors/qik.py#L322-L345 | def _getPWMFrequency(self, device, message):
"""
Get the PWM frequency stored on the hardware device.
:Parameters:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
message : `bool`
... | [
"def",
"_getPWMFrequency",
"(",
"self",
",",
"device",
",",
"message",
")",
":",
"result",
"=",
"self",
".",
"_getConfig",
"(",
"self",
".",
"PWM_PARAM",
",",
"device",
")",
"freq",
",",
"msg",
"=",
"self",
".",
"_CONFIG_PWM",
".",
"get",
"(",
"result"... | Get the PWM frequency stored on the hardware device.
:Parameters:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
message : `bool`
If set to `True` a text message will be returned, if s... | [
"Get",
"the",
"PWM",
"frequency",
"stored",
"on",
"the",
"hardware",
"device",
"."
] | python | train | 32.625 |
neptune-ml/steppy-toolkit | toolkit/keras_transformers/architectures.py | https://github.com/neptune-ml/steppy-toolkit/blob/bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132/toolkit/keras_transformers/architectures.py#L178-L219 | def vdcnn(embedding_size, maxlen, max_features,
filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation,
max_pooling, mean_pooling, weighted_average_attention, concat_mode,
dropout_embedding, conv_dropout, dense_dropout, dropout_mode,
conv_k... | [
"def",
"vdcnn",
"(",
"embedding_size",
",",
"maxlen",
",",
"max_features",
",",
"filter_nr",
",",
"kernel_size",
",",
"repeat_block",
",",
"dense_size",
",",
"repeat_dense",
",",
"output_size",
",",
"output_activation",
",",
"max_pooling",
",",
"mean_pooling",
","... | Note:
Implementation of http://www.aclweb.org/anthology/E17-1104
We didn't use k-max pooling but GlobalMaxPool1D at the end and didn't explore it in the
intermediate layers. | [
"Note",
":",
"Implementation",
"of",
"http",
":",
"//",
"www",
".",
"aclweb",
".",
"org",
"/",
"anthology",
"/",
"E17",
"-",
"1104",
"We",
"didn",
"t",
"use",
"k",
"-",
"max",
"pooling",
"but",
"GlobalMaxPool1D",
"at",
"the",
"end",
"and",
"didn",
"t... | python | train | 57.261905 |
ray-project/ray | python/ray/profiling.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/profiling.py#L30-L61 | def profile(event_type, extra_data=None):
"""Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with ray.profile("custom... | [
"def",
"profile",
"(",
"event_type",
",",
"extra_data",
"=",
"None",
")",
":",
"worker",
"=",
"ray",
".",
"worker",
".",
"global_worker",
"return",
"RayLogSpanRaylet",
"(",
"worker",
".",
"profiler",
",",
"event_type",
",",
"extra_data",
"=",
"extra_data",
"... | Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with ray.profile("custom event", extra_data={'key': 'value'}):
... | [
"Profile",
"a",
"span",
"of",
"time",
"so",
"that",
"it",
"appears",
"in",
"the",
"timeline",
"visualization",
"."
] | python | train | 44.40625 |
ArchiveTeam/wpull | wpull/protocol/http/stream.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/protocol/http/stream.py#L309-L365 | def _read_body_by_chunk(self, response, file, raw=False):
'''Read the connection using chunked transfer encoding.
Coroutine.
'''
reader = ChunkedTransferReader(self._connection)
file_is_async = hasattr(file, 'drain')
while True:
chunk_size, data = yield fro... | [
"def",
"_read_body_by_chunk",
"(",
"self",
",",
"response",
",",
"file",
",",
"raw",
"=",
"False",
")",
":",
"reader",
"=",
"ChunkedTransferReader",
"(",
"self",
".",
"_connection",
")",
"file_is_async",
"=",
"hasattr",
"(",
"file",
",",
"'drain'",
")",
"w... | Read the connection using chunked transfer encoding.
Coroutine. | [
"Read",
"the",
"connection",
"using",
"chunked",
"transfer",
"encoding",
"."
] | python | train | 24.912281 |
svetlyak40wt/twiggy-goodies | twiggy_goodies/django_rq.py | https://github.com/svetlyak40wt/twiggy-goodies/blob/71528d5959fab81eb8d0e4373f20d37a013ac00e/twiggy_goodies/django_rq.py#L10-L32 | def job(func_or_queue, connection=None, *args, **kwargs):
"""This decorator does all what django_rq's one, plus
it group all logged messages using uuid and sets
job_name field as well."""
decorated_func = _job(func_or_queue, connection=connection, *args, **kwargs)
if callable(func_or_queue):
... | [
"def",
"job",
"(",
"func_or_queue",
",",
"connection",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"decorated_func",
"=",
"_job",
"(",
"func_or_queue",
",",
"connection",
"=",
"connection",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | This decorator does all what django_rq's one, plus
it group all logged messages using uuid and sets
job_name field as well. | [
"This",
"decorator",
"does",
"all",
"what",
"django_rq",
"s",
"one",
"plus",
"it",
"group",
"all",
"logged",
"messages",
"using",
"uuid",
"and",
"sets",
"job_name",
"field",
"as",
"well",
"."
] | python | train | 38.73913 |
mitsei/dlkit | dlkit/json_/assessment/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/sessions.py#L6346-L6364 | def get_banks_by_assessment_offered(self, assessment_offered_id):
"""Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list of banks
raise: N... | [
"def",
"get_banks_by_assessment_offered",
"(",
"self",
",",
"assessment_offered_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_bins_by_resource",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'ASSESSMENT'",
",",
"local",
"=",... | Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list of banks
raise: NotFound - ``assessment_offered_id`` is not found
raise: NullArgument... | [
"Gets",
"the",
"list",
"of",
"Banks",
"mapped",
"to",
"an",
"AssessmentOffered",
"."
] | python | train | 52.315789 |
tensorflow/probability | tensorflow_probability/python/mcmc/eight_schools_hmc.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/eight_schools_hmc.py#L37-L41 | def mvn(*args, **kwargs):
"""Convenience function to efficiently construct a MultivariateNormalDiag."""
# Faster than using `tfd.MultivariateNormalDiag`.
return tfd.Independent(tfd.Normal(*args, **kwargs),
reinterpreted_batch_ndims=1) | [
"def",
"mvn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Faster than using `tfd.MultivariateNormalDiag`.",
"return",
"tfd",
".",
"Independent",
"(",
"tfd",
".",
"Normal",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
",",
"reinterpreted_batch_... | Convenience function to efficiently construct a MultivariateNormalDiag. | [
"Convenience",
"function",
"to",
"efficiently",
"construct",
"a",
"MultivariateNormalDiag",
"."
] | python | test | 52.2 |
tensorflow/datasets | tensorflow_datasets/image/mnist.py | https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/image/mnist.py#L113-L144 | def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# Download the full MNIST Database
filenames = {
"train_data": _MNIST_TRAIN_DATA_FILENAME,
"train_labels": _MNIST_TRAIN_LABELS_FILENAME,
"test_data": _MNIST_TEST_DATA_FILENAME,
"test_labels": _MNIST_TEST_... | [
"def",
"_split_generators",
"(",
"self",
",",
"dl_manager",
")",
":",
"# Download the full MNIST Database",
"filenames",
"=",
"{",
"\"train_data\"",
":",
"_MNIST_TRAIN_DATA_FILENAME",
",",
"\"train_labels\"",
":",
"_MNIST_TRAIN_LABELS_FILENAME",
",",
"\"test_data\"",
":",
... | Returns SplitGenerators. | [
"Returns",
"SplitGenerators",
"."
] | python | train | 36.65625 |
wonambi-python/wonambi | wonambi/widgets/notes.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L1334-L1350 | def rename_rater(self, test_name=None, test_new_name=None):
"""action: create dialog to rename event type."""
if test_name and test_new_name:
name = test_name, True
new_name = test_new_name, True
else:
name = QInputDialog.getText(self, 'Rename Rater',
... | [
"def",
"rename_rater",
"(",
"self",
",",
"test_name",
"=",
"None",
",",
"test_new_name",
"=",
"None",
")",
":",
"if",
"test_name",
"and",
"test_new_name",
":",
"name",
"=",
"test_name",
",",
"True",
"new_name",
"=",
"test_new_name",
",",
"True",
"else",
":... | action: create dialog to rename event type. | [
"action",
":",
"create",
"dialog",
"to",
"rename",
"event",
"type",
"."
] | python | train | 42.470588 |
ssato/python-anyconfig | src/anyconfig/api.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/api.py#L223-L246 | def open(path, mode=None, ac_parser=None, **options):
"""
Open given configuration file with appropriate open flag.
:param path: Configuration file path
:param mode:
Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing.
Please note that even if you specify 'r' or 'w', it w... | [
"def",
"open",
"(",
"path",
",",
"mode",
"=",
"None",
",",
"ac_parser",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"psr",
"=",
"find",
"(",
"path",
",",
"forced_type",
"=",
"ac_parser",
")",
"if",
"mode",
"is",
"not",
"None",
"and",
"mode",
... | Open given configuration file with appropriate open flag.
:param path: Configuration file path
:param mode:
Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing.
Please note that even if you specify 'r' or 'w', it will be changed to
'rb' or 'wb' if selected backend, xml an... | [
"Open",
"given",
"configuration",
"file",
"with",
"appropriate",
"open",
"flag",
"."
] | python | train | 39.25 |
CloudGenix/sdk-python | cloudgenix/interactive.py | https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L72-L254 | def login(self, email=None, password=None):
"""
Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
... | [
"def",
"login",
"(",
"self",
",",
"email",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"# if email not given in function, or if first login fails, prompt.",
"if",
"email",
"is",
"None",
":",
"# If user is not set, pull from cache. If not in cache, prompt.",
"if",
... | Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
- **email**: Email to log in for, will prompt if not entere... | [
"Interactive",
"login",
"using",
"the",
"cloudgenix",
".",
"API",
"object",
".",
"This",
"function",
"is",
"more",
"robust",
"and",
"handles",
"SAML",
"and",
"MSP",
"accounts",
".",
"Expects",
"interactive",
"capability",
".",
"if",
"this",
"is",
"not",
"ava... | python | train | 51.612022 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAIndicator/indicators.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/indicators.py#L586-L593 | def QA_indicator_shadow(DataFrame):
"""
上下影线指标
"""
return {
'LOW': lower_shadow(DataFrame), 'UP': upper_shadow(DataFrame),
'BODY': body(DataFrame), 'BODY_ABS': body_abs(DataFrame), 'PRICE_PCG': price_pcg(DataFrame)
} | [
"def",
"QA_indicator_shadow",
"(",
"DataFrame",
")",
":",
"return",
"{",
"'LOW'",
":",
"lower_shadow",
"(",
"DataFrame",
")",
",",
"'UP'",
":",
"upper_shadow",
"(",
"DataFrame",
")",
",",
"'BODY'",
":",
"body",
"(",
"DataFrame",
")",
",",
"'BODY_ABS'",
":"... | 上下影线指标 | [
"上下影线指标"
] | python | train | 30.625 |
shmir/PyIxExplorer | ixexplorer/ixe_statistics_view.py | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_statistics_view.py#L242-L279 | def read_stats(self, *stats):
""" Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
from ixexplorer.ixe_stream import IxePacketGroupStream
sleep_time = 0.1 # in cases we only want few counters but very f... | [
"def",
"read_stats",
"(",
"self",
",",
"*",
"stats",
")",
":",
"from",
"ixexplorer",
".",
"ixe_stream",
"import",
"IxePacketGroupStream",
"sleep_time",
"=",
"0.1",
"# in cases we only want few counters but very fast we need a smaller sleep time",
"if",
"not",
"stats",
":"... | Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics. | [
"Read",
"stream",
"statistics",
"from",
"chassis",
"."
] | python | train | 55 |
googleapis/google-auth-library-python | google/auth/credentials.py | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/credentials.py#L266-L289 | def with_scopes_if_required(credentials, scopes):
"""Creates a copy of the credentials with scopes if scoping is required.
This helper function is useful when you do not know (or care to know) the
specific type of credentials you are using (such as when you use
:func:`google.auth.default`). This functi... | [
"def",
"with_scopes_if_required",
"(",
"credentials",
",",
"scopes",
")",
":",
"if",
"isinstance",
"(",
"credentials",
",",
"Scoped",
")",
"and",
"credentials",
".",
"requires_scopes",
":",
"return",
"credentials",
".",
"with_scopes",
"(",
"scopes",
")",
"else",... | Creates a copy of the credentials with scopes if scoping is required.
This helper function is useful when you do not know (or care to know) the
specific type of credentials you are using (such as when you use
:func:`google.auth.default`). This function will call
:meth:`Scoped.with_scopes` if the creden... | [
"Creates",
"a",
"copy",
"of",
"the",
"credentials",
"with",
"scopes",
"if",
"scoping",
"is",
"required",
"."
] | python | train | 42.166667 |
DLR-RM/RAFCON | source/rafcon/utils/installation.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/installation.py#L228-L252 | def get_data_files_recursively(*rel_root_path, **kwargs):
""" Adds all files of the specified path to a data_files compatible list
:param tuple rel_root_path: List of path elements pointing to a directory of files
:return: list of tuples of install directory and list of source files
:rtype: list(tuple(... | [
"def",
"get_data_files_recursively",
"(",
"*",
"rel_root_path",
",",
"*",
"*",
"kwargs",
")",
":",
"result_list",
"=",
"list",
"(",
")",
"rel_root_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"rel_root_path",
")",
"share_target_root",
"=",
"os",
".... | Adds all files of the specified path to a data_files compatible list
:param tuple rel_root_path: List of path elements pointing to a directory of files
:return: list of tuples of install directory and list of source files
:rtype: list(tuple(str, [str])) | [
"Adds",
"all",
"files",
"of",
"the",
"specified",
"path",
"to",
"a",
"data_files",
"compatible",
"list"
] | python | train | 49.28 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/gallery/gallery_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/gallery/gallery_client.py#L1326-L1343 | def delete_question(self, publisher_name, extension_name, question_id):
"""DeleteQuestion.
[Preview API] Deletes an existing question and all its associated responses for an extension. (soft delete)
:param str publisher_name: Name of the publisher who published the extension.
:param str ... | [
"def",
"delete_question",
"(",
"self",
",",
"publisher_name",
",",
"extension_name",
",",
"question_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"publisher_name",
"is",
"not",
"None",
":",
"route_values",
"[",
"'publisherName'",
"]",
"=",
"self",
".",
... | DeleteQuestion.
[Preview API] Deletes an existing question and all its associated responses for an extension. (soft delete)
:param str publisher_name: Name of the publisher who published the extension.
:param str extension_name: Name of the extension.
:param long question_id: Identifier ... | [
"DeleteQuestion",
".",
"[",
"Preview",
"API",
"]",
"Deletes",
"an",
"existing",
"question",
"and",
"all",
"its",
"associated",
"responses",
"for",
"an",
"extension",
".",
"(",
"soft",
"delete",
")",
":",
"param",
"str",
"publisher_name",
":",
"Name",
"of",
... | python | train | 60.833333 |
ff0000/scarlet | scarlet/cms/sites.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/sites.py#L104-L124 | def register(self, slug, bundle, order=1, title=None):
"""
Registers the bundle for a certain slug.
If a slug is already registered, this will raise AlreadyRegistered.
:param slug: The slug to register.
:param bundle: The bundle instance being registered.
:param order: ... | [
"def",
"register",
"(",
"self",
",",
"slug",
",",
"bundle",
",",
"order",
"=",
"1",
",",
"title",
"=",
"None",
")",
":",
"if",
"slug",
"in",
"self",
".",
"_registry",
":",
"raise",
"AlreadyRegistered",
"(",
"'The url %s is already registered'",
"%",
"slug"... | Registers the bundle for a certain slug.
If a slug is already registered, this will raise AlreadyRegistered.
:param slug: The slug to register.
:param bundle: The bundle instance being registered.
:param order: An integer that controls where this bundle's \
dashboard links appe... | [
"Registers",
"the",
"bundle",
"for",
"a",
"certain",
"slug",
"."
] | python | train | 36 |
HIPS/autograd | autograd/differential_operators.py | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L98-L105 | def tensor_jacobian_product(fun, argnum=0):
"""Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs)."""
def vector_dot_fun(*args, **kwargs):
args, vector = args[:-1],... | [
"def",
"tensor_jacobian_product",
"(",
"fun",
",",
"argnum",
"=",
"0",
")",
":",
"def",
"vector_dot_fun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
",",
"vector",
"=",
"args",
"[",
":",
"-",
"1",
"]",
",",
"args",
"[",
"-",
"1"... | Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs). | [
"Builds",
"a",
"function",
"that",
"returns",
"the",
"exact",
"tensor",
"-",
"Jacobian",
"product",
"that",
"is",
"the",
"Jacobian",
"matrix",
"left",
"-",
"multiplied",
"by",
"tensor",
".",
"The",
"returned",
"function",
"has",
"arguments",
"(",
"*",
"args"... | python | train | 55.75 |
lk-geimfari/mimesis | mimesis/shortcuts.py | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/shortcuts.py#L14-L26 | def luhn_checksum(num: str) -> str:
"""Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number.
"""
check = 0
for i, s in enumerate(reversed(num)):
sx = int(s)
sx = sx * 2 if i % 2 == 0 e... | [
"def",
"luhn_checksum",
"(",
"num",
":",
"str",
")",
"->",
"str",
":",
"check",
"=",
"0",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"reversed",
"(",
"num",
")",
")",
":",
"sx",
"=",
"int",
"(",
"s",
")",
"sx",
"=",
"sx",
"*",
"2",
"if",
... | Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number. | [
"Calculate",
"a",
"checksum",
"for",
"num",
"using",
"the",
"Luhn",
"algorithm",
"."
] | python | train | 31 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L203-L214 | def web_error_and_result(f):
"""
Same as error_and_result decorator, except:
If no exception was raised during task execution, ONLY IN CASE OF WEB
REQUEST formats task result into json dictionary {'data': task return value}
"""
@wraps(f)
def web_error_and_result_decorator(*args, **kwargs):
... | [
"def",
"web_error_and_result",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"web_error_and_result_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"error_and_result_decorator_inner_fn",
"(",
"f",
",",
"True",
",",
"*",
... | Same as error_and_result decorator, except:
If no exception was raised during task execution, ONLY IN CASE OF WEB
REQUEST formats task result into json dictionary {'data': task return value} | [
"Same",
"as",
"error_and_result",
"decorator",
"except",
":",
"If",
"no",
"exception",
"was",
"raised",
"during",
"task",
"execution",
"ONLY",
"IN",
"CASE",
"OF",
"WEB",
"REQUEST",
"formats",
"task",
"result",
"into",
"json",
"dictionary",
"{",
"data",
":",
... | python | train | 35.666667 |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L565-L571 | def _is_saccharide_arrow(self, before, after):
"""Return True if the arrow is in a chemical name."""
if (before and after and before[-1].isdigit() and after[0].isdigit() and
before.rstrip('0123456789').endswith('(') and after.lstrip('0123456789').startswith(')-')):
return True
... | [
"def",
"_is_saccharide_arrow",
"(",
"self",
",",
"before",
",",
"after",
")",
":",
"if",
"(",
"before",
"and",
"after",
"and",
"before",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
"and",
"after",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"and",
... | Return True if the arrow is in a chemical name. | [
"Return",
"True",
"if",
"the",
"arrow",
"is",
"in",
"a",
"chemical",
"name",
"."
] | python | train | 50 |
ionelmc/python-fields | src/fields/__init__.py | https://github.com/ionelmc/python-fields/blob/91e13560173abcc42cc1a95cbe2956b307126416/src/fields/__init__.py#L204-L222 | def slots_class_sealer(fields, defaults):
"""
This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally).
The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses.
"""
class __slots_meta__(type):
def __new__(mcs, name, bas... | [
"def",
"slots_class_sealer",
"(",
"fields",
",",
"defaults",
")",
":",
"class",
"__slots_meta__",
"(",
"type",
")",
":",
"def",
"__new__",
"(",
"mcs",
",",
"name",
",",
"bases",
",",
"namespace",
")",
":",
"if",
"\"__slots__\"",
"not",
"in",
"namespace",
... | This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally).
The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses. | [
"This",
"sealer",
"makes",
"a",
"container",
"class",
"that",
"uses",
"__slots__",
"(",
"it",
"uses",
":",
"func",
":",
"class_sealer",
"internally",
")",
"."
] | python | train | 36.263158 |
Kozea/wdb | client/wdb/ext.py | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/ext.py#L33-L46 | def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if th... | [
"def",
"_patch_tcpserver",
"(",
")",
":",
"shutdown_request",
"=",
"TCPServer",
".",
"shutdown_request",
"def",
"shutdown_request_patched",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"current_thread",
"(",
")",
"shutdown_request",
"(",
... | Patch shutdown_request to open blocking interaction after the end of the
request | [
"Patch",
"shutdown_request",
"to",
"open",
"blocking",
"interaction",
"after",
"the",
"end",
"of",
"the",
"request"
] | python | train | 31.857143 |
NarrativeScience/lsi | src/lsi/utils/hosts.py | https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L296-L306 | def display(self):
"""
Returns the best name to display for this host. Uses the instance
name if available; else just the public IP.
:rtype: ``str``
"""
if isinstance(self.name, six.string_types) and len(self.name) > 0:
return '{0} ({1})'.format(self.name, se... | [
"def",
"display",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"name",
",",
"six",
".",
"string_types",
")",
"and",
"len",
"(",
"self",
".",
"name",
")",
">",
"0",
":",
"return",
"'{0} ({1})'",
".",
"format",
"(",
"self",
".",
"name... | Returns the best name to display for this host. Uses the instance
name if available; else just the public IP.
:rtype: ``str`` | [
"Returns",
"the",
"best",
"name",
"to",
"display",
"for",
"this",
"host",
".",
"Uses",
"the",
"instance",
"name",
"if",
"available",
";",
"else",
"just",
"the",
"public",
"IP",
"."
] | python | test | 33.727273 |
wbond/oscrypto | oscrypto/_osx/symmetric.py | https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_osx/symmetric.py#L82-L121 | def aes_cbc_no_padding_decrypt(key, data, iv):
"""
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
T... | [
"def",
"aes_cbc_no_padding_decrypt",
"(",
"key",
",",
"data",
",",
"iv",
")",
":",
"if",
"len",
"(",
"key",
")",
"not",
"in",
"[",
"16",
",",
"24",
",",
"32",
"]",
":",
"raise",
"ValueError",
"(",
"pretty_message",
"(",
"'''\n key must be either... | Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector - a byte string 16-bytes long
... | [
"Decrypts",
"AES",
"ciphertext",
"in",
"CBC",
"mode",
"using",
"a",
"128",
"192",
"or",
"256",
"bit",
"key",
"and",
"no",
"padding",
"."
] | python | valid | 27.95 |
tensorflow/probability | tensorflow_probability/python/distributions/hidden_markov_model.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/hidden_markov_model.py#L914-L917 | def _log_matrix_vector(ms, vs):
"""Multiply tensor of matrices by vectors assuming values stored are logs."""
return tf.reduce_logsumexp(input_tensor=ms + vs[..., tf.newaxis, :], axis=-1) | [
"def",
"_log_matrix_vector",
"(",
"ms",
",",
"vs",
")",
":",
"return",
"tf",
".",
"reduce_logsumexp",
"(",
"input_tensor",
"=",
"ms",
"+",
"vs",
"[",
"...",
",",
"tf",
".",
"newaxis",
",",
":",
"]",
",",
"axis",
"=",
"-",
"1",
")"
] | Multiply tensor of matrices by vectors assuming values stored are logs. | [
"Multiply",
"tensor",
"of",
"matrices",
"by",
"vectors",
"assuming",
"values",
"stored",
"are",
"logs",
"."
] | python | test | 47.25 |
twisted/mantissa | xmantissa/web.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L260-L281 | def locateChild(self, context, segments):
"""
Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard.
"""
shortcut = getattr(self, 'child_' + segments[0], None)
if shortcut:
res = shortcut(context)
... | [
"def",
"locateChild",
"(",
"self",
",",
"context",
",",
"segments",
")",
":",
"shortcut",
"=",
"getattr",
"(",
"self",
",",
"'child_'",
"+",
"segments",
"[",
"0",
"]",
",",
"None",
")",
"if",
"shortcut",
":",
"res",
"=",
"shortcut",
"(",
"context",
"... | Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard. | [
"Return",
"a",
"statically",
"defined",
"child",
"or",
"a",
"child",
"defined",
"by",
"a",
"sessionless",
"site",
"root",
"plugin",
"or",
"an",
"avatar",
"from",
"guard",
"."
] | python | train | 39 |
angr/angr | angr/state_plugins/preconstrainer.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/preconstrainer.py#L119-L158 | def remove_preconstraints(self, to_composite_solver=True, simplify=True):
"""
Remove the preconstraints from the state.
If you are using the zen plugin, this will also use that to filter the constraints.
:param to_composite_solver: Whether to convert the replacement solver to a com... | [
"def",
"remove_preconstraints",
"(",
"self",
",",
"to_composite_solver",
"=",
"True",
",",
"simplify",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"preconstraints",
":",
"return",
"# cache key set creation",
"precon_cache_keys",
"=",
"set",
"(",
")",
"for",... | Remove the preconstraints from the state.
If you are using the zen plugin, this will also use that to filter the constraints.
:param to_composite_solver: Whether to convert the replacement solver to a composite solver. You probably
want this if you're switch... | [
"Remove",
"the",
"preconstraints",
"from",
"the",
"state",
"."
] | python | train | 42.825 |
bapakode/OmMongo | ommongo/session.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/session.py#L442-L448 | def clear_collection(self, *classes):
''' Clear all objects from the collections associated with the
objects in `*cls`. **use with caution!**'''
for c in classes:
self.queue.append(ClearCollectionOp(self.transaction_id, self, c))
if self.autoflush:
self.flush() | [
"def",
"clear_collection",
"(",
"self",
",",
"*",
"classes",
")",
":",
"for",
"c",
"in",
"classes",
":",
"self",
".",
"queue",
".",
"append",
"(",
"ClearCollectionOp",
"(",
"self",
".",
"transaction_id",
",",
"self",
",",
"c",
")",
")",
"if",
"self",
... | Clear all objects from the collections associated with the
objects in `*cls`. **use with caution!** | [
"Clear",
"all",
"objects",
"from",
"the",
"collections",
"associated",
"with",
"the",
"objects",
"in",
"*",
"cls",
".",
"**",
"use",
"with",
"caution!",
"**"
] | python | train | 38.571429 |
BernardFW/bernard | src/bernard/platforms/telegram/platform.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/telegram/platform.py#L126-L150 | async def _get_full_user(self) -> Dict:
"""
Sometimes Telegram does not provide all the user info with the message.
In order to get the full profile (aka the language code) you need to
call this method which will make sure that the full User object is
loaded.
The result ... | [
"async",
"def",
"_get_full_user",
"(",
"self",
")",
"->",
"Dict",
":",
"if",
"'language_code'",
"in",
"self",
".",
"_user",
":",
"return",
"self",
".",
"_user",
"async",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_full_user",
"is",
"None",
... | Sometimes Telegram does not provide all the user info with the message.
In order to get the full profile (aka the language code) you need to
call this method which will make sure that the full User object is
loaded.
The result is cached for the lifetime of the object, so if the function... | [
"Sometimes",
"Telegram",
"does",
"not",
"provide",
"all",
"the",
"user",
"info",
"with",
"the",
"message",
".",
"In",
"order",
"to",
"get",
"the",
"full",
"profile",
"(",
"aka",
"the",
"language",
"code",
")",
"you",
"need",
"to",
"call",
"this",
"method... | python | train | 37.88 |
push-things/django-th | django_th/publishing_limit.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/publishing_limit.py#L13-L41 | def get_data(service, cache_data, trigger_id):
"""
get the data from the cache
:param service: the service name
:param cache_data: the data from the cache
:type trigger_id: integer
:return: Return the data from the cache
:rtype: object
... | [
"def",
"get_data",
"(",
"service",
",",
"cache_data",
",",
"trigger_id",
")",
":",
"if",
"service",
".",
"startswith",
"(",
"'th_'",
")",
":",
"cache",
"=",
"caches",
"[",
"'django_th'",
"]",
"limit",
"=",
"settings",
".",
"DJANGO_TH",
".",
"get",
"(",
... | get the data from the cache
:param service: the service name
:param cache_data: the data from the cache
:type trigger_id: integer
:return: Return the data from the cache
:rtype: object | [
"get",
"the",
"data",
"from",
"the",
"cache",
":",
"param",
"service",
":",
"the",
"service",
"name",
":",
"param",
"cache_data",
":",
"the",
"data",
"from",
"the",
"cache",
":",
"type",
"trigger_id",
":",
"integer",
":",
"return",
":",
"Return",
"the",
... | python | train | 42.137931 |
pybel/pybel-tools | src/pybel_tools/document_utils/utils.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/document_utils/utils.py#L24-L36 | def lint_directory(source, target):
"""Adds a linted version of each document in the source directory to the target directory
:param str source: Path to directory to lint
:param str target: Path to directory to output
"""
for path in os.listdir(source):
if not path.endswith('.bel'):
... | [
"def",
"lint_directory",
"(",
"source",
",",
"target",
")",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"source",
")",
":",
"if",
"not",
"path",
".",
"endswith",
"(",
"'.bel'",
")",
":",
"continue",
"log",
".",
"info",
"(",
"'linting: %s'",
... | Adds a linted version of each document in the source directory to the target directory
:param str source: Path to directory to lint
:param str target: Path to directory to output | [
"Adds",
"a",
"linted",
"version",
"of",
"each",
"document",
"in",
"the",
"source",
"directory",
"to",
"the",
"target",
"directory"
] | python | valid | 37.230769 |
bcbio/bcbio-nextgen | scripts/utils/cwltool2nextflow.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/utils/cwltool2nextflow.py#L116-L134 | def _wf_to_dict(wf):
"""Parse a workflow into cwl2wdl style dictionary.
"""
inputs, outputs = _get_wf_inout(wf)
out = {"name": _id_to_name(wf.tool["id"]).replace("-", "_"), "inputs": inputs,
"outputs": outputs, "steps": [], "subworkflows": [],
"requirements": []}
for step in wf... | [
"def",
"_wf_to_dict",
"(",
"wf",
")",
":",
"inputs",
",",
"outputs",
"=",
"_get_wf_inout",
"(",
"wf",
")",
"out",
"=",
"{",
"\"name\"",
":",
"_id_to_name",
"(",
"wf",
".",
"tool",
"[",
"\"id\"",
"]",
")",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
... | Parse a workflow into cwl2wdl style dictionary. | [
"Parse",
"a",
"workflow",
"into",
"cwl2wdl",
"style",
"dictionary",
"."
] | python | train | 52.368421 |
erinxocon/requests-xml | requests_xml.py | https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L105-L112 | def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
"""
if self._pq is None:
self._pq = PyQuery(self.raw_xml)
return self._pq | [
"def",
"pq",
"(",
"self",
")",
"->",
"PyQuery",
":",
"if",
"self",
".",
"_pq",
"is",
"None",
":",
"self",
".",
"_pq",
"=",
"PyQuery",
"(",
"self",
".",
"raw_xml",
")",
"return",
"self",
".",
"_pq"
] | `PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`. | [
"PyQuery",
"<https",
":",
"//",
"pythonhosted",
".",
"org",
"/",
"pyquery",
"/",
">",
"_",
"representation",
"of",
"the",
":",
"class",
":",
"Element",
"<Element",
">",
"or",
":",
"class",
":",
"HTML",
"<HTML",
">",
"."
] | python | train | 33.5 |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L4298-L4309 | def ekntab():
"""
Return the number of loaded EK tables.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html
:return: The number of loaded EK tables.
:rtype: int
"""
n = ctypes.c_int(0)
libspice.ekntab_c(ctypes.byref(n))
return n.value | [
"def",
"ekntab",
"(",
")",
":",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"libspice",
".",
"ekntab_c",
"(",
"ctypes",
".",
"byref",
"(",
"n",
")",
")",
"return",
"n",
".",
"value"
] | Return the number of loaded EK tables.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html
:return: The number of loaded EK tables.
:rtype: int | [
"Return",
"the",
"number",
"of",
"loaded",
"EK",
"tables",
"."
] | python | train | 23.333333 |
rorr73/LifeSOSpy | lifesospy/response.py | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/response.py#L350-L361 | def rssi_bars(self) -> int:
"""Received Signal Strength Indication, from 0 to 4 bars."""
rssi_db = self.rssi_db
if rssi_db < 45:
return 0
elif rssi_db < 60:
return 1
elif rssi_db < 75:
return 2
elif rssi_db < 90:
return 3
... | [
"def",
"rssi_bars",
"(",
"self",
")",
"->",
"int",
":",
"rssi_db",
"=",
"self",
".",
"rssi_db",
"if",
"rssi_db",
"<",
"45",
":",
"return",
"0",
"elif",
"rssi_db",
"<",
"60",
":",
"return",
"1",
"elif",
"rssi_db",
"<",
"75",
":",
"return",
"2",
"eli... | Received Signal Strength Indication, from 0 to 4 bars. | [
"Received",
"Signal",
"Strength",
"Indication",
"from",
"0",
"to",
"4",
"bars",
"."
] | python | train | 26.916667 |
todddeluca/temps | temps.py | https://github.com/todddeluca/temps/blob/10bf4e71a6b2e8ad10fa8a272145968b6c84f61b/temps.py#L88-L110 | def tmpfile(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
'''
For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
... | [
"def",
"tmpfile",
"(",
"root",
"=",
"TEMPS_DIR",
",",
"prefix",
"=",
"TEMPS_PREFIX",
",",
"suffix",
"=",
"TEMPS_SUFFIX",
")",
":",
"path",
"=",
"tmppath",
"(",
"root",
",",
"prefix",
",",
"suffix",
")",
"try",
":",
"yield",
"path",
"finally",
":",
"if"... | For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
when the with statement is exited, the file will be removed.
This function is... | [
"For",
"use",
"in",
"a",
"with",
"statement",
"this",
"function",
"returns",
"a",
"context",
"manager",
"that",
"yields",
"a",
"path",
"directly",
"under",
"root",
"guaranteed",
"to",
"be",
"unique",
"by",
"using",
"the",
"uuid",
"module",
".",
"This",
"pa... | python | train | 34.478261 |
akolpakov/django-unused-media | django_unused_media/remove.py | https://github.com/akolpakov/django-unused-media/blob/0a6c38840f4eac49d285c7be5da7330a564cee92/django_unused_media/remove.py#L16-L33 | def remove_empty_dirs(path=None):
"""
Recursively delete empty directories; return True if everything was deleted.
"""
if not path:
path = settings.MEDIA_ROOT
if not os.path.isdir(path):
return False
listdir = [os.path.join(path, filename) for filename in os.listdir(path)]... | [
"def",
"remove_empty_dirs",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"settings",
".",
"MEDIA_ROOT",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"False",
"listdir",
"=",
"[",
"os",
... | Recursively delete empty directories; return True if everything was deleted. | [
"Recursively",
"delete",
"empty",
"directories",
";",
"return",
"True",
"if",
"everything",
"was",
"deleted",
"."
] | python | train | 23.833333 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L39-L52 | def get_apps(self):
"""
Get the list of installed apps
and return the apps that have
an emails module
"""
templates = []
for app in settings.INSTALLED_APPS:
try:
app = import_module(app + '.emails')
templates += self.get... | [
"def",
"get_apps",
"(",
"self",
")",
":",
"templates",
"=",
"[",
"]",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"try",
":",
"app",
"=",
"import_module",
"(",
"app",
"+",
"'.emails'",
")",
"templates",
"+=",
"self",
".",
"get_plugs_mail_... | Get the list of installed apps
and return the apps that have
an emails module | [
"Get",
"the",
"list",
"of",
"installed",
"apps",
"and",
"return",
"the",
"apps",
"that",
"have",
"an",
"emails",
"module"
] | python | train | 29.214286 |
kmadac/bitstamp-python-client | bitstamp/client.py | https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L415-L421 | def litecoin_withdrawal(self, amount, address):
"""
Send litecoins to another litecoin wallet specified by address.
"""
data = {'amount': amount, 'address': address}
return self._post("ltc_withdrawal/", data=data, return_json=True,
version=2) | [
"def",
"litecoin_withdrawal",
"(",
"self",
",",
"amount",
",",
"address",
")",
":",
"data",
"=",
"{",
"'amount'",
":",
"amount",
",",
"'address'",
":",
"address",
"}",
"return",
"self",
".",
"_post",
"(",
"\"ltc_withdrawal/\"",
",",
"data",
"=",
"data",
... | Send litecoins to another litecoin wallet specified by address. | [
"Send",
"litecoins",
"to",
"another",
"litecoin",
"wallet",
"specified",
"by",
"address",
"."
] | python | train | 43.142857 |
inasafe/inasafe | safe/plugin.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/plugin.py#L648-L671 | def unload(self):
"""GUI breakdown procedure (for QGIS plugin api).
.. note:: Don't change the name of this method from unload!
This method is called by QGIS and should be used to *remove*
any graphical user interface elements that should appear in QGIS.
"""
# Remove th... | [
"def",
"unload",
"(",
"self",
")",
":",
"# Remove the plugin menu item and icon",
"if",
"self",
".",
"wizard",
":",
"self",
".",
"wizard",
".",
"deleteLater",
"(",
")",
"for",
"myAction",
"in",
"self",
".",
"actions",
":",
"self",
".",
"iface",
".",
"remov... | GUI breakdown procedure (for QGIS plugin api).
.. note:: Don't change the name of this method from unload!
This method is called by QGIS and should be used to *remove*
any graphical user interface elements that should appear in QGIS. | [
"GUI",
"breakdown",
"procedure",
"(",
"for",
"QGIS",
"plugin",
"api",
")",
"."
] | python | train | 44.458333 |
hyperledger/indy-crypto | wrappers/python/indy_crypto/bls.py | https://github.com/hyperledger/indy-crypto/blob/1675e29a2a5949b44899553d3d128335cf7a61b3/wrappers/python/indy_crypto/bls.py#L41-L56 | def as_bytes(self) -> bytes:
"""
Returns BLS entity bytes representation.
:return: BLS entity bytes representation
"""
logger = logging.getLogger(__name__)
logger.debug("BlsEntity.as_bytes: >>> self: %r", self)
xbytes = POINTER(c_ubyte)()
xbytes_len = c_s... | [
"def",
"as_bytes",
"(",
"self",
")",
"->",
"bytes",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"BlsEntity.as_bytes: >>> self: %r\"",
",",
"self",
")",
"xbytes",
"=",
"POINTER",
"(",
"c_ubyte",
")",
... | Returns BLS entity bytes representation.
:return: BLS entity bytes representation | [
"Returns",
"BLS",
"entity",
"bytes",
"representation",
".",
":",
"return",
":",
"BLS",
"entity",
"bytes",
"representation"
] | python | train | 33.1875 |
IRC-SPHERE/HyperStream | hyperstream/time_interval.py | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/time_interval.py#L118-L135 | def split(self, points):
'''Splits the list of time intervals in the specified points
The function assumes that the time intervals do not overlap and ignores
points that are not inside of any interval.
Parameters
==========
points: list of datetime
'''
f... | [
"def",
"split",
"(",
"self",
",",
"points",
")",
":",
"for",
"p",
"in",
"points",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"intervals",
")",
")",
":",
"if",
"(",
"self",
".",
"intervals",
"[",
"i",
"]",
".",
"start",
"<",
... | Splits the list of time intervals in the specified points
The function assumes that the time intervals do not overlap and ignores
points that are not inside of any interval.
Parameters
==========
points: list of datetime | [
"Splits",
"the",
"list",
"of",
"time",
"intervals",
"in",
"the",
"specified",
"points"
] | python | train | 42.166667 |
rigetti/pyquil | pyquil/noise.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/noise.py#L715-L736 | def correct_bitstring_probs(p, assignment_probabilities):
"""
Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner
axis over bits) and a list of assignment probability matrices (one for each bit in the readout)
compute the corrected probabilities.
:param np.a... | [
"def",
"correct_bitstring_probs",
"(",
"p",
",",
"assignment_probabilities",
")",
":",
"return",
"_apply_local_transforms",
"(",
"p",
",",
"(",
"np",
".",
"linalg",
".",
"inv",
"(",
"ap",
")",
"for",
"ap",
"in",
"assignment_probabilities",
")",
")"
] | Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner
axis over bits) and a list of assignment probability matrices (one for each bit in the readout)
compute the corrected probabilities.
:param np.array p: An array that enumerates bitstring probabilities. When
... | [
"Given",
"a",
"2d",
"array",
"of",
"corrupted",
"bitstring",
"probabilities",
"(",
"outer",
"axis",
"iterates",
"over",
"shots",
"inner",
"axis",
"over",
"bits",
")",
"and",
"a",
"list",
"of",
"assignment",
"probability",
"matrices",
"(",
"one",
"for",
"each... | python | train | 57.681818 |
SBRG/ssbio | ssbio/protein/structure/properties/residues.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/residues.py#L82-L89 | def residue_distances(res_1_num, res_1_chain, res_2_num, res_2_chain, model):
"""Distance between the last atom of 2 residues"""
res1 = model[res_1_chain][res_1_num].child_list[-1]
res2 = model[res_2_chain][res_2_num].child_list[-1]
distance = res1 - res2
return distance | [
"def",
"residue_distances",
"(",
"res_1_num",
",",
"res_1_chain",
",",
"res_2_num",
",",
"res_2_chain",
",",
"model",
")",
":",
"res1",
"=",
"model",
"[",
"res_1_chain",
"]",
"[",
"res_1_num",
"]",
".",
"child_list",
"[",
"-",
"1",
"]",
"res2",
"=",
"mod... | Distance between the last atom of 2 residues | [
"Distance",
"between",
"the",
"last",
"atom",
"of",
"2",
"residues"
] | python | train | 35.75 |
koenedaele/skosprovider | skosprovider/uri.py | https://github.com/koenedaele/skosprovider/blob/7304a37953978ca8227febc2d3cc2b2be178f215/skosprovider/uri.py#L115-L128 | def generate(self, **kwargs):
'''
Generate a :term:`URI` based on parameters passed.
:param id: The id of the concept or collection.
:param type: What we're generating a :term:`URI` for: `concept`
or `collection`.
:rtype: string
'''
if kwargs['type'] ... | [
"def",
"generate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
"[",
"'type'",
"]",
"not",
"in",
"[",
"'concept'",
",",
"'collection'",
"]",
":",
"raise",
"ValueError",
"(",
"'Type %s is invalid'",
"%",
"kwargs",
"[",
"'type'",
"]",
... | Generate a :term:`URI` based on parameters passed.
:param id: The id of the concept or collection.
:param type: What we're generating a :term:`URI` for: `concept`
or `collection`.
:rtype: string | [
"Generate",
"a",
":",
"term",
":",
"URI",
"based",
"on",
"parameters",
"passed",
"."
] | python | valid | 37.214286 |
JamesRamm/longclaw | longclaw/orders/api.py | https://github.com/JamesRamm/longclaw/blob/8bbf2e6d703271b815ec111813c7c5d1d4e4e810/longclaw/orders/api.py#L22-L27 | def fulfill_order(self, request, pk):
"""Mark the order specified by pk as fulfilled
"""
order = Order.objects.get(id=pk)
order.fulfill()
return Response(status=status.HTTP_204_NO_CONTENT) | [
"def",
"fulfill_order",
"(",
"self",
",",
"request",
",",
"pk",
")",
":",
"order",
"=",
"Order",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"pk",
")",
"order",
".",
"fulfill",
"(",
")",
"return",
"Response",
"(",
"status",
"=",
"status",
".",
"HTT... | Mark the order specified by pk as fulfilled | [
"Mark",
"the",
"order",
"specified",
"by",
"pk",
"as",
"fulfilled"
] | python | train | 37.166667 |
SmartDeveloperHub/agora-client | agora/client/execution.py | https://github.com/SmartDeveloperHub/agora-client/blob/53e126d12c2803ee71cf0822aaa0b0cf08cc3df4/agora/client/execution.py#L68-L78 | def __extend_uri(prefixes, short):
"""
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
"""
for prefix in prefixes:
if short.startswith(prefix):
return short... | [
"def",
"__extend_uri",
"(",
"prefixes",
",",
"short",
")",
":",
"for",
"prefix",
"in",
"prefixes",
":",
"if",
"short",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"short",
".",
"replace",
"(",
"prefix",
"+",
"':'",
",",
"prefixes",
"[",
"pref... | Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return: | [
"Extend",
"a",
"prefixed",
"uri",
"with",
"the",
"help",
"of",
"a",
"specific",
"dictionary",
"of",
"prefixes",
":",
"param",
"prefixes",
":",
"Dictionary",
"of",
"prefixes",
":",
"param",
"short",
":",
"Prefixed",
"uri",
"to",
"be",
"extended",
":",
"retu... | python | train | 33.363636 |
google/grr | grr/client/grr_response_client/client_actions/file_finder.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/client_actions/file_finder.py#L140-L166 | def GetExpandedPaths(
args):
"""Expands given path patterns.
Args:
args: A `FileFinderArgs` instance that dictates the behaviour of the path
expansion.
Yields:
Absolute paths (as string objects) derived from input patterns.
Raises:
ValueError: For unsupported path types.
"""
if args... | [
"def",
"GetExpandedPaths",
"(",
"args",
")",
":",
"if",
"args",
".",
"pathtype",
"==",
"rdf_paths",
".",
"PathSpec",
".",
"PathType",
".",
"OS",
":",
"pathtype",
"=",
"rdf_paths",
".",
"PathSpec",
".",
"PathType",
".",
"OS",
"else",
":",
"raise",
"ValueE... | Expands given path patterns.
Args:
args: A `FileFinderArgs` instance that dictates the behaviour of the path
expansion.
Yields:
Absolute paths (as string objects) derived from input patterns.
Raises:
ValueError: For unsupported path types. | [
"Expands",
"given",
"path",
"patterns",
"."
] | python | train | 26.851852 |
inasafe/inasafe | safe/gui/tools/multi_buffer_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L238-L243 | def add_class_button_status(self):
"""Function to enable or disable add class button."""
if self.class_form.text() and self.radius_form.value() >= 0:
self.add_class_button.setEnabled(True)
else:
self.add_class_button.setEnabled(False) | [
"def",
"add_class_button_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"class_form",
".",
"text",
"(",
")",
"and",
"self",
".",
"radius_form",
".",
"value",
"(",
")",
">=",
"0",
":",
"self",
".",
"add_class_button",
".",
"setEnabled",
"(",
"True",
... | Function to enable or disable add class button. | [
"Function",
"to",
"enable",
"or",
"disable",
"add",
"class",
"button",
"."
] | python | train | 46.166667 |
PyconUK/ConferenceScheduler | src/conference_scheduler/lp_problem/constraints.py | https://github.com/PyconUK/ConferenceScheduler/blob/fb139f0ef2eab5ac8f4919aa4994d94d4e040030/src/conference_scheduler/lp_problem/constraints.py#L32-L47 | def _events_available_in_scheduled_slot(events, slots, X, **kwargs):
"""
Constraint that ensures that an event is scheduled in slots for which it is
available
"""
slot_availability_array = lpu.slot_availability_array(slots=slots,
events=event... | [
"def",
"_events_available_in_scheduled_slot",
"(",
"events",
",",
"slots",
",",
"X",
",",
"*",
"*",
"kwargs",
")",
":",
"slot_availability_array",
"=",
"lpu",
".",
"slot_availability_array",
"(",
"slots",
"=",
"slots",
",",
"events",
"=",
"events",
")",
"label... | Constraint that ensures that an event is scheduled in slots for which it is
available | [
"Constraint",
"that",
"ensures",
"that",
"an",
"event",
"is",
"scheduled",
"in",
"slots",
"for",
"which",
"it",
"is",
"available"
] | python | train | 41.25 |
FutunnOpen/futuquant | futuquant/quote/open_quote_context.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/quote/open_quote_context.py#L1655-L1723 | def get_holding_change_list(self, code, holder_type, start=None, end=None):
"""
获取大股东持股变动列表,只提供美股数据
:param code: 股票代码. 例如:'US.AAPL'
:param holder_type: 持有者类别,StockHolder_
:param start: 开始时间. 例如:'2016-10-01'
:param end: 结束时间,例如:'2017-10-01'。
start与end的组合如下:
... | [
"def",
"get_holding_change_list",
"(",
"self",
",",
"code",
",",
"holder_type",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"holder_type",
"=",
"STOCK_HOLDER_CLASS_MAP",
"[",
"holder_type",
"]",
"if",
"code",
"is",
"None",
"or",
"is_str",
... | 获取大股东持股变动列表,只提供美股数据
:param code: 股票代码. 例如:'US.AAPL'
:param holder_type: 持有者类别,StockHolder_
:param start: 开始时间. 例如:'2016-10-01'
:param end: 结束时间,例如:'2017-10-01'。
start与end的组合如下:
========== ========== ========================================
star... | [
"获取大股东持股变动列表",
"只提供美股数据"
] | python | train | 44.797101 |
TorkamaniLab/metapipe | metapipe/parser.py | https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/parser.py#L72-L84 | def _parse(self, lines, grammar, ignore_comments=False):
""" Given a type and a list, parse it using the more detailed
parse grammar.
"""
results = []
for c in lines:
if c != '' and not (ignore_comments and c[0] == '#'):
try:
result... | [
"def",
"_parse",
"(",
"self",
",",
"lines",
",",
"grammar",
",",
"ignore_comments",
"=",
"False",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"lines",
":",
"if",
"c",
"!=",
"''",
"and",
"not",
"(",
"ignore_comments",
"and",
"c",
"[",
"0",... | Given a type and a list, parse it using the more detailed
parse grammar. | [
"Given",
"a",
"type",
"and",
"a",
"list",
"parse",
"it",
"using",
"the",
"more",
"detailed",
"parse",
"grammar",
"."
] | python | train | 43.076923 |
sass/libsass-python | sassutils/builder.py | https://github.com/sass/libsass-python/blob/fde5b18bc761f0253e71685ee5489e4beb8a403e/sassutils/builder.py#L255-L302 | def build_one(self, package_dir, filename, source_map=False):
"""Builds one Sass/SCSS file.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:... | [
"def",
"build_one",
"(",
"self",
",",
"package_dir",
",",
"filename",
",",
"source_map",
"=",
"False",
")",
":",
"sass_filename",
",",
"css_filename",
"=",
"self",
".",
"resolve_filename",
"(",
"package_dir",
",",
"filename",
",",
")",
"root_path",
"=",
"os"... | Builds one Sass/SCSS file.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:`str`, :class:`basestring`
:param source_map: whether to use sour... | [
"Builds",
"one",
"Sass",
"/",
"SCSS",
"file",
"."
] | python | train | 41.729167 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.