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 |
|---|---|---|---|---|---|---|---|---|---|
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L4373-L4381 | def setspan(self, *args):
"""Sets the span of the span element anew, erases all data inside.
Arguments:
*args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme`
"""
self.data = []
for child in args:
self.append(child) | [
"def",
"setspan",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"data",
"=",
"[",
"]",
"for",
"child",
"in",
"args",
":",
"self",
".",
"append",
"(",
"child",
")"
] | Sets the span of the span element anew, erases all data inside.
Arguments:
*args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme` | [
"Sets",
"the",
"span",
"of",
"the",
"span",
"element",
"anew",
"erases",
"all",
"data",
"inside",
"."
] | python | train | 32.222222 |
rsheftel/raccoon | raccoon/dataframe.py | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L933-L943 | def delete_all_rows(self):
"""
Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all
information, and at the same time it keeps the container lists for the columns and index so if there is another
object that references this DataFrame... | [
"def",
"delete_all_rows",
"(",
"self",
")",
":",
"del",
"self",
".",
"_index",
"[",
":",
"]",
"for",
"c",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_columns",
")",
")",
":",
"del",
"self",
".",
"_data",
"[",
"c",
"]",
"[",
":",
"]"
] | Deletes the contents of all rows in the DataFrame. This function is faster than delete_rows() to remove all
information, and at the same time it keeps the container lists for the columns and index so if there is another
object that references this DataFrame, like a ViewSeries, the reference remains in t... | [
"Deletes",
"the",
"contents",
"of",
"all",
"rows",
"in",
"the",
"DataFrame",
".",
"This",
"function",
"is",
"faster",
"than",
"delete_rows",
"()",
"to",
"remove",
"all",
"information",
"and",
"at",
"the",
"same",
"time",
"it",
"keeps",
"the",
"container",
... | python | train | 46.454545 |
dagster-io/dagster | python_modules/dagstermill/dagstermill/__init__.py | https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagstermill/dagstermill/__init__.py#L478-L526 | def replace_parameters(context, nb, parameters):
# Uma: This is a copy-paste from papermill papermill/execute.py:104 (execute_parameters).
# Typically, papermill injects the injected-parameters cell *below* the parameters cell
# but we want to *replace* the parameters cell, which is what this function does.... | [
"def",
"replace_parameters",
"(",
"context",
",",
"nb",
",",
"parameters",
")",
":",
"# Uma: This is a copy-paste from papermill papermill/execute.py:104 (execute_parameters).",
"# Typically, papermill injects the injected-parameters cell *below* the parameters cell",
"# but we want to *repl... | Assigned parameters into the appropiate place in the input notebook
Args:
nb (NotebookNode): Executable notebook object
parameters (dict): Arbitrary keyword arguments to pass to the notebook parameters. | [
"Assigned",
"parameters",
"into",
"the",
"appropiate",
"place",
"in",
"the",
"input",
"notebook",
"Args",
":",
"nb",
"(",
"NotebookNode",
")",
":",
"Executable",
"notebook",
"object",
"parameters",
"(",
"dict",
")",
":",
"Arbitrary",
"keyword",
"arguments",
"t... | python | test | 44.938776 |
etcher-be/emiz | emiz/avwx/core.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L423-L430 | def is_possible_temp(temp: str) -> bool:
"""
Returns True if all characters are digits or 'M' (for minus)
"""
for char in temp:
if not (char.isdigit() or char == 'M'):
return False
return True | [
"def",
"is_possible_temp",
"(",
"temp",
":",
"str",
")",
"->",
"bool",
":",
"for",
"char",
"in",
"temp",
":",
"if",
"not",
"(",
"char",
".",
"isdigit",
"(",
")",
"or",
"char",
"==",
"'M'",
")",
":",
"return",
"False",
"return",
"True"
] | Returns True if all characters are digits or 'M' (for minus) | [
"Returns",
"True",
"if",
"all",
"characters",
"are",
"digits",
"or",
"M",
"(",
"for",
"minus",
")"
] | python | train | 28.125 |
HubbleHQ/heroku-kafka | heroku_kafka.py | https://github.com/HubbleHQ/heroku-kafka/blob/2c28b79e0ba130e13e91d9458826d4930eee2c52/heroku_kafka.py#L98-L103 | def send(self, topic, *args, **kwargs):
"""
Appends the prefix to the topic before sendingf
"""
prefix_topic = self.heroku_kafka.prefix_topic(topic)
return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"topic",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"prefix_topic",
"=",
"self",
".",
"heroku_kafka",
".",
"prefix_topic",
"(",
"topic",
")",
"return",
"super",
"(",
"HerokuKafkaProducer",
",",
"self",
")",
".... | Appends the prefix to the topic before sendingf | [
"Appends",
"the",
"prefix",
"to",
"the",
"topic",
"before",
"sendingf"
] | python | train | 43.166667 |
guaix-ucm/pyemir | emirdrp/recipes/acquisition/maskcheck.py | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/acquisition/maskcheck.py#L63-L119 | def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None):
"""Detect objects in a region and return the centroid of the brightest one"""
from matplotlib.patches import Ellipse
if logger is None:
logger = logging.getLogger(__name__)
region = bounding_box.slice
... | [
"def",
"comp_centroid",
"(",
"data",
",",
"bounding_box",
",",
"debug_plot",
"=",
"False",
",",
"plot_reference",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"from",
"matplotlib",
".",
"patches",
"import",
"Ellipse",
"if",
"logger",
"is",
"None",
":... | Detect objects in a region and return the centroid of the brightest one | [
"Detect",
"objects",
"in",
"a",
"region",
"and",
"return",
"the",
"centroid",
"of",
"the",
"brightest",
"one"
] | python | train | 34.280702 |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L2923-L2943 | def dbmin_stddev(self, value=None):
""" Corresponds to IDD Field `dbmin_stddev`
Standard deviation of extreme annual minimum dry-bulb temperature
Args:
value (float): value for IDD Field `dbmin_stddev`
Unit: C
if `value` is None it will not be checke... | [
"def",
"dbmin_stddev",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type f... | Corresponds to IDD Field `dbmin_stddev`
Standard deviation of extreme annual minimum dry-bulb temperature
Args:
value (float): value for IDD Field `dbmin_stddev`
Unit: C
if `value` is None it will not be checked against the
specification and i... | [
"Corresponds",
"to",
"IDD",
"Field",
"dbmin_stddev",
"Standard",
"deviation",
"of",
"extreme",
"annual",
"minimum",
"dry",
"-",
"bulb",
"temperature"
] | python | train | 36.238095 |
DataDog/integrations-core | vsphere/datadog_checks/vsphere/vsphere.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/vsphere/datadog_checks/vsphere/vsphere.py#L68-L80 | def trace_method(method):
"""
Decorator to catch and print the exceptions that happen within async tasks.
Note: this should be applied to methods of VSphereCheck only!
"""
def wrapper(*args, **kwargs):
try:
method(*args, **kwargs)
except Exception:
args[0].pr... | [
"def",
"trace_method",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"args",
"[",
"0",
"]",
".",
... | Decorator to catch and print the exceptions that happen within async tasks.
Note: this should be applied to methods of VSphereCheck only! | [
"Decorator",
"to",
"catch",
"and",
"print",
"the",
"exceptions",
"that",
"happen",
"within",
"async",
"tasks",
".",
"Note",
":",
"this",
"should",
"be",
"applied",
"to",
"methods",
"of",
"VSphereCheck",
"only!"
] | python | train | 30.461538 |
Vital-Fernandez/dazer | bin/lib/Astro_Libraries/cosmics.py | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/cosmics.py#L591-L617 | def run(self, maxiter = 4, verbose = False):
"""
Full artillery :-)
- Find saturated stars
- Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found)
Stops if no cosmics are found or if maxiter is reached.
"""
if self.satlev... | [
"def",
"run",
"(",
"self",
",",
"maxiter",
"=",
"4",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"self",
".",
"satlevel",
">",
"0",
"and",
"self",
".",
"satstars",
"==",
"None",
":",
"self",
".",
"findsatstars",
"(",
"verbose",
"=",
"True",
")",
... | Full artillery :-)
- Find saturated stars
- Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found)
Stops if no cosmics are found or if maxiter is reached. | [
"Full",
"artillery",
":",
"-",
")",
"-",
"Find",
"saturated",
"stars",
"-",
"Run",
"maxiter",
"L",
".",
"A",
".",
"Cosmic",
"iterations",
"(",
"stops",
"if",
"no",
"more",
"cosmics",
"are",
"found",
")",
"Stops",
"if",
"no",
"cosmics",
"are",
"found",
... | python | train | 42.111111 |
esterhui/pypu | pypu/service_flickr.py | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/service_flickr.py#L504-L572 | def _update_config_location(self,directory,files=None):
"""Loads location and applies to all files in given
files list (or if none, all files in flickr DB)
google reverse GEO to figure out location lat/long
file can contain things like:
Australia
Sydney, Australia
... | [
"def",
"_update_config_location",
"(",
"self",
",",
"directory",
",",
"files",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_connectToFlickr",
"(",
")",
":",
"print",
"(",
"\"%s - Couldn't connect to flickr\"",
"%",
"(",
"filename",
")",
")",
"return",
... | Loads location and applies to all files in given
files list (or if none, all files in flickr DB)
google reverse GEO to figure out location lat/long
file can contain things like:
Australia
Sydney, Australia
Holcomb Campground, California.
If image already has Lat... | [
"Loads",
"location",
"and",
"applies",
"to",
"all",
"files",
"in",
"given",
"files",
"list",
"(",
"or",
"if",
"none",
"all",
"files",
"in",
"flickr",
"DB",
")"
] | python | train | 36.173913 |
tanghaibao/jcvi | jcvi/formats/agp.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/agp.py#L1307-L1360 | def reindex(args):
"""
%prog agpfile
assume the component line order is correct, modify coordinates, this is
necessary mostly due to manual edits (insert/delete) that disrupts
the target coordinates.
"""
p = OptionParser(reindex.__doc__)
p.add_option("--nogaps", default=False, action="s... | [
"def",
"reindex",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"reindex",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--nogaps\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Remove all gap lin... | %prog agpfile
assume the component line order is correct, modify coordinates, this is
necessary mostly due to manual edits (insert/delete) that disrupts
the target coordinates. | [
"%prog",
"agpfile"
] | python | train | 29.944444 |
gaqzi/py-gocd | gocd/api/response.py | https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/response.py#L62-L68 | def is_json(self):
"""
Returns:
bool: True if `content_type` is `application/json`
"""
return (self.content_type.startswith('application/json') or
re.match(r'application/vnd.go.cd.v(\d+)\+json', self.content_type)) | [
"def",
"is_json",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"content_type",
".",
"startswith",
"(",
"'application/json'",
")",
"or",
"re",
".",
"match",
"(",
"r'application/vnd.go.cd.v(\\d+)\\+json'",
",",
"self",
".",
"content_type",
")",
")"
] | Returns:
bool: True if `content_type` is `application/json` | [
"Returns",
":",
"bool",
":",
"True",
"if",
"content_type",
"is",
"application",
"/",
"json"
] | python | valid | 38 |
nephila/djangocms-blog | djangocms_blog/admin.py | https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/admin.py#L247-L265 | def publish_post(self, request, pk):
"""
Admin view to publish a single post
:param request: request
:param pk: primary key of the post to publish
:return: Redirect to the post itself (if found) or fallback urls
"""
language = get_language_from_request(request, c... | [
"def",
"publish_post",
"(",
"self",
",",
"request",
",",
"pk",
")",
":",
"language",
"=",
"get_language_from_request",
"(",
"request",
",",
"check_path",
"=",
"True",
")",
"try",
":",
"post",
"=",
"Post",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"in... | Admin view to publish a single post
:param request: request
:param pk: primary key of the post to publish
:return: Redirect to the post itself (if found) or fallback urls | [
"Admin",
"view",
"to",
"publish",
"a",
"single",
"post"
] | python | train | 38.789474 |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/jinja2/compiler.py#L277-L285 | def visit_Name(self, node):
"""All assignments to names go through this function."""
if node.ctx == 'store':
self.identifiers.declared_locally.add(node.name)
elif node.ctx == 'param':
self.identifiers.declared_parameter.add(node.name)
elif node.ctx == 'load' and n... | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"ctx",
"==",
"'store'",
":",
"self",
".",
"identifiers",
".",
"declared_locally",
".",
"add",
"(",
"node",
".",
"name",
")",
"elif",
"node",
".",
"ctx",
"==",
"'param'",
":",... | All assignments to names go through this function. | [
"All",
"assignments",
"to",
"names",
"go",
"through",
"this",
"function",
"."
] | python | test | 47.222222 |
spacetelescope/drizzlepac | drizzlepac/sky.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L754-L767 | def _updateKW(image, filename, exten, skyKW, Value):
"""update the header with the kw,value"""
# Update the value in memory
image.header[skyKW] = Value
# Now update the value on disk
if isinstance(exten,tuple):
strexten = '[%s,%s]'%(exten[0],str(exten[1]))
else:
strexten = '[%s]... | [
"def",
"_updateKW",
"(",
"image",
",",
"filename",
",",
"exten",
",",
"skyKW",
",",
"Value",
")",
":",
"# Update the value in memory",
"image",
".",
"header",
"[",
"skyKW",
"]",
"=",
"Value",
"# Now update the value on disk",
"if",
"isinstance",
"(",
"exten",
... | update the header with the kw,value | [
"update",
"the",
"header",
"with",
"the",
"kw",
"value"
] | python | train | 39.5 |
SeattleTestbed/seash | pyreadline/console/console.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/console/console.py#L781-L801 | def hook_wrapper(prompt):
u'''Wrap a Python readline so it behaves like GNU readline.'''
try:
# call the Python hook
res = ensure_str(readline_hook(prompt))
# make sure it returned the right sort of thing
if res and not isinstance(res, str):
raise TypeError, u'... | [
"def",
"hook_wrapper",
"(",
"prompt",
")",
":",
"try",
":",
"# call the Python hook\r",
"res",
"=",
"ensure_str",
"(",
"readline_hook",
"(",
"prompt",
")",
")",
"# make sure it returned the right sort of thing\r",
"if",
"res",
"and",
"not",
"isinstance",
"(",
"res",... | u'''Wrap a Python readline so it behaves like GNU readline. | [
"u",
"Wrap",
"a",
"Python",
"readline",
"so",
"it",
"behaves",
"like",
"GNU",
"readline",
"."
] | python | train | 35.952381 |
project-rig/rig | rig/machine_control/struct_file.py | https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/struct_file.py#L9-L91 | def read_struct_file(struct_data):
"""Interpret a struct file defining the location of variables in memory.
Parameters
----------
struct_data : :py:class:`bytes`
String of :py:class:`bytes` containing data to interpret as the struct
definition.
Returns
-------
{struct_name:... | [
"def",
"read_struct_file",
"(",
"struct_data",
")",
":",
"# Holders for all structs",
"structs",
"=",
"dict",
"(",
")",
"# Holders for the current struct",
"name",
"=",
"None",
"# Iterate over every line in the file",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"str... | Interpret a struct file defining the location of variables in memory.
Parameters
----------
struct_data : :py:class:`bytes`
String of :py:class:`bytes` containing data to interpret as the struct
definition.
Returns
-------
{struct_name: :py:class:`~.Struct`}
A dictionar... | [
"Interpret",
"a",
"struct",
"file",
"defining",
"the",
"location",
"of",
"variables",
"in",
"memory",
"."
] | python | train | 36.554217 |
gplepage/gvar | src/gvar/linalg.py | https://github.com/gplepage/gvar/blob/d6671697319eb6280de3793c9a1c2b616c6f2ae0/src/gvar/linalg.py#L227-L293 | def lstsq(a, b, rcond=None, weighted=False, extrainfo=False):
""" Least-squares solution ``x`` to ``a @ x = b`` for |GVar|\s.
Here ``x`` is defined to be the solution that minimizes ``||b - a @ x||``.
If ``b`` has a covariance matrix, another option is to weight the
norm with the inverse covariance mat... | [
"def",
"lstsq",
"(",
"a",
",",
"b",
",",
"rcond",
"=",
"None",
",",
"weighted",
"=",
"False",
",",
"extrainfo",
"=",
"False",
")",
":",
"a",
"=",
"numpy",
".",
"asarray",
"(",
"a",
")",
"b",
"=",
"numpy",
".",
"asarray",
"(",
"b",
")",
"if",
... | Least-squares solution ``x`` to ``a @ x = b`` for |GVar|\s.
Here ``x`` is defined to be the solution that minimizes ``||b - a @ x||``.
If ``b`` has a covariance matrix, another option is to weight the
norm with the inverse covariance matrix: i.e., minimize
``|| isig @ b - isig @ a @ x||`` where ``isig`... | [
"Least",
"-",
"squares",
"solution",
"x",
"to",
"a",
"@",
"x",
"=",
"b",
"for",
"|GVar|",
"\\",
"s",
"."
] | python | train | 42.432836 |
numenta/nupic | src/nupic/frameworks/opf/model.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/frameworks/opf/model.py#L228-L237 | def _getModelCheckpointFilePath(checkpointDir):
""" Return the absolute path of the model's checkpoint file.
:param checkpointDir: (string)
Directory of where the experiment is to be or was saved
:returns: (string) An absolute path.
"""
path = os.path.join(checkpointDir, "model.data")
... | [
"def",
"_getModelCheckpointFilePath",
"(",
"checkpointDir",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"checkpointDir",
",",
"\"model.data\"",
")",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"return",
"path"
] | Return the absolute path of the model's checkpoint file.
:param checkpointDir: (string)
Directory of where the experiment is to be or was saved
:returns: (string) An absolute path. | [
"Return",
"the",
"absolute",
"path",
"of",
"the",
"model",
"s",
"checkpoint",
"file",
"."
] | python | valid | 35.7 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/reftrack.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L2036-L2053 | def unload(self, refobj):
"""Load the given refobject
Unload in this case means, that a reference is stays in the scene
but it is not in a loaded state.
So there is a reference, but data is not read from it.
This will call :meth:`ReftypeInterface.unload`.
:param refobj... | [
"def",
"unload",
"(",
"self",
",",
"refobj",
")",
":",
"inter",
"=",
"self",
".",
"get_typ_interface",
"(",
"self",
".",
"get_typ",
"(",
"refobj",
")",
")",
"ref",
"=",
"self",
".",
"get_reference",
"(",
"refobj",
")",
"inter",
".",
"unload",
"(",
"r... | Load the given refobject
Unload in this case means, that a reference is stays in the scene
but it is not in a loaded state.
So there is a reference, but data is not read from it.
This will call :meth:`ReftypeInterface.unload`.
:param refobj: the refobject
:type refobj:... | [
"Load",
"the",
"given",
"refobject"
] | python | train | 31.166667 |
crate/crate-python | src/crate/client/cursor.py | https://github.com/crate/crate-python/blob/68e39c95f5bbe88b74bbfa26de4347fc644636a8/src/crate/client/cursor.py#L212-L221 | def duration(self):
"""
This read-only attribute specifies the server-side duration of a query
in milliseconds.
"""
if self._closed or \
not self._result or \
"duration" not in self._result:
return -1
return self._result.get("du... | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
"or",
"not",
"self",
".",
"_result",
"or",
"\"duration\"",
"not",
"in",
"self",
".",
"_result",
":",
"return",
"-",
"1",
"return",
"self",
".",
"_result",
".",
"get",
"(",
"\"dur... | This read-only attribute specifies the server-side duration of a query
in milliseconds. | [
"This",
"read",
"-",
"only",
"attribute",
"specifies",
"the",
"server",
"-",
"side",
"duration",
"of",
"a",
"query",
"in",
"milliseconds",
"."
] | python | train | 32.2 |
tcalmant/ipopo | pelix/ipopo/contexts.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/contexts.py#L399-L413 | def add_instance(self, name, properties):
# type: (str, dict) -> None
"""
Stores the description of a component instance. The given properties
are stored as is.
:param name: Instance name
:param properties: Instance properties
:raise NameError: Already known inst... | [
"def",
"add_instance",
"(",
"self",
",",
"name",
",",
"properties",
")",
":",
"# type: (str, dict) -> None",
"if",
"name",
"in",
"self",
".",
"__instances",
":",
"raise",
"NameError",
"(",
"name",
")",
"# Store properties \"as-is\"",
"self",
".",
"__instances",
... | Stores the description of a component instance. The given properties
are stored as is.
:param name: Instance name
:param properties: Instance properties
:raise NameError: Already known instance name | [
"Stores",
"the",
"description",
"of",
"a",
"component",
"instance",
".",
"The",
"given",
"properties",
"are",
"stored",
"as",
"is",
"."
] | python | train | 31.866667 |
slackapi/python-slackclient | slack/web/client.py | https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/web/client.py#L1005-L1017 | def reminders_add(self, *, text: str, time: str, **kwargs) -> SlackResponse:
"""Creates a reminder.
Args:
text (str): The content of the reminder. e.g. 'eat a banana'
time (str): When this reminder should happen:
the Unix timestamp (up to five years from now e.g.... | [
"def",
"reminders_add",
"(",
"self",
",",
"*",
",",
"text",
":",
"str",
",",
"time",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"self",
".",
"_validate_xoxp_token",
"(",
")",
"kwargs",
".",
"update",
"(",
"{",
"\"text\"",
"... | Creates a reminder.
Args:
text (str): The content of the reminder. e.g. 'eat a banana'
time (str): When this reminder should happen:
the Unix timestamp (up to five years from now e.g. '1602288000'),
the number of seconds until the reminder (if within 24 h... | [
"Creates",
"a",
"reminder",
"."
] | python | train | 50.230769 |
rpcope1/HackerNewsAPI-Py | HackerNewsAPI/API.py | https://github.com/rpcope1/HackerNewsAPI-Py/blob/b231aed24ec59fc32af320bbef27d48cc4b69914/HackerNewsAPI/API.py#L122-L133 | def get_max_item(self):
"""
Get the current maximum item number
:return: The current maximum item number.
"""
suburl = "v0/maxitem.json"
try:
max_item = self._make_request(suburl)
except requests.HTTPError as e:
hn_logger.exception('Faulted... | [
"def",
"get_max_item",
"(",
"self",
")",
":",
"suburl",
"=",
"\"v0/maxitem.json\"",
"try",
":",
"max_item",
"=",
"self",
".",
"_make_request",
"(",
"suburl",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"hn_logger",
".",
"exception",
"(",
"... | Get the current maximum item number
:return: The current maximum item number. | [
"Get",
"the",
"current",
"maximum",
"item",
"number",
":",
"return",
":",
"The",
"current",
"maximum",
"item",
"number",
"."
] | python | train | 33.583333 |
hardbyte/python-can | can/interfaces/systec/ucan.py | https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/interfaces/systec/ucan.py#L484-L497 | def get_hardware_info(self):
"""
Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for
both CAN channels are returned separately.
:return:
Tuple with extended hardware information structure (see structure :class:`Hardware... | [
"def",
"get_hardware_info",
"(",
"self",
")",
":",
"hw_info_ex",
"=",
"HardwareInfoEx",
"(",
")",
"can_info_ch0",
",",
"can_info_ch1",
"=",
"ChannelInfo",
"(",
")",
",",
"ChannelInfo",
"(",
")",
"UcanGetHardwareInfoEx2",
"(",
"self",
".",
"_handle",
",",
"byre... | Returns the extended hardware information of a device. With multi-channel USB-CANmoduls the information for
both CAN channels are returned separately.
:return:
Tuple with extended hardware information structure (see structure :class:`HardwareInfoEx`) and
structures with informat... | [
"Returns",
"the",
"extended",
"hardware",
"information",
"of",
"a",
"device",
".",
"With",
"multi",
"-",
"channel",
"USB",
"-",
"CANmoduls",
"the",
"information",
"for",
"both",
"CAN",
"channels",
"are",
"returned",
"separately",
"."
] | python | train | 54.285714 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L95-L121 | def dissolve(inlist):
"""
list and tuple flattening
Parameters
----------
inlist: list
the list with sub-lists or tuples to be flattened
Returns
-------
list
the flattened result
Examples
--------
>>> dissolve([[1, 2], [3, 4]])
[1, 2, 3, 4]
... | [
"def",
"dissolve",
"(",
"inlist",
")",
":",
"out",
"=",
"[",
"]",
"for",
"i",
"in",
"inlist",
":",
"i",
"=",
"list",
"(",
"i",
")",
"if",
"isinstance",
"(",
"i",
",",
"tuple",
")",
"else",
"i",
"out",
".",
"extend",
"(",
"dissolve",
"(",
"i",
... | list and tuple flattening
Parameters
----------
inlist: list
the list with sub-lists or tuples to be flattened
Returns
-------
list
the flattened result
Examples
--------
>>> dissolve([[1, 2], [3, 4]])
[1, 2, 3, 4]
>>> dissolve([(1, 2, (3, ... | [
"list",
"and",
"tuple",
"flattening",
"Parameters",
"----------",
"inlist",
":",
"list",
"the",
"list",
"with",
"sub",
"-",
"lists",
"or",
"tuples",
"to",
"be",
"flattened",
"Returns",
"-------",
"list",
"the",
"flattened",
"result",
"Examples",
"--------",
">... | python | train | 20.518519 |
gawel/panoramisk | panoramisk/utils.py | https://github.com/gawel/panoramisk/blob/2ccb5d18be28a8e8f444dc0cd3a3bfb59aa19a8e/panoramisk/utils.py#L57-L88 | def agi_code_check(code=None, response=None, line=None):
"""
Check the AGI code and return a dict to help on error handling.
"""
code = int(code)
response = response or ""
result = {'status_code': code, 'result': ('', ''), 'msg': ''}
if code == 100:
result['msg'] = line
elif code... | [
"def",
"agi_code_check",
"(",
"code",
"=",
"None",
",",
"response",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"code",
"=",
"int",
"(",
"code",
")",
"response",
"=",
"response",
"or",
"\"\"",
"result",
"=",
"{",
"'status_code'",
":",
"code",
",... | Check the AGI code and return a dict to help on error handling. | [
"Check",
"the",
"AGI",
"code",
"and",
"return",
"a",
"dict",
"to",
"help",
"on",
"error",
"handling",
"."
] | python | test | 35.8125 |
cloudendpoints/endpoints-python | endpoints/apiserving.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/apiserving.py#L469-L494 | def protorpc_to_endpoints_error(self, status, body):
"""Convert a ProtoRPC error to the format expected by Google Endpoints.
If the body does not contain an ProtoRPC message in state APPLICATION_ERROR
the status and body will be returned unchanged.
Args:
status: HTTP status of the response from ... | [
"def",
"protorpc_to_endpoints_error",
"(",
"self",
",",
"status",
",",
"body",
")",
":",
"try",
":",
"rpc_error",
"=",
"self",
".",
"__PROTOJSON",
".",
"decode_message",
"(",
"remote",
".",
"RpcStatus",
",",
"body",
")",
"except",
"(",
"ValueError",
",",
"... | Convert a ProtoRPC error to the format expected by Google Endpoints.
If the body does not contain an ProtoRPC message in state APPLICATION_ERROR
the status and body will be returned unchanged.
Args:
status: HTTP status of the response from the backend
body: JSON-encoded error in format expecte... | [
"Convert",
"a",
"ProtoRPC",
"error",
"to",
"the",
"format",
"expected",
"by",
"Google",
"Endpoints",
"."
] | python | train | 36.846154 |
Workable/flask-log-request-id | flask_log_request_id/extras/celery.py | https://github.com/Workable/flask-log-request-id/blob/3aaea86dfe2621ecc443a1e739ae6a27ae1187be/flask_log_request_id/extras/celery.py#L21-L30 | def on_before_publish_insert_request_id_header(headers, **kwargs):
"""
This function is meant to be used as signal processor for "before_task_publish".
:param Dict headers: The headers of the message
:param kwargs: Any extra keyword arguments
"""
if _CELERY_X_HEADER not in headers:
reque... | [
"def",
"on_before_publish_insert_request_id_header",
"(",
"headers",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_CELERY_X_HEADER",
"not",
"in",
"headers",
":",
"request_id",
"=",
"current_request_id",
"(",
")",
"headers",
"[",
"_CELERY_X_HEADER",
"]",
"=",
"request... | This function is meant to be used as signal processor for "before_task_publish".
:param Dict headers: The headers of the message
:param kwargs: Any extra keyword arguments | [
"This",
"function",
"is",
"meant",
"to",
"be",
"used",
"as",
"signal",
"processor",
"for",
"before_task_publish",
".",
":",
"param",
"Dict",
"headers",
":",
"The",
"headers",
"of",
"the",
"message",
":",
"param",
"kwargs",
":",
"Any",
"extra",
"keyword",
"... | python | train | 47.8 |
mandiant/ioc_writer | ioc_writer/ioc_common.py | https://github.com/mandiant/ioc_writer/blob/712247f3a10bdc2584fa18ac909fc763f71df21a/ioc_writer/ioc_common.py#L93-L105 | def make_eventlogitem_log(log, condition='is', negate=False, preserve_case=False):
"""
Create a node for EventLogItem/log
:return: A IndicatorItem represented as an Element node
"""
document = 'EventLogItem'
search = 'EventLogItem/log'
content_type = 'string'
content = log
ii_no... | [
"def",
"make_eventlogitem_log",
"(",
"log",
",",
"condition",
"=",
"'is'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'EventLogItem'",
"search",
"=",
"'EventLogItem/log'",
"content_type",
"=",
"'string'",
"conten... | Create a node for EventLogItem/log
:return: A IndicatorItem represented as an Element node | [
"Create",
"a",
"node",
"for",
"EventLogItem",
"/",
"log",
":",
"return",
":",
"A",
"IndicatorItem",
"represented",
"as",
"an",
"Element",
"node"
] | python | train | 38.846154 |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L279-L312 | def assemble_common_meta(common_meta_dfs, fields_to_remove, sources, remove_all_metadata_fields, error_report_file):
""" Assemble the common metadata dfs together. Both indices are sorted.
Fields that are not in all the dfs are dropped.
Args:
common_meta_dfs (list of pandas dfs)
fields_to_r... | [
"def",
"assemble_common_meta",
"(",
"common_meta_dfs",
",",
"fields_to_remove",
",",
"sources",
",",
"remove_all_metadata_fields",
",",
"error_report_file",
")",
":",
"all_meta_df",
",",
"all_meta_df_with_dups",
"=",
"build_common_all_meta_df",
"(",
"common_meta_dfs",
",",
... | Assemble the common metadata dfs together. Both indices are sorted.
Fields that are not in all the dfs are dropped.
Args:
common_meta_dfs (list of pandas dfs)
fields_to_remove (list of strings): fields to be removed from the
common metadata because they don't agree across files
... | [
"Assemble",
"the",
"common",
"metadata",
"dfs",
"together",
".",
"Both",
"indices",
"are",
"sorted",
".",
"Fields",
"that",
"are",
"not",
"in",
"all",
"the",
"dfs",
"are",
"dropped",
"."
] | python | train | 40.676471 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L101-L107 | def get_taglist(node):
"""
Return a list of tags (with NRML namespace removed) representing the
order of the nodes within a node
"""
return [re.sub(r'\{[^}]*\}', "", copy(subnode.tag))
for subnode in node.nodes] | [
"def",
"get_taglist",
"(",
"node",
")",
":",
"return",
"[",
"re",
".",
"sub",
"(",
"r'\\{[^}]*\\}'",
",",
"\"\"",
",",
"copy",
"(",
"subnode",
".",
"tag",
")",
")",
"for",
"subnode",
"in",
"node",
".",
"nodes",
"]"
] | Return a list of tags (with NRML namespace removed) representing the
order of the nodes within a node | [
"Return",
"a",
"list",
"of",
"tags",
"(",
"with",
"NRML",
"namespace",
"removed",
")",
"representing",
"the",
"order",
"of",
"the",
"nodes",
"within",
"a",
"node"
] | python | train | 33.857143 |
knipknap/exscript | Exscript/util/start.py | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/start.py#L32-L64 | def run(users, hosts, func, **kwargs):
"""
Convenience function that creates an Exscript.Queue instance, adds
the given accounts, and calls Queue.run() with the given
hosts and function as an argument.
If you also want to pass arguments to the given function, you may use
util.decorator.bind() l... | [
"def",
"run",
"(",
"users",
",",
"hosts",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"attempts",
"=",
"kwargs",
".",
"get",
"(",
"\"attempts\"",
",",
"1",
")",
"if",
"\"attempts\"",
"in",
"kwargs",
":",
"del",
"kwargs",
"[",
"\"attempts\"",
"]",... | Convenience function that creates an Exscript.Queue instance, adds
the given accounts, and calls Queue.run() with the given
hosts and function as an argument.
If you also want to pass arguments to the given function, you may use
util.decorator.bind() like this::
def my_callback(job, host, conn, ... | [
"Convenience",
"function",
"that",
"creates",
"an",
"Exscript",
".",
"Queue",
"instance",
"adds",
"the",
"given",
"accounts",
"and",
"calls",
"Queue",
".",
"run",
"()",
"with",
"the",
"given",
"hosts",
"and",
"function",
"as",
"an",
"argument",
"."
] | python | train | 32.242424 |
pybel/pybel | src/pybel/struct/graph.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L397-L403 | def add_transcription(self, gene: Gene, rna: Union[Rna, MicroRna]) -> str:
"""Add a transcription relation from a gene to an RNA or miRNA node.
:param gene: A gene node
:param rna: An RNA or microRNA node
"""
return self.add_unqualified_edge(gene, rna, TRANSCRIBED_TO) | [
"def",
"add_transcription",
"(",
"self",
",",
"gene",
":",
"Gene",
",",
"rna",
":",
"Union",
"[",
"Rna",
",",
"MicroRna",
"]",
")",
"->",
"str",
":",
"return",
"self",
".",
"add_unqualified_edge",
"(",
"gene",
",",
"rna",
",",
"TRANSCRIBED_TO",
")"
] | Add a transcription relation from a gene to an RNA or miRNA node.
:param gene: A gene node
:param rna: An RNA or microRNA node | [
"Add",
"a",
"transcription",
"relation",
"from",
"a",
"gene",
"to",
"an",
"RNA",
"or",
"miRNA",
"node",
"."
] | python | train | 43.285714 |
crdoconnor/strictyaml | strictyaml/representation.py | https://github.com/crdoconnor/strictyaml/blob/efdac7f89e81679fc95686288cd32b9563fde609/strictyaml/representation.py#L102-L119 | def data(self):
"""
Returns raw data representation of the document or document segment.
Mappings are rendered as ordered dicts, sequences as lists and scalar values
as whatever the validator returns (int, string, etc.).
If no validators are used, scalar values are always retur... | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_value",
",",
"CommentedMap",
")",
":",
"mapping",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_value",
".",
"items",
"(",
")",
":",
"map... | Returns raw data representation of the document or document segment.
Mappings are rendered as ordered dicts, sequences as lists and scalar values
as whatever the validator returns (int, string, etc.).
If no validators are used, scalar values are always returned as strings. | [
"Returns",
"raw",
"data",
"representation",
"of",
"the",
"document",
"or",
"document",
"segment",
"."
] | python | train | 38.5 |
mesowx/MesoPy | MesoPy.py | https://github.com/mesowx/MesoPy/blob/cd1e837e108ed7a110d81cf789f19afcdd52145b/MesoPy.py#L497-L571 | def climatology(self, startclim, endclim, **kwargs):
r""" Returns a climatology of observations at a user specified location for a specified time. Users must specify
at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa',
'nwsfirezone', 'gacc', or... | [
"def",
"climatology",
"(",
"self",
",",
"startclim",
",",
"endclim",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_geo_param",
"(",
"kwargs",
")",
"kwargs",
"[",
"'startclim'",
"]",
"=",
"startclim",
"kwargs",
"[",
"'endclim'",
"]",
"=",
"endcl... | r""" Returns a climatology of observations at a user specified location for a specified time. Users must specify
at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa',
'nwsfirezone', 'gacc', or 'subgacc') to obtain observation data. Other parameters may ... | [
"r",
"Returns",
"a",
"climatology",
"of",
"observations",
"at",
"a",
"user",
"specified",
"location",
"for",
"a",
"specified",
"time",
".",
"Users",
"must",
"specify",
"at",
"least",
"one",
"geographic",
"search",
"parameter",
"(",
"stid",
"state",
"country",
... | python | train | 58.626667 |
BD2KGenomics/protect | docker/pipelineWrapper.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/docker/pipelineWrapper.py#L51-L168 | def run(self, args, pipeline_command):
"""
Invokes the pipeline with the defined command. Command line arguments, and the command need
to be set with arg_builder, and command_builder respectively before this method can be
invoked.
"""
# output that must be moved but not ... | [
"def",
"run",
"(",
"self",
",",
"args",
",",
"pipeline_command",
")",
":",
"# output that must be moved but not renamed",
"consistentNaming",
"=",
"[",
"'alignments/normal_dna_fix_pg_sorted.bam'",
",",
"'alignments/normal_dna_fix_pg_sorted.bam.bai'",
",",
"'alignments/rna_genome_... | Invokes the pipeline with the defined command. Command line arguments, and the command need
to be set with arg_builder, and command_builder respectively before this method can be
invoked. | [
"Invokes",
"the",
"pipeline",
"with",
"the",
"defined",
"command",
".",
"Command",
"line",
"arguments",
"and",
"the",
"command",
"need",
"to",
"be",
"set",
"with",
"arg_builder",
"and",
"command_builder",
"respectively",
"before",
"this",
"method",
"can",
"be",
... | python | train | 53.228814 |
theislab/scanpy | scanpy/plotting/_tools/paga.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_tools/paga.py#L21-L131 | def paga_compare(
adata,
basis=None,
edges=False,
color=None,
alpha=None,
groups=None,
components=None,
projection='2d',
legend_loc='on data',
legend_fontsize=None,
legend_fontweight='bold',
color_map=None,
palette=N... | [
"def",
"paga_compare",
"(",
"adata",
",",
"basis",
"=",
"None",
",",
"edges",
"=",
"False",
",",
"color",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"components",
"=",
"None",
",",
"projection",
"=",
"'2d'",
",",
"legend... | Scatter and PAGA graph side-by-side.
Consists in a scatter plot and the abstracted graph. See
:func:`~scanpy.api.pl.paga` for all related parameters.
See :func:`~scanpy.api.pl.paga_path` for visualizing gene changes along paths
through the abstracted graph.
Additional parameters are as follows.
... | [
"Scatter",
"and",
"PAGA",
"graph",
"side",
"-",
"by",
"-",
"side",
"."
] | python | train | 28.648649 |
qacafe/cdrouter.py | cdrouter/cdrouter.py | https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/cdrouter.py#L419-L451 | def authenticate(self, retries=3):
"""Set API token by authenticating via username/password.
:param retries: Number of authentication attempts to make before giving up as an int.
:return: Learned API token
:rtype: string
"""
username = self.username or self._getuser(sel... | [
"def",
"authenticate",
"(",
"self",
",",
"retries",
"=",
"3",
")",
":",
"username",
"=",
"self",
".",
"username",
"or",
"self",
".",
"_getuser",
"(",
"self",
".",
"base",
")",
"password",
"=",
"self",
".",
"password",
"while",
"retries",
">",
"0",
":... | Set API token by authenticating via username/password.
:param retries: Number of authentication attempts to make before giving up as an int.
:return: Learned API token
:rtype: string | [
"Set",
"API",
"token",
"by",
"authenticating",
"via",
"username",
"/",
"password",
"."
] | python | train | 31.727273 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L598-L610 | def run_selected_clicked(self):
"""Run the selected scenario."""
# get all selected rows
rows = sorted(set(index.row() for index in
self.table.selectedIndexes()))
self.enable_busy_cursor()
# iterate over selected rows
for row in rows:
... | [
"def",
"run_selected_clicked",
"(",
"self",
")",
":",
"# get all selected rows",
"rows",
"=",
"sorted",
"(",
"set",
"(",
"index",
".",
"row",
"(",
")",
"for",
"index",
"in",
"self",
".",
"table",
".",
"selectedIndexes",
"(",
")",
")",
")",
"self",
".",
... | Run the selected scenario. | [
"Run",
"the",
"selected",
"scenario",
"."
] | python | train | 39.615385 |
RRZE-HPC/kerncraft | kerncraft/kernel.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/kernel.py#L157-L165 | def force_iterable(f):
"""Will make any functions return an iterable objects by wrapping its result in a list."""
def wrapper(*args, **kwargs):
r = f(*args, **kwargs)
if hasattr(r, '__iter__'):
return r
else:
return [r]
return wrapper | [
"def",
"force_iterable",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"hasattr",
"(",
"r",
",",
"'__iter__'",
")",
":",
"return",... | Will make any functions return an iterable objects by wrapping its result in a list. | [
"Will",
"make",
"any",
"functions",
"return",
"an",
"iterable",
"objects",
"by",
"wrapping",
"its",
"result",
"in",
"a",
"list",
"."
] | python | test | 31.777778 |
bpython/curtsies | curtsies/formatstring.py | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L613-L626 | def _getitem_normalized(self, index):
"""Builds the more compact fmtstrs by using fromstr( of the control sequences)"""
index = normalize_slice(len(self), index)
counter = 0
output = ''
for fs in self.chunks:
if index.start < counter + len(fs) and index.stop > counter... | [
"def",
"_getitem_normalized",
"(",
"self",
",",
"index",
")",
":",
"index",
"=",
"normalize_slice",
"(",
"len",
"(",
"self",
")",
",",
"index",
")",
"counter",
"=",
"0",
"output",
"=",
"''",
"for",
"fs",
"in",
"self",
".",
"chunks",
":",
"if",
"index... | Builds the more compact fmtstrs by using fromstr( of the control sequences) | [
"Builds",
"the",
"more",
"compact",
"fmtstrs",
"by",
"using",
"fromstr",
"(",
"of",
"the",
"control",
"sequences",
")"
] | python | train | 42.785714 |
Aluriak/ACCC | accc/compiler/compiler.py | https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/compiler/compiler.py#L180-L192 | def _next_condition_lexems(self, source_code, source_code_size):
"""Return condition lexem readed in source_code"""
# find three lexems
lexems = tuple((
self._next_lexem(LEXEM_TYPE_COMPARISON, source_code, source_code_size),
self._next_lexem(LEXEM_TYPE_OPERATOR , source_... | [
"def",
"_next_condition_lexems",
"(",
"self",
",",
"source_code",
",",
"source_code_size",
")",
":",
"# find three lexems",
"lexems",
"=",
"tuple",
"(",
"(",
"self",
".",
"_next_lexem",
"(",
"LEXEM_TYPE_COMPARISON",
",",
"source_code",
",",
"source_code_size",
")",
... | Return condition lexem readed in source_code | [
"Return",
"condition",
"lexem",
"readed",
"in",
"source_code"
] | python | train | 48.923077 |
rocky/python3-trepan | trepan/processor/command/down.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/down.py#L28-L40 | def run(self, args):
"""**down** [*count*]
Move the current frame down in the stack trace (to a newer frame). 0
is the most recent frame. If no count is given, move down 1.
See also:
---------
`up` and `frame`."""
Mframe.adjust_relative(self.proc, self.name, args, self.signum)
return False | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"Mframe",
".",
"adjust_relative",
"(",
"self",
".",
"proc",
",",
"self",
".",
"name",
",",
"args",
",",
"self",
".",
"signum",
")",
"return",
"False"
] | **down** [*count*]
Move the current frame down in the stack trace (to a newer frame). 0
is the most recent frame. If no count is given, move down 1.
See also:
---------
`up` and `frame`. | [
"**",
"down",
"**",
"[",
"*",
"count",
"*",
"]"
] | python | test | 23.538462 |
programa-stic/barf-project | barf/arch/x86/parser.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/x86/parser.py#L100-L131 | def parse_operand(string, location, tokens):
"""Parse an x86 instruction operand.
"""
mod = " ".join(tokens.get("modifier", ""))
if "immediate" in tokens:
imm = parse_immediate("".join(tokens["immediate"]))
size = modifier_size.get(mod, None)
oprnd = X86ImmediateOperand(imm, si... | [
"def",
"parse_operand",
"(",
"string",
",",
"location",
",",
"tokens",
")",
":",
"mod",
"=",
"\" \"",
".",
"join",
"(",
"tokens",
".",
"get",
"(",
"\"modifier\"",
",",
"\"\"",
")",
")",
"if",
"\"immediate\"",
"in",
"tokens",
":",
"imm",
"=",
"parse_imm... | Parse an x86 instruction operand. | [
"Parse",
"an",
"x86",
"instruction",
"operand",
"."
] | python | train | 30.625 |
edx/XBlock | xblock/mixins.py | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/mixins.py#L388-L395 | def get_child(self, usage_id):
"""Return the child identified by ``usage_id``."""
if usage_id in self._child_cache:
return self._child_cache[usage_id]
child_block = self.runtime.get_block(usage_id, for_parent=self)
self._child_cache[usage_id] = child_block
return chi... | [
"def",
"get_child",
"(",
"self",
",",
"usage_id",
")",
":",
"if",
"usage_id",
"in",
"self",
".",
"_child_cache",
":",
"return",
"self",
".",
"_child_cache",
"[",
"usage_id",
"]",
"child_block",
"=",
"self",
".",
"runtime",
".",
"get_block",
"(",
"usage_id"... | Return the child identified by ``usage_id``. | [
"Return",
"the",
"child",
"identified",
"by",
"usage_id",
"."
] | python | train | 40.125 |
gmarull/qtmodern | qtmodern/styles.py | https://github.com/gmarull/qtmodern/blob/b58b24c5bcfa0b81c7b1af5a7dfdc0fae660ce0f/qtmodern/styles.py#L27-L69 | def dark(app):
""" Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance.
"""
_apply_base_theme(app)
darkPalette = QPalette()
# base
darkPalette.setColor(QPalette.WindowText, QColor(180, 180, 180))
darkPalette.setColor(QPalet... | [
"def",
"dark",
"(",
"app",
")",
":",
"_apply_base_theme",
"(",
"app",
")",
"darkPalette",
"=",
"QPalette",
"(",
")",
"# base",
"darkPalette",
".",
"setColor",
"(",
"QPalette",
".",
"WindowText",
",",
"QColor",
"(",
"180",
",",
"180",
",",
"180",
")",
"... | Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance. | [
"Apply",
"Dark",
"Theme",
"to",
"the",
"Qt",
"application",
"instance",
"."
] | python | train | 44.162791 |
ministryofjustice/money-to-prisoners-common | mtp_common/build_tasks/executor.py | https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/executor.py#L71-L80 | def lookup_task(self, task):
"""
Looks up a task by name or by callable
"""
if isinstance(task, str):
try:
return self[task]
except KeyError:
pass
raise TaskError('Unknown task %s' % task) | [
"def",
"lookup_task",
"(",
"self",
",",
"task",
")",
":",
"if",
"isinstance",
"(",
"task",
",",
"str",
")",
":",
"try",
":",
"return",
"self",
"[",
"task",
"]",
"except",
"KeyError",
":",
"pass",
"raise",
"TaskError",
"(",
"'Unknown task %s'",
"%",
"ta... | Looks up a task by name or by callable | [
"Looks",
"up",
"a",
"task",
"by",
"name",
"or",
"by",
"callable"
] | python | train | 27.5 |
Cadair/jupyter_environment_kernels | environment_kernels/core.py | https://github.com/Cadair/jupyter_environment_kernels/blob/3da304550b511bda7d5d39280379b5ca39bb31bc/environment_kernels/core.py#L128-L144 | def validate_env(self, envname):
"""
Check the name of the environment against the black list and the
whitelist. If a whitelist is specified only it is checked.
"""
if self.whitelist_envs and envname in self.whitelist_envs:
return True
elif self.whitelist_envs... | [
"def",
"validate_env",
"(",
"self",
",",
"envname",
")",
":",
"if",
"self",
".",
"whitelist_envs",
"and",
"envname",
"in",
"self",
".",
"whitelist_envs",
":",
"return",
"True",
"elif",
"self",
".",
"whitelist_envs",
":",
"return",
"False",
"if",
"self",
".... | Check the name of the environment against the black list and the
whitelist. If a whitelist is specified only it is checked. | [
"Check",
"the",
"name",
"of",
"the",
"environment",
"against",
"the",
"black",
"list",
"and",
"the",
"whitelist",
".",
"If",
"a",
"whitelist",
"is",
"specified",
"only",
"it",
"is",
"checked",
"."
] | python | train | 34.529412 |
UCL-INGI/INGInious | inginious/agent/docker_agent/_timeout_watcher.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/_timeout_watcher.py#L27-L35 | async def clean(self):
""" Close all the running tasks watching for a container timeout. All references to
containers are removed: any attempt to was_killed after a call to clean() will return None.
"""
for x in self._running_asyncio_tasks:
x.cancel()
self._contai... | [
"async",
"def",
"clean",
"(",
"self",
")",
":",
"for",
"x",
"in",
"self",
".",
"_running_asyncio_tasks",
":",
"x",
".",
"cancel",
"(",
")",
"self",
".",
"_container_had_error",
"=",
"set",
"(",
")",
"self",
".",
"_watching",
"=",
"set",
"(",
")",
"se... | Close all the running tasks watching for a container timeout. All references to
containers are removed: any attempt to was_killed after a call to clean() will return None. | [
"Close",
"all",
"the",
"running",
"tasks",
"watching",
"for",
"a",
"container",
"timeout",
".",
"All",
"references",
"to",
"containers",
"are",
"removed",
":",
"any",
"attempt",
"to",
"was_killed",
"after",
"a",
"call",
"to",
"clean",
"()",
"will",
"return",... | python | train | 45.333333 |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L16-L35 | def read_local_conf(local_conf):
"""Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict
"""
log = logging.getLogger(__name__)
# Attempt to read.
log.info('Reading c... | [
"def",
"read_local_conf",
"(",
"local_conf",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Attempt to read.",
"log",
".",
"info",
"(",
"'Reading config from %s...'",
",",
"local_conf",
")",
"try",
":",
"config",
"=",
"read_config",
... | Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict | [
"Search",
"for",
"conf",
".",
"py",
"in",
"any",
"rel_source",
"directory",
"in",
"CWD",
"and",
"if",
"found",
"read",
"it",
"and",
"return",
"."
] | python | train | 33 |
belbio/bel | bel/terms/terms.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/terms/terms.py#L101-L113 | def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str:
"""Get normalized term"""
if equivalents and len(equivalents) > 0:
for start_ns in namespace_targets:
if re.match(start_ns, term_id):
for target_ns in namespace_targets[start_ns]:
... | [
"def",
"get_normalized_term",
"(",
"term_id",
":",
"str",
",",
"equivalents",
":",
"list",
",",
"namespace_targets",
":",
"dict",
")",
"->",
"str",
":",
"if",
"equivalents",
"and",
"len",
"(",
"equivalents",
")",
">",
"0",
":",
"for",
"start_ns",
"in",
"... | Get normalized term | [
"Get",
"normalized",
"term"
] | python | train | 42.538462 |
smarie/python-parsyfiles | parsyfiles/parsing_registries.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_registries.py#L518-L529 | def get_all_supported_exts_for_type(self, type_to_match: Type[Any], strict: bool) -> Set[str]:
"""
Utility method to return the set of all supported file extensions that may be converted to objects of the given
type. type=JOKER is a joker that means all types
:param type_to_match:
... | [
"def",
"get_all_supported_exts_for_type",
"(",
"self",
",",
"type_to_match",
":",
"Type",
"[",
"Any",
"]",
",",
"strict",
":",
"bool",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"matching",
"=",
"self",
".",
"find_all_matching_parsers",
"(",
"desired_type",
"="... | Utility method to return the set of all supported file extensions that may be converted to objects of the given
type. type=JOKER is a joker that means all types
:param type_to_match:
:param strict:
:return: | [
"Utility",
"method",
"to",
"return",
"the",
"set",
"of",
"all",
"supported",
"file",
"extensions",
"that",
"may",
"be",
"converted",
"to",
"objects",
"of",
"the",
"given",
"type",
".",
"type",
"=",
"JOKER",
"is",
"a",
"joker",
"that",
"means",
"all",
"ty... | python | train | 48.833333 |
sirfoga/pyhal | hal/cvs/versioning.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/cvs/versioning.py#L235-L253 | def from_str(string, max_number=9, separator="."):
"""Parses string
:param string: Version
:param max_number: Max number reachable by sub
:param separator: Version numbers are separated with this split
:return: Parses string and returns object
"""
tokens = string... | [
"def",
"from_str",
"(",
"string",
",",
"max_number",
"=",
"9",
",",
"separator",
"=",
"\".\"",
")",
":",
"tokens",
"=",
"string",
".",
"split",
"(",
"separator",
")",
"tokens",
"=",
"list",
"(",
"reversed",
"(",
"tokens",
")",
")",
"# reverse order of im... | Parses string
:param string: Version
:param max_number: Max number reachable by sub
:param separator: Version numbers are separated with this split
:return: Parses string and returns object | [
"Parses",
"string"
] | python | train | 36.263158 |
pvlib/pvlib-python | pvlib/irradiance.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/irradiance.py#L965-L1004 | def king(surface_tilt, dhi, ghi, solar_zenith):
'''
Determine diffuse irradiance from the sky on a tilted surface using
the King model.
King's model determines the diffuse irradiance from the sky (ground
reflected irradiance is not included in this algorithm) on a tilted
surface using the surfa... | [
"def",
"king",
"(",
"surface_tilt",
",",
"dhi",
",",
"ghi",
",",
"solar_zenith",
")",
":",
"sky_diffuse",
"=",
"(",
"dhi",
"*",
"(",
"(",
"1",
"+",
"tools",
".",
"cosd",
"(",
"surface_tilt",
")",
")",
")",
"/",
"2",
"+",
"ghi",
"*",
"(",
"(",
"... | Determine diffuse irradiance from the sky on a tilted surface using
the King model.
King's model determines the diffuse irradiance from the sky (ground
reflected irradiance is not included in this algorithm) on a tilted
surface using the surface tilt angle, diffuse horizontal irradiance,
global hor... | [
"Determine",
"diffuse",
"irradiance",
"from",
"the",
"sky",
"on",
"a",
"tilted",
"surface",
"using",
"the",
"King",
"model",
"."
] | python | train | 33.35 |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/parser.py#L422-L552 | def _split_into_chunks(self):
"""Split the code object into a list of `Chunk` objects.
Each chunk is only entered at its first instruction, though there can
be many exits from a chunk.
Returns a list of `Chunk` objects.
"""
# The list of chunks so far, and the one we'r... | [
"def",
"_split_into_chunks",
"(",
"self",
")",
":",
"# The list of chunks so far, and the one we're working on.",
"chunks",
"=",
"[",
"]",
"chunk",
"=",
"None",
"# A dict mapping byte offsets of line starts to the line numbers.",
"bytes_lines_map",
"=",
"dict",
"(",
"self",
"... | Split the code object into a list of `Chunk` objects.
Each chunk is only entered at its first instruction, though there can
be many exits from a chunk.
Returns a list of `Chunk` objects. | [
"Split",
"the",
"code",
"object",
"into",
"a",
"list",
"of",
"Chunk",
"objects",
"."
] | python | test | 42.145038 |
briancappello/flask-unchained | flask_unchained/bundles/controller/templates.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/templates.py#L18-L23 | def parse_template(template):
"""returns a 2-tuple of (template_name, number_of_priors)"""
m = TEMPLATE_OVERRIDE_RE.match(template)
if not m:
return template, 0
return m.group('template'), int(m.group('depth')) | [
"def",
"parse_template",
"(",
"template",
")",
":",
"m",
"=",
"TEMPLATE_OVERRIDE_RE",
".",
"match",
"(",
"template",
")",
"if",
"not",
"m",
":",
"return",
"template",
",",
"0",
"return",
"m",
".",
"group",
"(",
"'template'",
")",
",",
"int",
"(",
"m",
... | returns a 2-tuple of (template_name, number_of_priors) | [
"returns",
"a",
"2",
"-",
"tuple",
"of",
"(",
"template_name",
"number_of_priors",
")"
] | python | train | 38.166667 |
chrislit/abydos | abydos/stats/_confusion_table.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_confusion_table.py#L422-L437 | def population(self):
"""Return population, N.
Returns
-------
int
The population (N) of the confusion table
Example
-------
>>> ct = ConfusionTable(120, 60, 20, 30)
>>> ct.population()
230
"""
return self._tp + self.... | [
"def",
"population",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tp",
"+",
"self",
".",
"_tn",
"+",
"self",
".",
"_fp",
"+",
"self",
".",
"_fn"
] | Return population, N.
Returns
-------
int
The population (N) of the confusion table
Example
-------
>>> ct = ConfusionTable(120, 60, 20, 30)
>>> ct.population()
230 | [
"Return",
"population",
"N",
"."
] | python | valid | 20.625 |
gwpy/gwpy | gwpy/timeseries/io/cache.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/timeseries/io/cache.py#L30-L76 | def preformat_cache(cache, start=None, end=None):
"""Preprocess a `list` of file paths for reading.
- read the cache from the file (if necessary)
- sieve the cache to only include data we need
Parameters
----------
cache : `list`, `str`
List of file paths, or path to a LAL-format cache... | [
"def",
"preformat_cache",
"(",
"cache",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"# open cache file",
"if",
"isinstance",
"(",
"cache",
",",
"FILE_LIKE",
"+",
"string_types",
")",
":",
"return",
"read_cache",
"(",
"cache",
",",
"sort",... | Preprocess a `list` of file paths for reading.
- read the cache from the file (if necessary)
- sieve the cache to only include data we need
Parameters
----------
cache : `list`, `str`
List of file paths, or path to a LAL-format cache file on disk.
start : `~gwpy.time.LIGOTimeGPS`, `fl... | [
"Preprocess",
"a",
"list",
"of",
"file",
"paths",
"for",
"reading",
"."
] | python | train | 34.340426 |
yyuu/botornado | boto/dynamodb/table.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/dynamodb/table.py#L104-L129 | def refresh(self, wait_for_active=False, retry_seconds=5):
"""
Refresh all of the fields of the Table object by calling
the underlying DescribeTable request.
:type wait_for_active: bool
:param wait_for_active: If True, this command will not return
until the table sta... | [
"def",
"refresh",
"(",
"self",
",",
"wait_for_active",
"=",
"False",
",",
"retry_seconds",
"=",
"5",
")",
":",
"done",
"=",
"False",
"while",
"not",
"done",
":",
"response",
"=",
"self",
".",
"layer2",
".",
"describe_table",
"(",
"self",
".",
"name",
"... | Refresh all of the fields of the Table object by calling
the underlying DescribeTable request.
:type wait_for_active: bool
:param wait_for_active: If True, this command will not return
until the table status, as returned from Amazon DynamoDB, is
'ACTIVE'.
:type ... | [
"Refresh",
"all",
"of",
"the",
"fields",
"of",
"the",
"Table",
"object",
"by",
"calling",
"the",
"underlying",
"DescribeTable",
"request",
"."
] | python | train | 38.076923 |
jim-easterbrook/pyctools | src/pyctools/core/config.py | https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/config.py#L381-L397 | def set_config(self, config):
"""Update the component's configuration.
Use the :py:meth:`get_config` method to get a copy of the
component's configuration, update that copy then call
:py:meth:`set_config` to update the component. This enables
the configuration to be changed in a... | [
"def",
"set_config",
"(",
"self",
",",
"config",
")",
":",
"# put copy of config on queue for running component",
"self",
".",
"_configmixin_queue",
".",
"append",
"(",
"copy",
".",
"deepcopy",
"(",
"config",
")",
")",
"# notify component, using thread safe method",
"se... | Update the component's configuration.
Use the :py:meth:`get_config` method to get a copy of the
component's configuration, update that copy then call
:py:meth:`set_config` to update the component. This enables
the configuration to be changed in a threadsafe manner while
the comp... | [
"Update",
"the",
"component",
"s",
"configuration",
"."
] | python | train | 40.529412 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/command_cursor.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/command_cursor.py#L70-L92 | def batch_size(self, batch_size):
"""Limits the number of documents returned in one batch. Each batch
requires a round trip to the server. It can be adjusted to optimize
performance and limit data transfer.
.. note:: batch_size can not override MongoDB's internal limits on the
... | [
"def",
"batch_size",
"(",
"self",
",",
"batch_size",
")",
":",
"if",
"not",
"isinstance",
"(",
"batch_size",
",",
"integer_types",
")",
":",
"raise",
"TypeError",
"(",
"\"batch_size must be an integer\"",
")",
"if",
"batch_size",
"<",
"0",
":",
"raise",
"Value... | Limits the number of documents returned in one batch. Each batch
requires a round trip to the server. It can be adjusted to optimize
performance and limit data transfer.
.. note:: batch_size can not override MongoDB's internal limits on the
amount of data it will return to the client... | [
"Limits",
"the",
"number",
"of",
"documents",
"returned",
"in",
"one",
"batch",
".",
"Each",
"batch",
"requires",
"a",
"round",
"trip",
"to",
"the",
"server",
".",
"It",
"can",
"be",
"adjusted",
"to",
"optimize",
"performance",
"and",
"limit",
"data",
"tra... | python | train | 44.26087 |
edx/edx-val | edxval/api.py | https://github.com/edx/edx-val/blob/30df48061e77641edb5272895b7c7f7f25eb7aa7/edxval/api.py#L419-L431 | def get_transcript_preferences(course_id):
"""
Retrieves course wide transcript preferences
Arguments:
course_id (str): course id
"""
try:
transcript_preference = TranscriptPreference.objects.get(course_id=course_id)
except TranscriptPreference.DoesNotExist:
return
... | [
"def",
"get_transcript_preferences",
"(",
"course_id",
")",
":",
"try",
":",
"transcript_preference",
"=",
"TranscriptPreference",
".",
"objects",
".",
"get",
"(",
"course_id",
"=",
"course_id",
")",
"except",
"TranscriptPreference",
".",
"DoesNotExist",
":",
"retur... | Retrieves course wide transcript preferences
Arguments:
course_id (str): course id | [
"Retrieves",
"course",
"wide",
"transcript",
"preferences"
] | python | train | 28.692308 |
arraylabs/pymyq | pymyq/device.py | https://github.com/arraylabs/pymyq/blob/413ae01ca23568f7b5f698a87e872f456072356b/pymyq/device.py#L127-L133 | def _coerce_state_from_string(value: Union[int, str]) -> str:
"""Return a proper state from a string input."""
try:
return STATE_MAP[int(value)]
except KeyError:
_LOGGER.error('Unknown state: %s', value)
return STATE_UNKNOWN | [
"def",
"_coerce_state_from_string",
"(",
"value",
":",
"Union",
"[",
"int",
",",
"str",
"]",
")",
"->",
"str",
":",
"try",
":",
"return",
"STATE_MAP",
"[",
"int",
"(",
"value",
")",
"]",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"'Unknow... | Return a proper state from a string input. | [
"Return",
"a",
"proper",
"state",
"from",
"a",
"string",
"input",
"."
] | python | train | 39.714286 |
matthiask/django-authlib | authlib/email.py | https://github.com/matthiask/django-authlib/blob/a142da7e27fe9d30f34a84b12f24f686f9d2c8e1/authlib/email.py#L118-L146 | def decode(code, *, max_age):
"""decode(code, *, max_age)
Decodes the code from the registration link and returns a tuple consisting
of the verified email address and the payload which was passed through to
``get_confirmation_code``.
The maximum age in seconds of the link has to be specified as ``m... | [
"def",
"decode",
"(",
"code",
",",
"*",
",",
"max_age",
")",
":",
"try",
":",
"data",
"=",
"get_signer",
"(",
")",
".",
"unsign",
"(",
"code",
",",
"max_age",
"=",
"max_age",
")",
"except",
"signing",
".",
"SignatureExpired",
":",
"raise",
"ValidationE... | decode(code, *, max_age)
Decodes the code from the registration link and returns a tuple consisting
of the verified email address and the payload which was passed through to
``get_confirmation_code``.
The maximum age in seconds of the link has to be specified as ``max_age``.
This method raises ``V... | [
"decode",
"(",
"code",
"*",
"max_age",
")",
"Decodes",
"the",
"code",
"from",
"the",
"registration",
"link",
"and",
"returns",
"a",
"tuple",
"consisting",
"of",
"the",
"verified",
"email",
"address",
"and",
"the",
"payload",
"which",
"was",
"passed",
"throug... | python | train | 34.896552 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsAggShockModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsAggShockModel.py#L201-L239 | def simDeath(self):
'''
Randomly determine which consumers die, and distribute their wealth among the survivors.
This method only works if there is only one period in the cycle.
Parameters
----------
None
Returns
-------
who_dies : np.array(bool)... | [
"def",
"simDeath",
"(",
"self",
")",
":",
"# Divide agents into wealth groups, kill one random agent per wealth group",
"# order = np.argsort(self.aLvlNow)",
"# how_many_die = int(self.AgentCount*(1.0-self.LivPrb[0]))",
"# group_size = self.AgentCount/how_many_die # This shoul... | Randomly determine which consumers die, and distribute their wealth among the survivors.
This method only works if there is only one period in the cycle.
Parameters
----------
None
Returns
-------
who_dies : np.array(bool)
Boolean array of size Agent... | [
"Randomly",
"determine",
"which",
"consumers",
"die",
"and",
"distribute",
"their",
"wealth",
"among",
"the",
"survivors",
".",
"This",
"method",
"only",
"works",
"if",
"there",
"is",
"only",
"one",
"period",
"in",
"the",
"cycle",
"."
] | python | train | 43.666667 |
FutunnOpen/futuquant | futuquant/quote/quote_query.py | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/quote/quote_query.py#L235-L346 | def unpack_rsp(cls, rsp_pb):
"""Convert from PLS response to user response"""
ret_type = rsp_pb.retType
ret_msg = rsp_pb.retMsg
if ret_type != RET_OK:
return RET_ERROR, ret_msg, None
raw_snapshot_list = rsp_pb.s2c.snapshotList
snapshot_list = []
for... | [
"def",
"unpack_rsp",
"(",
"cls",
",",
"rsp_pb",
")",
":",
"ret_type",
"=",
"rsp_pb",
".",
"retType",
"ret_msg",
"=",
"rsp_pb",
".",
"retMsg",
"if",
"ret_type",
"!=",
"RET_OK",
":",
"return",
"RET_ERROR",
",",
"ret_msg",
",",
"None",
"raw_snapshot_list",
"=... | Convert from PLS response to user response | [
"Convert",
"from",
"PLS",
"response",
"to",
"user",
"response"
] | python | train | 51.455357 |
KarchinLab/probabilistic2020 | prob2020/python/indel.py | https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/prob2020/python/indel.py#L289-L301 | def get_frameshift_lengths(num_bins):
"""Simple function that returns the lengths for each frameshift category
if `num_bins` number of frameshift categories are requested.
"""
fs_len = []
i = 1
tmp_bins = 0
while(tmp_bins<num_bins):
if i%3:
fs_len.append(i)
tm... | [
"def",
"get_frameshift_lengths",
"(",
"num_bins",
")",
":",
"fs_len",
"=",
"[",
"]",
"i",
"=",
"1",
"tmp_bins",
"=",
"0",
"while",
"(",
"tmp_bins",
"<",
"num_bins",
")",
":",
"if",
"i",
"%",
"3",
":",
"fs_len",
".",
"append",
"(",
"i",
")",
"tmp_bi... | Simple function that returns the lengths for each frameshift category
if `num_bins` number of frameshift categories are requested. | [
"Simple",
"function",
"that",
"returns",
"the",
"lengths",
"for",
"each",
"frameshift",
"category",
"if",
"num_bins",
"number",
"of",
"frameshift",
"categories",
"are",
"requested",
"."
] | python | train | 27.076923 |
mozilla/build-mar | src/mardor/cli.py | https://github.com/mozilla/build-mar/blob/d8c3b3469e55654d31f430cb343fd89392196c4e/src/mardor/cli.py#L119-L150 | def do_verify(marfile, keyfiles=None):
"""Verify the MAR file."""
try:
with open(marfile, 'rb') as f:
with MarReader(f) as m:
# Check various parts of the mar file
# e.g. signature algorithms and additional block sections
errors = m.get_errors(... | [
"def",
"do_verify",
"(",
"marfile",
",",
"keyfiles",
"=",
"None",
")",
":",
"try",
":",
"with",
"open",
"(",
"marfile",
",",
"'rb'",
")",
"as",
"f",
":",
"with",
"MarReader",
"(",
"f",
")",
"as",
"m",
":",
"# Check various parts of the mar file",
"# e.g.... | Verify the MAR file. | [
"Verify",
"the",
"MAR",
"file",
"."
] | python | train | 35.15625 |
GNS3/gns3-server | gns3server/compute/vpcs/__init__.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/__init__.py#L41-L54 | def create_node(self, *args, **kwargs):
"""
Creates a new VPCS VM.
:returns: VPCSVM instance
"""
node = yield from super().create_node(*args, **kwargs)
self._free_mac_ids.setdefault(node.project.id, list(range(0, 255)))
try:
self._used_mac_ids[node.i... | [
"def",
"create_node",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"yield",
"from",
"super",
"(",
")",
".",
"create_node",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_free_mac_ids",
".",
"setdefa... | Creates a new VPCS VM.
:returns: VPCSVM instance | [
"Creates",
"a",
"new",
"VPCS",
"VM",
"."
] | python | train | 35.714286 |
DataBiosphere/toil | src/toil/provisioners/aws/awsProvisioner.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/aws/awsProvisioner.py#L394-L406 | def _waitForIP(cls, instance):
"""
Wait until the instances has a public IP address assigned to it.
:type instance: boto.ec2.instance.Instance
"""
logger.debug('Waiting for ip...')
while True:
time.sleep(a_short_time)
instance.update()
... | [
"def",
"_waitForIP",
"(",
"cls",
",",
"instance",
")",
":",
"logger",
".",
"debug",
"(",
"'Waiting for ip...'",
")",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"a_short_time",
")",
"instance",
".",
"update",
"(",
")",
"if",
"instance",
".",
"ip_add... | Wait until the instances has a public IP address assigned to it.
:type instance: boto.ec2.instance.Instance | [
"Wait",
"until",
"the",
"instances",
"has",
"a",
"public",
"IP",
"address",
"assigned",
"to",
"it",
"."
] | python | train | 35 |
hugapi/hug | hug/routing.py | https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L242-L246 | def add_response_headers(self, headers, **overrides):
"""Adds the specified response headers while keeping existing ones in-tact"""
response_headers = self.route.get('response_headers', {}).copy()
response_headers.update(headers)
return self.where(response_headers=response_headers, **ove... | [
"def",
"add_response_headers",
"(",
"self",
",",
"headers",
",",
"*",
"*",
"overrides",
")",
":",
"response_headers",
"=",
"self",
".",
"route",
".",
"get",
"(",
"'response_headers'",
",",
"{",
"}",
")",
".",
"copy",
"(",
")",
"response_headers",
".",
"u... | Adds the specified response headers while keeping existing ones in-tact | [
"Adds",
"the",
"specified",
"response",
"headers",
"while",
"keeping",
"existing",
"ones",
"in",
"-",
"tact"
] | python | train | 64.6 |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/biosignalsnotebooks/old/_factory.py | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/biosignalsnotebooks/old/_factory.py#L343-L383 | def _generate_footer(notebook_object, notebook_type):
"""
Internal function that is used for generation of the notebooks footer.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the header will be created.
notebook_type : str
... | [
"def",
"_generate_footer",
"(",
"notebook_object",
",",
"notebook_type",
")",
":",
"footer_aux",
"=",
"FOOTER",
"if",
"\"Main_Files\"",
"in",
"notebook_type",
":",
"footer_aux",
"=",
"footer_aux",
".",
"replace",
"(",
"\"../MainFiles/\"",
",",
"\"\"",
")",
"# ====... | Internal function that is used for generation of the notebooks footer.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the header will be created.
notebook_type : str
Notebook type: - "Main_Files_Signal_Samples"
... | [
"Internal",
"function",
"that",
"is",
"used",
"for",
"generation",
"of",
"the",
"notebooks",
"footer",
"."
] | python | train | 41.95122 |
mortada/fredapi | fredapi/fred.py | https://github.com/mortada/fredapi/blob/d3ca79efccb9525f2752a0d6da90e793e87c3fd8/fredapi/fred.py#L307-L349 | def __get_search_results(self, url, limit, order_by, sort_order, filter):
"""
helper function for getting search results up to specified limit on the number of results. The Fred HTTP API
truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data... | [
"def",
"__get_search_results",
"(",
"self",
",",
"url",
",",
"limit",
",",
"order_by",
",",
"sort_order",
",",
"filter",
")",
":",
"order_by_options",
"=",
"[",
"'search_rank'",
",",
"'series_id'",
",",
"'title'",
",",
"'units'",
",",
"'frequency'",
",",
"'s... | helper function for getting search results up to specified limit on the number of results. The Fred HTTP API
truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data. | [
"helper",
"function",
"for",
"getting",
"search",
"results",
"up",
"to",
"specified",
"limit",
"on",
"the",
"number",
"of",
"results",
".",
"The",
"Fred",
"HTTP",
"API",
"truncates",
"to",
"1000",
"results",
"per",
"request",
"so",
"this",
"may",
"issue",
... | python | train | 48.232558 |
mitsei/dlkit | dlkit/handcar/relationship/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/relationship/managers.py#L1304-L1328 | def get_family_search_session(self, proxy=None):
"""Gets the ``OsidSession`` associated with the family search service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.FamilySearchSession) - a
``FamilySearchSession``
raise: NullArgument - ``proxy`` ... | [
"def",
"get_family_search_session",
"(",
"self",
",",
"proxy",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"supports_family_search",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError... | Gets the ``OsidSession`` associated with the family search service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.FamilySearchSession) - a
``FamilySearchSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to comp... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"family",
"search",
"service",
"."
] | python | train | 40.28 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/work_item_tracking_process/work_item_tracking_process_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/work_item_tracking_process/work_item_tracking_process_client.py#L637-L648 | def create_new_process(self, create_request):
"""CreateNewProcess.
[Preview API] Creates a process.
:param :class:`<CreateProcessModel> <azure.devops.v5_0.work_item_tracking_process.models.CreateProcessModel>` create_request: CreateProcessModel.
:rtype: :class:`<ProcessInfo> <azure.devop... | [
"def",
"create_new_process",
"(",
"self",
",",
"create_request",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"create_request",
",",
"'CreateProcessModel'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'POST'"... | CreateNewProcess.
[Preview API] Creates a process.
:param :class:`<CreateProcessModel> <azure.devops.v5_0.work_item_tracking_process.models.CreateProcessModel>` create_request: CreateProcessModel.
:rtype: :class:`<ProcessInfo> <azure.devops.v5_0.work_item_tracking_process.models.ProcessInfo>` | [
"CreateNewProcess",
".",
"[",
"Preview",
"API",
"]",
"Creates",
"a",
"process",
".",
":",
"param",
":",
"class",
":",
"<CreateProcessModel",
">",
"<azure",
".",
"devops",
".",
"v5_0",
".",
"work_item_tracking_process",
".",
"models",
".",
"CreateProcessModel",
... | python | train | 62 |
ewels/MultiQC | multiqc/modules/quast/quast.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/quast/quast.py#L293-L341 | def quast_predicted_genes_barplot(self):
"""
Make a bar plot showing the number and length of predicted genes
for each assembly
"""
# Prep the data
# extract the ranges given to quast with "--gene-thresholds"
prefix = '# predicted genes (>= '
suffix = ' b... | [
"def",
"quast_predicted_genes_barplot",
"(",
"self",
")",
":",
"# Prep the data",
"# extract the ranges given to quast with \"--gene-thresholds\"",
"prefix",
"=",
"'# predicted genes (>= '",
"suffix",
"=",
"' bp)'",
"all_thresholds",
"=",
"sorted",
"(",
"list",
"(",
"set",
... | Make a bar plot showing the number and length of predicted genes
for each assembly | [
"Make",
"a",
"bar",
"plot",
"showing",
"the",
"number",
"and",
"length",
"of",
"predicted",
"genes",
"for",
"each",
"assembly"
] | python | train | 39.857143 |
Unidata/MetPy | metpy/calc/basic.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/basic.py#L431-L468 | def geopotential_to_height(geopot):
r"""Compute height from a given geopotential.
Parameters
----------
geopotential : `pint.Quantity`
Geopotential (array_like)
Returns
-------
`pint.Quantity`
The corresponding height value(s)
Examples
--------
>>> from metpy.c... | [
"def",
"geopotential_to_height",
"(",
"geopot",
")",
":",
"# Calculate geopotential",
"height",
"=",
"(",
"(",
"(",
"1",
"/",
"mpconsts",
".",
"Re",
")",
"-",
"(",
"geopot",
"/",
"(",
"mpconsts",
".",
"G",
"*",
"mpconsts",
".",
"me",
")",
")",
")",
"... | r"""Compute height from a given geopotential.
Parameters
----------
geopotential : `pint.Quantity`
Geopotential (array_like)
Returns
-------
`pint.Quantity`
The corresponding height value(s)
Examples
--------
>>> from metpy.constants import g, G, me, Re
>>> imp... | [
"r",
"Compute",
"height",
"from",
"a",
"given",
"geopotential",
"."
] | python | train | 30.868421 |
jsfenfen/990-xml-reader | irs_reader/filing.py | https://github.com/jsfenfen/990-xml-reader/blob/00020529b789081329a31a2e30b5ee729ce7596a/irs_reader/filing.py#L53-L68 | def _download(self, force_overwrite=False, verbose=False):
"""
Download the file if it's not already there.
We shouldn't *need* to overwrite; the xml is not supposed to update.
"""
if not force_overwrite:
# If the file is already there, we're done
if os.pa... | [
"def",
"_download",
"(",
"self",
",",
"force_overwrite",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"not",
"force_overwrite",
":",
"# If the file is already there, we're done",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"filepat... | Download the file if it's not already there.
We shouldn't *need* to overwrite; the xml is not supposed to update. | [
"Download",
"the",
"file",
"if",
"it",
"s",
"not",
"already",
"there",
".",
"We",
"shouldn",
"t",
"*",
"need",
"*",
"to",
"overwrite",
";",
"the",
"xml",
"is",
"not",
"supposed",
"to",
"update",
"."
] | python | train | 39.4375 |
wandb/client | wandb/fastai/__init__.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/fastai/__init__.py#L128-L136 | def on_train_end(self, **kwargs):
"Load the best model."
if self.save_model:
# Adapted from fast.ai "SaveModelCallback"
if self.model_path.is_file():
with self.model_path.open('rb') as model_file:
self.learn.load(model_file, purge=False)
... | [
"def",
"on_train_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"save_model",
":",
"# Adapted from fast.ai \"SaveModelCallback\"",
"if",
"self",
".",
"model_path",
".",
"is_file",
"(",
")",
":",
"with",
"self",
".",
"model_path",
".... | Load the best model. | [
"Load",
"the",
"best",
"model",
"."
] | python | train | 42.555556 |
evhub/coconut | coconut/requirements.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/requirements.py#L157-L176 | def print_new_versions(strict=False):
"""Prints new requirement versions."""
new_updates = []
same_updates = []
for req in everything_in(all_reqs):
new_versions = []
same_versions = []
for ver_str in all_versions(req):
if newer(ver_str_to_tuple(ver_str), min_versions[... | [
"def",
"print_new_versions",
"(",
"strict",
"=",
"False",
")",
":",
"new_updates",
"=",
"[",
"]",
"same_updates",
"=",
"[",
"]",
"for",
"req",
"in",
"everything_in",
"(",
"all_reqs",
")",
":",
"new_versions",
"=",
"[",
"]",
"same_versions",
"=",
"[",
"]"... | Prints new requirement versions. | [
"Prints",
"new",
"requirement",
"versions",
"."
] | python | train | 42.7 |
PyGithub/PyGithub | github/NamedUser.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/NamedUser.py#L514-L538 | def get_repos(self, type=github.GithubObject.NotSet, sort=github.GithubObject.NotSet,
direction=github.GithubObject.NotSet):
"""
:calls: `GET /users/:user/repos <http://developer.github.com/v3/repos>`_
:param type: string
:param sort: string
:param direction: st... | [
"def",
"get_repos",
"(",
"self",
",",
"type",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"sort",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"direction",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":",
"assert",
"typ... | :calls: `GET /users/:user/repos <http://developer.github.com/v3/repos>`_
:param type: string
:param sort: string
:param direction: string
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository` | [
":",
"calls",
":",
"GET",
"/",
"users",
"/",
":",
"user",
"/",
"repos",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"repos",
">",
"_",
":",
"param",
"type",
":",
"string",
":",
"param",
"sort",
":",
"string",
":",
... | python | train | 48.88 |
dbcli/athenacli | athenacli/packages/parseutils.py | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/parseutils.py#L18-L60 | def last_word(text, include='alphanum_underscore'):
"""
Find the last word in a sentence.
>>> last_word('abc')
'abc'
>>> last_word(' abc')
'abc'
>>> last_word('')
''
>>> last_word(' ')
''
>>> last_word('abc ')
''
>>> last_word('abc def')
'def'
>>> last_word('a... | [
"def",
"last_word",
"(",
"text",
",",
"include",
"=",
"'alphanum_underscore'",
")",
":",
"if",
"not",
"text",
":",
"# Empty string",
"return",
"''",
"if",
"text",
"[",
"-",
"1",
"]",
".",
"isspace",
"(",
")",
":",
"return",
"''",
"else",
":",
"regex",
... | Find the last word in a sentence.
>>> last_word('abc')
'abc'
>>> last_word(' abc')
'abc'
>>> last_word('')
''
>>> last_word(' ')
''
>>> last_word('abc ')
''
>>> last_word('abc def')
'def'
>>> last_word('abc def ')
''
>>> last_word('abc def;')
''
>>> la... | [
"Find",
"the",
"last",
"word",
"in",
"a",
"sentence",
".",
">>>",
"last_word",
"(",
"abc",
")",
"abc",
">>>",
"last_word",
"(",
"abc",
")",
"abc",
">>>",
"last_word",
"(",
")",
">>>",
"last_word",
"(",
")",
">>>",
"last_word",
"(",
"abc",
")",
">>>",... | python | train | 21.930233 |
python-useful-helpers/threaded | threaded/_threadpooled.py | https://github.com/python-useful-helpers/threaded/blob/c1aa5a631ab3e2904b915ed6c6a8be03a9673a1a/threaded/_threadpooled.py#L98-L105 | def loop_getter(
self
) -> typing.Optional[typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]]:
"""Loop getter.
:rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]
"""
return self.__loop... | [
"def",
"loop_getter",
"(",
"self",
")",
"->",
"typing",
".",
"Optional",
"[",
"typing",
".",
"Union",
"[",
"typing",
".",
"Callable",
"[",
"...",
",",
"asyncio",
".",
"AbstractEventLoop",
"]",
",",
"asyncio",
".",
"AbstractEventLoop",
"]",
"]",
":",
"ret... | Loop getter.
:rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] | [
"Loop",
"getter",
"."
] | python | train | 40 |
noahbenson/neuropythy | neuropythy/commands/atlas.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/commands/atlas.py#L58-L116 | def calc_atlases(worklog, atlas_subject_id='fsaverage'):
'''
cacl_atlases finds all available atlases in the possible subject directories of the given atlas
subject.
In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer
curv/morph-data files) named as '<he... | [
"def",
"calc_atlases",
"(",
"worklog",
",",
"atlas_subject_id",
"=",
"'fsaverage'",
")",
":",
"try",
":",
"sub",
"=",
"freesurfer_subject",
"(",
"atlas_subject_id",
")",
"except",
"Exception",
":",
"sub",
"=",
"None",
"if",
"sub",
"is",
"None",
":",
"try",
... | cacl_atlases finds all available atlases in the possible subject directories of the given atlas
subject.
In order to be a template, it must either be a collection of files (either mgh/mgz or FreeSurfer
curv/morph-data files) named as '<hemi>.<template>_<quantity><ending>' such as the files
'lh.wang2015... | [
"cacl_atlases",
"finds",
"all",
"available",
"atlases",
"in",
"the",
"possible",
"subject",
"directories",
"of",
"the",
"given",
"atlas",
"subject",
"."
] | python | train | 54.288136 |
dingusdk/PythonIhcSdk | ihcsdk/ihccontroller.py | https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihccontroller.py#L54-L59 | def set_runtime_value_bool(self, ihcid: int, value: bool) -> bool:
""" Set bool runtime value with re-authenticate if needed"""
if self.client.set_runtime_value_bool(ihcid, value):
return True
self.re_authenticate()
return self.client.set_runtime_value_bool(ihcid, value) | [
"def",
"set_runtime_value_bool",
"(",
"self",
",",
"ihcid",
":",
"int",
",",
"value",
":",
"bool",
")",
"->",
"bool",
":",
"if",
"self",
".",
"client",
".",
"set_runtime_value_bool",
"(",
"ihcid",
",",
"value",
")",
":",
"return",
"True",
"self",
".",
... | Set bool runtime value with re-authenticate if needed | [
"Set",
"bool",
"runtime",
"value",
"with",
"re",
"-",
"authenticate",
"if",
"needed"
] | python | train | 51.666667 |
apache/spark | python/pyspark/cloudpickle.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/cloudpickle.py#L540-L596 | def save_function_tuple(self, func):
""" Pickles an actual func object.
A func comprises: code, globals, defaults, closure, and dict. We
extract and save these, injecting reducing functions at certain points
to recreate the func object. Keep in mind that some of these pieces
... | [
"def",
"save_function_tuple",
"(",
"self",
",",
"func",
")",
":",
"if",
"is_tornado_coroutine",
"(",
"func",
")",
":",
"self",
".",
"save_reduce",
"(",
"_rebuild_tornado_coroutine",
",",
"(",
"func",
".",
"__wrapped__",
",",
")",
",",
"obj",
"=",
"func",
"... | Pickles an actual func object.
A func comprises: code, globals, defaults, closure, and dict. We
extract and save these, injecting reducing functions at certain points
to recreate the func object. Keep in mind that some of these pieces
can contain a ref to the func itself. Thus, a nai... | [
"Pickles",
"an",
"actual",
"func",
"object",
"."
] | python | train | 38.175439 |
PlaidWeb/Publ | publ/entry.py | https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/entry.py#L312-L316 | def _get_summary(self, text, **kwargs):
""" Render out just the summary """
card = cards.extract_card(text, kwargs, self.search_path)
return flask.Markup((card.description or '').strip()) | [
"def",
"_get_summary",
"(",
"self",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"card",
"=",
"cards",
".",
"extract_card",
"(",
"text",
",",
"kwargs",
",",
"self",
".",
"search_path",
")",
"return",
"flask",
".",
"Markup",
"(",
"(",
"card",
".",
... | Render out just the summary | [
"Render",
"out",
"just",
"the",
"summary"
] | python | train | 41.6 |
astropy/photutils | photutils/psf/epsf_stars.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf_stars.py#L149-L156 | def bbox(self):
"""
The minimal `~photutils.aperture.BoundingBox` for the cutout
region with respect to the original (large) image.
"""
return BoundingBox(self.slices[1].start, self.slices[1].stop,
self.slices[0].start, self.slices[0].stop) | [
"def",
"bbox",
"(",
"self",
")",
":",
"return",
"BoundingBox",
"(",
"self",
".",
"slices",
"[",
"1",
"]",
".",
"start",
",",
"self",
".",
"slices",
"[",
"1",
"]",
".",
"stop",
",",
"self",
".",
"slices",
"[",
"0",
"]",
".",
"start",
",",
"self"... | The minimal `~photutils.aperture.BoundingBox` for the cutout
region with respect to the original (large) image. | [
"The",
"minimal",
"~photutils",
".",
"aperture",
".",
"BoundingBox",
"for",
"the",
"cutout",
"region",
"with",
"respect",
"to",
"the",
"original",
"(",
"large",
")",
"image",
"."
] | python | train | 37.625 |
benhoff/pluginmanager | pluginmanager/plugin_manager.py | https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/plugin_manager.py#L208-L214 | def add_blacklisted_plugins(self, plugins):
"""
add blacklisted plugins.
`plugins` may be a single object or iterable.
"""
plugins = util.return_list(plugins)
self.blacklisted_plugins.extend(plugins) | [
"def",
"add_blacklisted_plugins",
"(",
"self",
",",
"plugins",
")",
":",
"plugins",
"=",
"util",
".",
"return_list",
"(",
"plugins",
")",
"self",
".",
"blacklisted_plugins",
".",
"extend",
"(",
"plugins",
")"
] | add blacklisted plugins.
`plugins` may be a single object or iterable. | [
"add",
"blacklisted",
"plugins",
".",
"plugins",
"may",
"be",
"a",
"single",
"object",
"or",
"iterable",
"."
] | python | train | 34.428571 |
Karaage-Cluster/karaage | karaage/plugins/kgapplications/views/states.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/plugins/kgapplications/views/states.py#L381-L389 | def add_step(self, step, step_id):
""" Add a step to the list. The first step added becomes the initial
step. """
assert step_id not in self._steps
assert step_id not in self._order
assert isinstance(step, Step)
self._steps[step_id] = step
self._order.append(step... | [
"def",
"add_step",
"(",
"self",
",",
"step",
",",
"step_id",
")",
":",
"assert",
"step_id",
"not",
"in",
"self",
".",
"_steps",
"assert",
"step_id",
"not",
"in",
"self",
".",
"_order",
"assert",
"isinstance",
"(",
"step",
",",
"Step",
")",
"self",
".",... | Add a step to the list. The first step added becomes the initial
step. | [
"Add",
"a",
"step",
"to",
"the",
"list",
".",
"The",
"first",
"step",
"added",
"becomes",
"the",
"initial",
"step",
"."
] | python | train | 35.111111 |
rigetti/grove | grove/tomography/utils.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/tomography/utils.py#L222-L241 | def estimate_assignment_probs(bitstring_prep_histograms):
"""
Compute the estimated assignment probability matrix for a sequence of single shot histograms
obtained by running the programs generated by `basis_state_preps()`.
bitstring_prep_histograms[i,j] = #number of measured outcomes j when runnin... | [
"def",
"estimate_assignment_probs",
"(",
"bitstring_prep_histograms",
")",
":",
"p",
"=",
"np",
".",
"array",
"(",
"bitstring_prep_histograms",
",",
"dtype",
"=",
"float",
")",
".",
"T",
"p",
"/=",
"p",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"[",
"np",
... | Compute the estimated assignment probability matrix for a sequence of single shot histograms
obtained by running the programs generated by `basis_state_preps()`.
bitstring_prep_histograms[i,j] = #number of measured outcomes j when running program i
The assignment probability is obtained by transposing... | [
"Compute",
"the",
"estimated",
"assignment",
"probability",
"matrix",
"for",
"a",
"sequence",
"of",
"single",
"shot",
"histograms",
"obtained",
"by",
"running",
"the",
"programs",
"generated",
"by",
"basis_state_preps",
"()",
"."
] | python | train | 49.5 |
log2timeline/dfvfs | dfvfs/resolver/context.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/resolver/context.py#L69-L85 | def ForceRemoveFileObject(self, path_spec):
"""Forces the removal of a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file-like object was cached.
"""
cache_value = self._file_object_cache.GetCacheValue(path_sp... | [
"def",
"ForceRemoveFileObject",
"(",
"self",
",",
"path_spec",
")",
":",
"cache_value",
"=",
"self",
".",
"_file_object_cache",
".",
"GetCacheValue",
"(",
"path_spec",
".",
"comparable",
")",
"if",
"not",
"cache_value",
":",
"return",
"False",
"while",
"not",
... | Forces the removal of a file-like object based on a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
bool: True if the file-like object was cached. | [
"Forces",
"the",
"removal",
"of",
"a",
"file",
"-",
"like",
"object",
"based",
"on",
"a",
"path",
"specification",
"."
] | python | train | 27.058824 |
jbfavre/python-protobix | protobix/senderprotocol.py | https://github.com/jbfavre/python-protobix/blob/96b7095a9c2485c9e1bdba098b7d82b93f91acb1/protobix/senderprotocol.py#L167-L197 | def _handle_response(self, zbx_answer):
"""
Analyze Zabbix Server response
Returns a list with number of:
* processed items
* failed items
* total items
* time spent
:zbx_answer: Zabbix server response as string
"""
zbx_answer = json.loads... | [
"def",
"_handle_response",
"(",
"self",
",",
"zbx_answer",
")",
":",
"zbx_answer",
"=",
"json",
".",
"loads",
"(",
"zbx_answer",
")",
"if",
"self",
".",
"_logger",
":",
"# pragma: no cover",
"self",
".",
"_logger",
".",
"info",
"(",
"\"Anaylizing Zabbix Server... | Analyze Zabbix Server response
Returns a list with number of:
* processed items
* failed items
* total items
* time spent
:zbx_answer: Zabbix server response as string | [
"Analyze",
"Zabbix",
"Server",
"response",
"Returns",
"a",
"list",
"with",
"number",
"of",
":",
"*",
"processed",
"items",
"*",
"failed",
"items",
"*",
"total",
"items",
"*",
"time",
"spent"
] | python | train | 34.387097 |
StackStorm/pybind | pybind/slxos/v17s_1_02/interface/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/interface/__init__.py#L108-L134 | def _set_ethernet(self, v, load=False):
"""
Setter method for ethernet, mapped from YANG variable /interface/ethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ethernet is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_ethernet",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | Setter method for ethernet, mapped from YANG variable /interface/ethernet (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ethernet is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_ethernet() direct... | [
"Setter",
"method",
"for",
"ethernet",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"ethernet",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file"... | python | train | 142.518519 |
expfactory/expfactory | expfactory/utils.py | https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/utils.py#L94-L108 | def copy_directory(src, dest, force=False):
''' Copy an entire directory recursively
'''
if os.path.exists(dest) and force is True:
shutil.rmtree(dest)
try:
shutil.copytree(src, dest)
except OSError as e:
# If the error was caused because the source wasn't a directory
... | [
"def",
"copy_directory",
"(",
"src",
",",
"dest",
",",
"force",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
"and",
"force",
"is",
"True",
":",
"shutil",
".",
"rmtree",
"(",
"dest",
")",
"try",
":",
"shutil",
... | Copy an entire directory recursively | [
"Copy",
"an",
"entire",
"directory",
"recursively"
] | python | train | 31.333333 |
python-security/pyt | pyt/vulnerabilities/vulnerabilities.py | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/vulnerabilities/vulnerabilities.py#L30-L65 | def identify_triggers(
cfg,
sources,
sinks,
lattice,
nosec_lines
):
"""Identify sources, sinks and sanitisers in a CFG.
Args:
cfg(CFG): CFG to find sources, sinks and sanitisers in.
sources(tuple): list of sources, a source is a (source, sanitiser) tuple.
sinks(tuple... | [
"def",
"identify_triggers",
"(",
"cfg",
",",
"sources",
",",
"sinks",
",",
"lattice",
",",
"nosec_lines",
")",
":",
"assignment_nodes",
"=",
"filter_cfg_nodes",
"(",
"cfg",
",",
"AssignmentNode",
")",
"tainted_nodes",
"=",
"filter_cfg_nodes",
"(",
"cfg",
",",
... | Identify sources, sinks and sanitisers in a CFG.
Args:
cfg(CFG): CFG to find sources, sinks and sanitisers in.
sources(tuple): list of sources, a source is a (source, sanitiser) tuple.
sinks(tuple): list of sources, a sink is a (sink, sanitiser) tuple.
nosec_lines(set): lines with #... | [
"Identify",
"sources",
"sinks",
"and",
"sanitisers",
"in",
"a",
"CFG",
"."
] | python | train | 33.333333 |
toumorokoshi/sprinter | sprinter/formula/ssh.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/formula/ssh.py#L83-L101 | def __install_ssh_config(self, config):
"""
Install the ssh configuration
"""
if not config.is_affirmative('use_global_ssh', default="no"):
ssh_config_injection = self._build_ssh_config(config)
if not os.path.exists(ssh_config_path):
if self.inje... | [
"def",
"__install_ssh_config",
"(",
"self",
",",
"config",
")",
":",
"if",
"not",
"config",
".",
"is_affirmative",
"(",
"'use_global_ssh'",
",",
"default",
"=",
"\"no\"",
")",
":",
"ssh_config_injection",
"=",
"self",
".",
"_build_ssh_config",
"(",
"config",
"... | Install the ssh configuration | [
"Install",
"the",
"ssh",
"configuration"
] | python | train | 40.052632 |
CivicSpleen/ambry | ambry/library/search_backends/base.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/base.py#L705-L832 | def parse(self, s, term_join=None):
""" Parses search term to
Args:
s (str): string with search term.
or_join (callable): function to join 'OR' terms.
Returns:
dict: all of the terms grouped by marker. Key is a marker, value is a term.
Example:
... | [
"def",
"parse",
"(",
"self",
",",
"s",
",",
"term_join",
"=",
"None",
")",
":",
"if",
"not",
"term_join",
":",
"term_join",
"=",
"lambda",
"x",
":",
"'('",
"+",
"' OR '",
".",
"join",
"(",
"x",
")",
"+",
"')'",
"toks",
"=",
"self",
".",
"scan",
... | Parses search term to
Args:
s (str): string with search term.
or_join (callable): function to join 'OR' terms.
Returns:
dict: all of the terms grouped by marker. Key is a marker, value is a term.
Example:
>>> SearchTermParser().parse('table2 fro... | [
"Parses",
"search",
"term",
"to"
] | python | train | 30.75 |
praekeltfoundation/seaworthy | seaworthy/definitions.py | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/definitions.py#L400-L410 | def get_logs(self, stdout=True, stderr=True, timestamps=False, tail='all',
since=None):
"""
Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that.
"""
return self.inner().logs(
stdout=stdout, stderr=stde... | [
"def",
"get_logs",
"(",
"self",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"timestamps",
"=",
"False",
",",
"tail",
"=",
"'all'",
",",
"since",
"=",
"None",
")",
":",
"return",
"self",
".",
"inner",
"(",
")",
".",
"logs",
"(",
"... | Get container logs.
This method does not support streaming, use :meth:`stream_logs` for
that. | [
"Get",
"container",
"logs",
"."
] | python | train | 33.818182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.