repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
google/neuroglancer | python/neuroglancer/server.py | https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/server.py#L245-L258 | def stop():
"""Stop the server, invalidating any viewer URLs.
This allows any previously-referenced data arrays to be garbage collected if there are no other
references to them.
"""
global global_server
if global_server is not None:
ioloop = global_server.ioloop
def stop_ioloop(... | [
"def",
"stop",
"(",
")",
":",
"global",
"global_server",
"if",
"global_server",
"is",
"not",
"None",
":",
"ioloop",
"=",
"global_server",
".",
"ioloop",
"def",
"stop_ioloop",
"(",
")",
":",
"ioloop",
".",
"stop",
"(",
")",
"ioloop",
".",
"close",
"(",
... | Stop the server, invalidating any viewer URLs.
This allows any previously-referenced data arrays to be garbage collected if there are no other
references to them. | [
"Stop",
"the",
"server",
"invalidating",
"any",
"viewer",
"URLs",
"."
] | python | train |
robotools/fontParts | Lib/fontParts/base/normalizers.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/normalizers.py#L752-L777 | def normalizeIdentifier(value):
"""
Normalizes identifier.
* **value** must be an :ref:`type-string` or `None`.
* **value** must not be longer than 100 characters.
* **value** must not contain a character out the range of 0x20 - 0x7E.
* Returned value is an unencoded ``unicode`` string.
"""... | [
"def",
"normalizeIdentifier",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"value",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"Identifiers must be strings, not %s.\"",
"%",
"type",
... | Normalizes identifier.
* **value** must be an :ref:`type-string` or `None`.
* **value** must not be longer than 100 characters.
* **value** must not contain a character out the range of 0x20 - 0x7E.
* Returned value is an unencoded ``unicode`` string. | [
"Normalizes",
"identifier",
"."
] | python | train |
StackStorm/pybind | pybind/nos/v6_0_2f/interface/fc_port/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/interface/fc_port/__init__.py#L182-L203 | def _set_fill_word(self, v, load=False):
"""
Setter method for fill_word, mapped from YANG variable /interface/fc_port/fill_word (fc-fillword-cfg-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fill_word is considered as a private
method. Backends looking to po... | [
"def",
"_set_fill_word",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base... | Setter method for fill_word, mapped from YANG variable /interface/fc_port/fill_word (fc-fillword-cfg-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fill_word is considered as a private
method. Backends looking to populate this variable should
do so via calling thi... | [
"Setter",
"method",
"for",
"fill_word",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"fc_port",
"/",
"fill_word",
"(",
"fc",
"-",
"fillword",
"-",
"cfg",
"-",
"type",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config"... | python | train |
jingw/pyhdfs | pyhdfs.py | https://github.com/jingw/pyhdfs/blob/b382b34f7cb28b41559f5be73102beb1732cd933/pyhdfs.py#L496-L507 | def create_symlink(self, link, destination, **kwargs):
"""Create a symbolic link at ``link`` pointing to ``destination``.
:param link: the path to be created that points to target
:param destination: the target of the symbolic link
:param createParent: If the parent directories do not e... | [
"def",
"create_symlink",
"(",
"self",
",",
"link",
",",
"destination",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"_put",
"(",
"link",
",",
"'CREATESYMLINK'",
",",
"destination",
"=",
"destination",
",",
"*",
"*",
"kwargs",
")",
"... | Create a symbolic link at ``link`` pointing to ``destination``.
:param link: the path to be created that points to target
:param destination: the target of the symbolic link
:param createParent: If the parent directories do not exist, should they be created?
:type createParent: bool
... | [
"Create",
"a",
"symbolic",
"link",
"at",
"link",
"pointing",
"to",
"destination",
"."
] | python | train |
Opentrons/opentrons | update-server/otupdate/balena/control.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/balena/control.py#L35-L55 | async def _resin_supervisor_restart():
""" Execute a container restart by requesting it from the supervisor.
Note that failures here are returned but most likely will not be
sent back to the caller, since this is run in a separate workthread.
If the system is not responding, look for these log messages... | [
"async",
"def",
"_resin_supervisor_restart",
"(",
")",
":",
"supervisor",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'RESIN_SUPERVISOR_ADDRESS'",
",",
"'http://127.0.0.1:48484'",
")",
"restart_url",
"=",
"supervisor",
"+",
"'/v1/restart'",
"api",
"=",
"os",
".",... | Execute a container restart by requesting it from the supervisor.
Note that failures here are returned but most likely will not be
sent back to the caller, since this is run in a separate workthread.
If the system is not responding, look for these log messages. | [
"Execute",
"a",
"container",
"restart",
"by",
"requesting",
"it",
"from",
"the",
"supervisor",
"."
] | python | train |
deontologician/restnavigator | restnavigator/halnav.py | https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L406-L444 | def _recursively_embed(self, doc, update_state=True):
'''Crafts a navigator from a hal-json embedded document'''
self_link = None
self_uri = utils.getpath(doc, '_links.self.href')
if self_uri is not None:
uri = urlparse.urljoin(self.uri, self_uri)
self_link = Link... | [
"def",
"_recursively_embed",
"(",
"self",
",",
"doc",
",",
"update_state",
"=",
"True",
")",
":",
"self_link",
"=",
"None",
"self_uri",
"=",
"utils",
".",
"getpath",
"(",
"doc",
",",
"'_links.self.href'",
")",
"if",
"self_uri",
"is",
"not",
"None",
":",
... | Crafts a navigator from a hal-json embedded document | [
"Crafts",
"a",
"navigator",
"from",
"a",
"hal",
"-",
"json",
"embedded",
"document"
] | python | train |
grahambell/pymoc | lib/pymoc/util/tool.py | https://github.com/grahambell/pymoc/blob/0e2e57ce07ff3de6ac024627c1fb6ad30c2fde48/lib/pymoc/util/tool.py#L121-L133 | def read_moc(self, filename):
"""Read a file into the current running MOC object.
If the running MOC object has not yet been created, then
it is created by reading the file, which will import the
MOC metadata. Otherwise the metadata are not imported.
"""
if self.moc is... | [
"def",
"read_moc",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"moc",
"is",
"None",
":",
"self",
".",
"moc",
"=",
"MOC",
"(",
"filename",
"=",
"filename",
")",
"else",
":",
"self",
".",
"moc",
".",
"read",
"(",
"filename",
")"
] | Read a file into the current running MOC object.
If the running MOC object has not yet been created, then
it is created by reading the file, which will import the
MOC metadata. Otherwise the metadata are not imported. | [
"Read",
"a",
"file",
"into",
"the",
"current",
"running",
"MOC",
"object",
"."
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/dtype.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dtype.py#L385-L398 | def decodeElem(self, bytes, index, raw=False):
"""Decodes a single element at array[index] from a sequence bytes
that contain data for the entire array.
"""
self._assertIndex(index)
start = index * self.type.nbytes
stop = start + self.type.nbytes
if stop > len(b... | [
"def",
"decodeElem",
"(",
"self",
",",
"bytes",
",",
"index",
",",
"raw",
"=",
"False",
")",
":",
"self",
".",
"_assertIndex",
"(",
"index",
")",
"start",
"=",
"index",
"*",
"self",
".",
"type",
".",
"nbytes",
"stop",
"=",
"start",
"+",
"self",
"."... | Decodes a single element at array[index] from a sequence bytes
that contain data for the entire array. | [
"Decodes",
"a",
"single",
"element",
"at",
"array",
"[",
"index",
"]",
"from",
"a",
"sequence",
"bytes",
"that",
"contain",
"data",
"for",
"the",
"entire",
"array",
"."
] | python | train |
h2oai/h2o-3 | h2o-py/h2o/model/clustering.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/model/clustering.py#L9-L27 | def size(self, train=False, valid=False, xval=False):
"""
Get the sizes of each cluster.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where
the keys are "train", "valid", and "xval... | [
"def",
"size",
"(",
"self",
",",
"train",
"=",
"False",
",",
"valid",
"=",
"False",
",",
"xval",
"=",
"False",
")",
":",
"tm",
"=",
"ModelBase",
".",
"_get_metrics",
"(",
"self",
",",
"train",
",",
"valid",
",",
"xval",
")",
"m",
"=",
"{",
"}",
... | Get the sizes of each cluster.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where
the keys are "train", "valid", and "xval".
:param bool train: If True, return the cluster sizes for the t... | [
"Get",
"the",
"sizes",
"of",
"each",
"cluster",
"."
] | python | test |
saltstack/salt | salt/modules/solr.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solr.py#L284-L310 | def _replication_request(command, host=None, core_name=None, params=None):
'''
PRIVATE METHOD
Performs the requested replication command and returns a dictionary with
success, errors and data as keys. The data object will contain the JSON
response.
command : str
The replication command ... | [
"def",
"_replication_request",
"(",
"command",
",",
"host",
"=",
"None",
",",
"core_name",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"[",
"]",
"if",
"params",
"is",
"None",
"else",
"params",
"extra",
"=",
"[",
"\"command={0}\"",
... | PRIVATE METHOD
Performs the requested replication command and returns a dictionary with
success, errors and data as keys. The data object will contain the JSON
response.
command : str
The replication command to execute.
host : str (None)
The solr host to query. __opts__['host'] is d... | [
"PRIVATE",
"METHOD",
"Performs",
"the",
"requested",
"replication",
"command",
"and",
"returns",
"a",
"dictionary",
"with",
"success",
"errors",
"and",
"data",
"as",
"keys",
".",
"The",
"data",
"object",
"will",
"contain",
"the",
"JSON",
"response",
"."
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L847-L851 | def notifications_get(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /notifications/get API method.
"""
return DXHTTPRequest('/notifications/get', input_params, always_retry=always_retry, **kwargs) | [
"def",
"notifications_get",
"(",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/notifications/get'",
",",
"input_params",
",",
"always_retry",
"=",
"always_retry",
",",
"*"... | Invokes the /notifications/get API method. | [
"Invokes",
"the",
"/",
"notifications",
"/",
"get",
"API",
"method",
"."
] | python | train |
boundlessgeo/gsconfig | src/geoserver/resource.py | https://github.com/boundlessgeo/gsconfig/blob/532f561f32b91ea8debea0573c503dd20988bf40/src/geoserver/resource.py#L20-L28 | def md_link(node):
"""Extract a metadata link tuple from an xml node"""
mimetype = node.find("type")
mdtype = node.find("metadataType")
content = node.find("content")
if None in [mimetype, mdtype, content]:
return None
else:
return (mimetype.text, mdtype.text, content.text) | [
"def",
"md_link",
"(",
"node",
")",
":",
"mimetype",
"=",
"node",
".",
"find",
"(",
"\"type\"",
")",
"mdtype",
"=",
"node",
".",
"find",
"(",
"\"metadataType\"",
")",
"content",
"=",
"node",
".",
"find",
"(",
"\"content\"",
")",
"if",
"None",
"in",
"... | Extract a metadata link tuple from an xml node | [
"Extract",
"a",
"metadata",
"link",
"tuple",
"from",
"an",
"xml",
"node"
] | python | valid |
pyQode/pyqode.cobol | pyqode/cobol/api/parsers/names.py | https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/api/parsers/names.py#L55-L69 | def find(self, name):
"""
Finds a possible child whose name match the name parameter.
:param name: name of the child node to look up
:type name: str
:return: DocumentNode or None
"""
for c in self.children:
if c.name == name:
return c... | [
"def",
"find",
"(",
"self",
",",
"name",
")",
":",
"for",
"c",
"in",
"self",
".",
"children",
":",
"if",
"c",
".",
"name",
"==",
"name",
":",
"return",
"c",
"result",
"=",
"c",
".",
"find",
"(",
"name",
")",
"if",
"result",
":",
"return",
"resu... | Finds a possible child whose name match the name parameter.
:param name: name of the child node to look up
:type name: str
:return: DocumentNode or None | [
"Finds",
"a",
"possible",
"child",
"whose",
"name",
"match",
"the",
"name",
"parameter",
"."
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L13571-L13588 | def get_medium_attachments_of_controller(self, name):
"""Returns an array of medium attachments which are attached to the
the controller with the given name.
in name of type str
return medium_attachments of type :class:`IMediumAttachment`
raises :class:`VBoxErrorObjectNotFound... | [
"def",
"get_medium_attachments_of_controller",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type basestring\"",
")",
"medium_attachments",
"=",
"s... | Returns an array of medium attachments which are attached to the
the controller with the given name.
in name of type str
return medium_attachments of type :class:`IMediumAttachment`
raises :class:`VBoxErrorObjectNotFound`
A storage controller with given name doesn't exist. | [
"Returns",
"an",
"array",
"of",
"medium",
"attachments",
"which",
"are",
"attached",
"to",
"the",
"the",
"controller",
"with",
"the",
"given",
"name",
"."
] | python | train |
bastikr/boolean.py | boolean/boolean.py | https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L646-L698 | def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
"""
# track the new list of unchanged args or rep... | [
"def",
"_subs",
"(",
"self",
",",
"substitutions",
",",
"default",
",",
"simplify",
")",
":",
"# track the new list of unchanged args or replaced args through",
"# a substitution",
"new_arguments",
"=",
"[",
"]",
"changed_something",
"=",
"False",
"# shortcut for basic logi... | Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.} | [
"Return",
"an",
"expression",
"where",
"all",
"subterms",
"equal",
"to",
"a",
"key",
"expression",
"are",
"substituted",
"by",
"the",
"corresponding",
"value",
"expression",
"using",
"a",
"mapping",
"of",
":",
"{",
"expr",
"-",
">",
"expr",
"to",
"substitute... | python | train |
O365/python-o365 | O365/excel.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/excel.py#L1751-L1754 | def delete_worksheet(self, worksheet_id):
""" Deletes a worksheet by it's id """
url = self.build_url(self._endpoints.get('get_worksheet').format(id=quote(worksheet_id)))
return bool(self.session.delete(url)) | [
"def",
"delete_worksheet",
"(",
"self",
",",
"worksheet_id",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_worksheet'",
")",
".",
"format",
"(",
"id",
"=",
"quote",
"(",
"worksheet_id",
")",
")",
... | Deletes a worksheet by it's id | [
"Deletes",
"a",
"worksheet",
"by",
"it",
"s",
"id"
] | python | train |
Cue/scales | src/greplin/scales/samplestats.py | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L71-L95 | def percentiles(self, percentiles):
"""Given a list of percentiles (floats between 0 and 1), return a
list of the values at those percentiles, interpolating if
necessary."""
try:
scores = [0.0]*len(percentiles)
if self.count > 0:
values = self.samples()
values.sort()
... | [
"def",
"percentiles",
"(",
"self",
",",
"percentiles",
")",
":",
"try",
":",
"scores",
"=",
"[",
"0.0",
"]",
"*",
"len",
"(",
"percentiles",
")",
"if",
"self",
".",
"count",
">",
"0",
":",
"values",
"=",
"self",
".",
"samples",
"(",
")",
"values",
... | Given a list of percentiles (floats between 0 and 1), return a
list of the values at those percentiles, interpolating if
necessary. | [
"Given",
"a",
"list",
"of",
"percentiles",
"(",
"floats",
"between",
"0",
"and",
"1",
")",
"return",
"a",
"list",
"of",
"the",
"values",
"at",
"those",
"percentiles",
"interpolating",
"if",
"necessary",
"."
] | python | train |
madedotcom/photon-pump | photonpump/connection.py | https://github.com/madedotcom/photon-pump/blob/ff0736c9cacd43c1f783c9668eefb53d03a3a93e/photonpump/connection.py#L397-L416 | async def start(self):
"""Loop forever reading messages and invoking
the operation that caused them"""
while True:
try:
data = await self.reader.read(8192)
if self._trace_enabled:
self._logger.trace(
"Re... | [
"async",
"def",
"start",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"data",
"=",
"await",
"self",
".",
"reader",
".",
"read",
"(",
"8192",
")",
"if",
"self",
".",
"_trace_enabled",
":",
"self",
".",
"_logger",
".",
"trace",
"(",
"\"Re... | Loop forever reading messages and invoking
the operation that caused them | [
"Loop",
"forever",
"reading",
"messages",
"and",
"invoking",
"the",
"operation",
"that",
"caused",
"them"
] | python | train |
MacHu-GWU/superjson-project | superjson/pkg/dateutil/rrule.py | https://github.com/MacHu-GWU/superjson-project/blob/782ca4b2edbd4b4018b8cedee42eeae7c921b917/superjson/pkg/dateutil/rrule.py#L214-L230 | def after(self, dt, inc=False):
""" Returns the first recurrence after the given datetime instance. The
inc keyword defines what happens if dt is an occurrence. With
inc=True, if dt itself is an occurrence, it will be returned. """
if self._cache_complete:
gen = self... | [
"def",
"after",
"(",
"self",
",",
"dt",
",",
"inc",
"=",
"False",
")",
":",
"if",
"self",
".",
"_cache_complete",
":",
"gen",
"=",
"self",
".",
"_cache",
"else",
":",
"gen",
"=",
"self",
"if",
"inc",
":",
"for",
"i",
"in",
"gen",
":",
"if",
"i"... | Returns the first recurrence after the given datetime instance. The
inc keyword defines what happens if dt is an occurrence. With
inc=True, if dt itself is an occurrence, it will be returned. | [
"Returns",
"the",
"first",
"recurrence",
"after",
"the",
"given",
"datetime",
"instance",
".",
"The",
"inc",
"keyword",
"defines",
"what",
"happens",
"if",
"dt",
"is",
"an",
"occurrence",
".",
"With",
"inc",
"=",
"True",
"if",
"dt",
"itself",
"is",
"an",
... | python | valid |
Qiskit/qiskit-terra | qiskit/visualization/bloch.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/visualization/bloch.py#L625-L630 | def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False) | [
"def",
"_hide_tick_lines_and_labels",
"(",
"axis",
")",
":",
"for",
"item",
"in",
"axis",
".",
"get_ticklines",
"(",
")",
"+",
"axis",
".",
"get_ticklabels",
"(",
")",
":",
"item",
".",
"set_visible",
"(",
"False",
")"
] | Set visible property of ticklines and ticklabels of an axis to False | [
"Set",
"visible",
"property",
"of",
"ticklines",
"and",
"ticklabels",
"of",
"an",
"axis",
"to",
"False"
] | python | test |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L89-L104 | def _getImports_pe(pth):
"""
Find the binary dependencies of PTH.
This implementation walks through the PE header
and uses library pefile for that and supports
32/64bit Windows
"""
import PyInstaller.lib.pefile as pefile
pe = pefile.PE(pth)
dlls = set()
# Some libraries have no ... | [
"def",
"_getImports_pe",
"(",
"pth",
")",
":",
"import",
"PyInstaller",
".",
"lib",
".",
"pefile",
"as",
"pefile",
"pe",
"=",
"pefile",
".",
"PE",
"(",
"pth",
")",
"dlls",
"=",
"set",
"(",
")",
"# Some libraries have no other binary dependencies.",
"# e.g. C:\... | Find the binary dependencies of PTH.
This implementation walks through the PE header
and uses library pefile for that and supports
32/64bit Windows | [
"Find",
"the",
"binary",
"dependencies",
"of",
"PTH",
"."
] | python | train |
secdev/scapy | scapy/compat.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/compat.py#L23-L33 | def lambda_tuple_converter(func):
"""
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y
"""
if func is not None and func.__code__.co_argcount == 1:
return lambda *args: func(args[0] if len(args) == 1 else args)
else:
return... | [
"def",
"lambda_tuple_converter",
"(",
"func",
")",
":",
"if",
"func",
"is",
"not",
"None",
"and",
"func",
".",
"__code__",
".",
"co_argcount",
"==",
"1",
":",
"return",
"lambda",
"*",
"args",
":",
"func",
"(",
"args",
"[",
"0",
"]",
"if",
"len",
"(",... | Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y | [
"Converts",
"a",
"Python",
"2",
"function",
"as",
"lambda",
"(",
"x",
"y",
")",
":",
"x",
"+",
"y",
"In",
"the",
"Python",
"3",
"format",
":",
"lambda",
"x",
"y",
":",
"x",
"+",
"y"
] | python | train |
logston/py3s3 | py3s3/storage.py | https://github.com/logston/py3s3/blob/1910ca60c53a53d839d6f7b09c05b555f3bfccf4/py3s3/storage.py#L50-L67 | def save(self, name, file):
"""
Saves new content to the file specified by name. The content should be
a proper File object or any python file-like object, ready to be read
from the beginning.
"""
# Get the proper name for the file, as it will actually be saved.
i... | [
"def",
"save",
"(",
"self",
",",
"name",
",",
"file",
")",
":",
"# Get the proper name for the file, as it will actually be saved.",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"file",
".",
"name",
"if",
"not",
"hasattr",
"(",
"file",
",",
"'chunks'",
")",
... | Saves new content to the file specified by name. The content should be
a proper File object or any python file-like object, ready to be read
from the beginning. | [
"Saves",
"new",
"content",
"to",
"the",
"file",
"specified",
"by",
"name",
".",
"The",
"content",
"should",
"be",
"a",
"proper",
"File",
"object",
"or",
"any",
"python",
"file",
"-",
"like",
"object",
"ready",
"to",
"be",
"read",
"from",
"the",
"beginnin... | python | train |
webadmin87/midnight | midnight_catalog/templatetags/midnight_catalog.py | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_catalog/templatetags/midnight_catalog.py#L51-L65 | def currency(money):
"""
Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой,
а также добавлеят символ валюты.
:param money:
:return:
"""
decimals = getattr(settings, 'MIDNIGHT_CATALOG_DECIMALS', 2)
money = round(float(money), decimals)
sym... | [
"def",
"currency",
"(",
"money",
")",
":",
"decimals",
"=",
"getattr",
"(",
"settings",
",",
"'MIDNIGHT_CATALOG_DECIMALS'",
",",
"2",
")",
"money",
"=",
"round",
"(",
"float",
"(",
"money",
")",
",",
"decimals",
")",
"symbol",
"=",
"getattr",
"(",
"setti... | Фильтр валюты. Форматирует цену в соответствии с установленным количеством знаков после запятой,
а также добавлеят символ валюты.
:param money:
:return: | [
"Фильтр",
"валюты",
".",
"Форматирует",
"цену",
"в",
"соответствии",
"с",
"установленным",
"количеством",
"знаков",
"после",
"запятой",
"а",
"также",
"добавлеят",
"символ",
"валюты",
".",
":",
"param",
"money",
":",
":",
"return",
":"
] | python | train |
Spinmob/spinmob | egg/_gui.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L1547-L1560 | def set_item(self, key, value):
"""
Sets the item by key, and refills the table sorted.
"""
keys = list(self.keys())
# if it exists, update
if key in keys:
self.set_value(1,keys.index(key),str(value))
# otherwise we have to add an element
els... | [
"def",
"set_item",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
"# if it exists, update",
"if",
"key",
"in",
"keys",
":",
"self",
".",
"set_value",
"(",
"1",
",",
"keys",
".",
"index... | Sets the item by key, and refills the table sorted. | [
"Sets",
"the",
"item",
"by",
"key",
"and",
"refills",
"the",
"table",
"sorted",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_bin_validate.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_validate.py#L355-L396 | def check_syntax(self, app_path=None):
"""Run syntax on each ".py" and ".json" file.
Args:
app_path (str, optional): Defaults to None. The path of Python files.
"""
app_path = app_path or '.'
for filename in sorted(os.listdir(app_path)):
error = None
... | [
"def",
"check_syntax",
"(",
"self",
",",
"app_path",
"=",
"None",
")",
":",
"app_path",
"=",
"app_path",
"or",
"'.'",
"for",
"filename",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"app_path",
")",
")",
":",
"error",
"=",
"None",
"status",
"=",
"... | Run syntax on each ".py" and ".json" file.
Args:
app_path (str, optional): Defaults to None. The path of Python files. | [
"Run",
"syntax",
"on",
"each",
".",
"py",
"and",
".",
"json",
"file",
"."
] | python | train |
davisd50/sparc.cache | sparc/cache/splunk/area.py | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L162-L179 | def initialize(self):
"""Instantiates the cache area to be ready for updates"""
if self.collname not in self.current_kv_names():
r = self.request('post',
self.url+"storage/collections/config",
headers={'content-type': 'application/jso... | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"self",
".",
"collname",
"not",
"in",
"self",
".",
"current_kv_names",
"(",
")",
":",
"r",
"=",
"self",
".",
"request",
"(",
"'post'",
",",
"self",
".",
"url",
"+",
"\"storage/collections/config\"",
",",
... | Instantiates the cache area to be ready for updates | [
"Instantiates",
"the",
"cache",
"area",
"to",
"be",
"ready",
"for",
"updates"
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_notification_stream.py#L259-L268 | def RIBNextHopLimitExceeded_RIBNextHopLimit(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
RIBNextHopLimitExceeded = ET.SubElement(config, "RIBNextHopLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
RIBNextHopLimit = ET.SubElem... | [
"def",
"RIBNextHopLimitExceeded_RIBNextHopLimit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"RIBNextHopLimitExceeded",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"RIBNextHopLimitExceeded\"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/backend_agg.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/backend_agg.py#L419-L425 | def new_figure_manager_given_figure(num, figure):
"""
Create a new figure manager instance for the given figure.
"""
canvas = FigureCanvasAgg(figure)
manager = FigureManagerBase(canvas, num)
return manager | [
"def",
"new_figure_manager_given_figure",
"(",
"num",
",",
"figure",
")",
":",
"canvas",
"=",
"FigureCanvasAgg",
"(",
"figure",
")",
"manager",
"=",
"FigureManagerBase",
"(",
"canvas",
",",
"num",
")",
"return",
"manager"
] | Create a new figure manager instance for the given figure. | [
"Create",
"a",
"new",
"figure",
"manager",
"instance",
"for",
"the",
"given",
"figure",
"."
] | python | train |
wavefrontHQ/python-client | wavefront_api_client/api/search_api.py | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/search_api.py#L131-L152 | def search_alert_deleted_for_facet(self, facet, **kwargs): # noqa: E501
"""Lists the values of a specific facet over the customer's deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asy... | [
"def",
"search_alert_deleted_for_facet",
"(",
"self",
",",
"facet",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".... | Lists the values of a specific facet over the customer's deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_alert_deleted_for_facet(facet, async_req... | [
"Lists",
"the",
"values",
"of",
"a",
"specific",
"facet",
"over",
"the",
"customer",
"s",
"deleted",
"alerts",
"#",
"noqa",
":",
"E501"
] | python | train |
prompt-toolkit/pymux | pymux/commands/commands.py | https://github.com/prompt-toolkit/pymux/blob/3f66e62b9de4b2251c7f9afad6c516dc5a30ec67/pymux/commands/commands.py#L337-L342 | def _(pymux, variables):
" Go to previous active window. "
w = pymux.arrangement.get_previous_active_window()
if w:
pymux.arrangement.set_active_window(w) | [
"def",
"_",
"(",
"pymux",
",",
"variables",
")",
":",
"w",
"=",
"pymux",
".",
"arrangement",
".",
"get_previous_active_window",
"(",
")",
"if",
"w",
":",
"pymux",
".",
"arrangement",
".",
"set_active_window",
"(",
"w",
")"
] | Go to previous active window. | [
"Go",
"to",
"previous",
"active",
"window",
"."
] | python | train |
uber/multidimensional_urlencode | multidimensional_urlencode/urlencoder.py | https://github.com/uber/multidimensional_urlencode/blob/f626528bc3535503fa1557a53bbfacaa29920251/multidimensional_urlencode/urlencoder.py#L57-L76 | def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
valu... | [
"def",
"urlencode",
"(",
"params",
")",
":",
"# Not doing duck typing here. Will make debugging easier.",
"if",
"not",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Only dicts are supported.\"",
")",
"params",
"=",
"flatten",
"(",
... | Urlencode a multidimensional dict. | [
"Urlencode",
"a",
"multidimensional",
"dict",
"."
] | python | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L271-L311 | def stats(self, result=None, counter=0):
"""
Display the node stats info on specific depth in this dict.
::
[
{"depth": 0, "leaf": M0, "root": N0},
{"depth": 1, "leaf": M1, "root": N1},
...
{"depth": k, "leaf": Mk, "ro... | [
"def",
"stats",
"(",
"self",
",",
"result",
"=",
"None",
",",
"counter",
"=",
"0",
")",
":",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"dict",
"(",
")",
"if",
"counter",
"==",
"0",
":",
"if",
"len",
"(",
"self",
")",
":",
"result",
"[",... | Display the node stats info on specific depth in this dict.
::
[
{"depth": 0, "leaf": M0, "root": N0},
{"depth": 1, "leaf": M1, "root": N1},
...
{"depth": k, "leaf": Mk, "root": Nk},
] | [
"Display",
"the",
"node",
"stats",
"info",
"on",
"specific",
"depth",
"in",
"this",
"dict",
"."
] | python | train |
chriskiehl/Gooey | gooey/gui/components/widgets/radio_group.py | https://github.com/chriskiehl/Gooey/blob/e598573c6519b953e0ccfc1f3663f827f8cd7e22/gooey/gui/components/widgets/radio_group.py#L95-L106 | def applyStyleRules(self):
"""
Conditionally disabled/enables form fields based on the current
section in the radio group
"""
for button, widget in zip(self.radioButtons, self.widgets):
if isinstance(widget, CheckBox):
widget.hideInput()
... | [
"def",
"applyStyleRules",
"(",
"self",
")",
":",
"for",
"button",
",",
"widget",
"in",
"zip",
"(",
"self",
".",
"radioButtons",
",",
"self",
".",
"widgets",
")",
":",
"if",
"isinstance",
"(",
"widget",
",",
"CheckBox",
")",
":",
"widget",
".",
"hideInp... | Conditionally disabled/enables form fields based on the current
section in the radio group | [
"Conditionally",
"disabled",
"/",
"enables",
"form",
"fields",
"based",
"on",
"the",
"current",
"section",
"in",
"the",
"radio",
"group"
] | python | train |
hyperledger/indy-plenum | plenum/server/node.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/node.py#L1411-L1421 | async def service_observable(self, limit) -> int:
"""
Service the observable's inBox and outBox
:return: the number of messages successfully serviced
"""
if not self.isReady():
return 0
o = self._service_observable_out_box(limit)
i = await self._obser... | [
"async",
"def",
"service_observable",
"(",
"self",
",",
"limit",
")",
"->",
"int",
":",
"if",
"not",
"self",
".",
"isReady",
"(",
")",
":",
"return",
"0",
"o",
"=",
"self",
".",
"_service_observable_out_box",
"(",
"limit",
")",
"i",
"=",
"await",
"self... | Service the observable's inBox and outBox
:return: the number of messages successfully serviced | [
"Service",
"the",
"observable",
"s",
"inBox",
"and",
"outBox"
] | python | train |
rocky/python3-trepan | trepan/processor/cmdproc.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/cmdproc.py#L75-L105 | def get_stack(f, t, botframe, proc_obj=None):
"""Return a stack of frames which the debugger will use for in
showing backtraces and in frame switching. As such various frame
that are really around may be excluded unless we are debugging the
sebugger. Also we will add traceback frame on top if that
e... | [
"def",
"get_stack",
"(",
"f",
",",
"t",
",",
"botframe",
",",
"proc_obj",
"=",
"None",
")",
":",
"exclude_frame",
"=",
"lambda",
"f",
":",
"False",
"if",
"proc_obj",
":",
"settings",
"=",
"proc_obj",
".",
"debugger",
".",
"settings",
"if",
"not",
"sett... | Return a stack of frames which the debugger will use for in
showing backtraces and in frame switching. As such various frame
that are really around may be excluded unless we are debugging the
sebugger. Also we will add traceback frame on top if that
exists. | [
"Return",
"a",
"stack",
"of",
"frames",
"which",
"the",
"debugger",
"will",
"use",
"for",
"in",
"showing",
"backtraces",
"and",
"in",
"frame",
"switching",
".",
"As",
"such",
"various",
"frame",
"that",
"are",
"really",
"around",
"may",
"be",
"excluded",
"... | python | test |
google/grr | grr/server/grr_response_server/aff4_objects/security.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/security.py#L400-L402 | def ApprovalUrnBuilder(subject, user, approval_id):
"""Encode an approval URN."""
return aff4.ROOT_URN.Add("ACL").Add(subject).Add(user).Add(approval_id) | [
"def",
"ApprovalUrnBuilder",
"(",
"subject",
",",
"user",
",",
"approval_id",
")",
":",
"return",
"aff4",
".",
"ROOT_URN",
".",
"Add",
"(",
"\"ACL\"",
")",
".",
"Add",
"(",
"subject",
")",
".",
"Add",
"(",
"user",
")",
".",
"Add",
"(",
"approval_id",
... | Encode an approval URN. | [
"Encode",
"an",
"approval",
"URN",
"."
] | python | train |
tensorforce/tensorforce | tensorforce/core/optimizers/clipped_step.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/core/optimizers/clipped_step.py#L44-L73 | def tf_step(self, time, variables, **kwargs):
"""
Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional arguments passed on to the internal optimizer.
... | [
"def",
"tf_step",
"(",
"self",
",",
"time",
",",
"variables",
",",
"*",
"*",
"kwargs",
")",
":",
"deltas",
"=",
"self",
".",
"optimizer",
".",
"step",
"(",
"time",
"=",
"time",
",",
"variables",
"=",
"variables",
",",
"*",
"*",
"kwargs",
")",
"with... | Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional arguments passed on to the internal optimizer.
Returns:
List of delta tensors corresponding to ... | [
"Creates",
"the",
"TensorFlow",
"operations",
"for",
"performing",
"an",
"optimization",
"step",
"."
] | python | valid |
jason-weirather/py-seq-tools | seqtools/format/sam/bam/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/sam/bam/__init__.py#L328-L379 | def _bin_to_extra(extra_bytes):
"""Pre all the reamining bytes of an entry
Post an array of
1. A dict keyed by Tag with {'type':,'value':} where value is a string unless type is i
2. A string of the remainder
"""
#global _bam_value_type
extra = StringIO(extra_bytes)
tags = {}
rem = ''
while extra... | [
"def",
"_bin_to_extra",
"(",
"extra_bytes",
")",
":",
"#global _bam_value_type",
"extra",
"=",
"StringIO",
"(",
"extra_bytes",
")",
"tags",
"=",
"{",
"}",
"rem",
"=",
"''",
"while",
"extra",
".",
"tell",
"(",
")",
"<",
"len",
"(",
"extra_bytes",
")",
":"... | Pre all the reamining bytes of an entry
Post an array of
1. A dict keyed by Tag with {'type':,'value':} where value is a string unless type is i
2. A string of the remainder | [
"Pre",
"all",
"the",
"reamining",
"bytes",
"of",
"an",
"entry",
"Post",
"an",
"array",
"of",
"1",
".",
"A",
"dict",
"keyed",
"by",
"Tag",
"with",
"{",
"type",
":",
"value",
":",
"}",
"where",
"value",
"is",
"a",
"string",
"unless",
"type",
"is",
"i... | python | train |
clach04/python-tuya | pytuya/__init__.py | https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L160-L174 | def _send_receive(self, payload):
"""
Send single buffer `payload` and receive a single buffer.
Args:
payload(bytes): Data to send.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
... | [
"def",
"_send_receive",
"(",
"self",
",",
"payload",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_TCP",
",",
"socket",
".",
"TCP... | Send single buffer `payload` and receive a single buffer.
Args:
payload(bytes): Data to send. | [
"Send",
"single",
"buffer",
"payload",
"and",
"receive",
"a",
"single",
"buffer",
".",
"Args",
":",
"payload",
"(",
"bytes",
")",
":",
"Data",
"to",
"send",
"."
] | python | train |
saltstack/salt | salt/modules/boto_route53.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_route53.py#L110-L179 | def describe_hosted_zones(zone_id=None, domain_name=None, region=None,
key=None, keyid=None, profile=None):
'''
Return detailed info about one, or all, zones in the bound account.
If neither zone_id nor domain_name is provided, return all zones.
Note that the return format is s... | [
"def",
"describe_hosted_zones",
"(",
"zone_id",
"=",
"None",
",",
"domain_name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region"... | Return detailed info about one, or all, zones in the bound account.
If neither zone_id nor domain_name is provided, return all zones.
Note that the return format is slightly different between the 'all'
and 'single' description types.
zone_id
The unique identifier for the Hosted Zone
domain... | [
"Return",
"detailed",
"info",
"about",
"one",
"or",
"all",
"zones",
"in",
"the",
"bound",
"account",
".",
"If",
"neither",
"zone_id",
"nor",
"domain_name",
"is",
"provided",
"return",
"all",
"zones",
".",
"Note",
"that",
"the",
"return",
"format",
"is",
"s... | python | train |
rwl/pylon | examples/pyreto/thesis/common.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/examples/pyreto/thesis/common.py#L220-L226 | def get_neg_one_task_agent(generators, market, nOffer, maxSteps):
""" Returns a task-agent tuple whose action is always minus one.
"""
env = pyreto.discrete.MarketEnvironment(generators, market, nOffer)
task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps)
agent = pyreto.util.NegOneAgent(env.out... | [
"def",
"get_neg_one_task_agent",
"(",
"generators",
",",
"market",
",",
"nOffer",
",",
"maxSteps",
")",
":",
"env",
"=",
"pyreto",
".",
"discrete",
".",
"MarketEnvironment",
"(",
"generators",
",",
"market",
",",
"nOffer",
")",
"task",
"=",
"pyreto",
".",
... | Returns a task-agent tuple whose action is always minus one. | [
"Returns",
"a",
"task",
"-",
"agent",
"tuple",
"whose",
"action",
"is",
"always",
"minus",
"one",
"."
] | python | train |
CEA-COSMIC/ModOpt | modopt/math/metrics.py | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/metrics.py#L216-L247 | def nrmse(test, ref, mask=None):
"""Return NRMSE
Parameters
----------
ref : np.ndarray
the reference image
test : np.ndarray
the tested image
mask : np.ndarray, optional
the mask for the ROI
Notes
-----
Compute the metric only on magnitude.
Returns
... | [
"def",
"nrmse",
"(",
"test",
",",
"ref",
",",
"mask",
"=",
"None",
")",
":",
"test",
",",
"ref",
",",
"mask",
"=",
"_preprocess_input",
"(",
"test",
",",
"ref",
",",
"mask",
")",
"if",
"mask",
"is",
"not",
"None",
":",
"test",
"=",
"mask",
"*",
... | Return NRMSE
Parameters
----------
ref : np.ndarray
the reference image
test : np.ndarray
the tested image
mask : np.ndarray, optional
the mask for the ROI
Notes
-----
Compute the metric only on magnitude.
Returns
-------
nrmse: float, the nrmse | [
"Return",
"NRMSE"
] | python | train |
flo-compbio/genometools | genometools/rnaseq/stringtie_gene_level_expression.py | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/rnaseq/stringtie_gene_level_expression.py#L91-L260 | def main(args=None):
"""Extracts gene-level expression data from StringTie output.
Parameters
----------
args: argparse.Namespace object, optional
The argument values. If not specified, the values will be obtained by
parsing the command line arguments using the `argparse` module.
R... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"# parse command-line arguments",
"parser",
"=",
"get_argument_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"stringtie_file",
"=",
"args",
".",
"s... | Extracts gene-level expression data from StringTie output.
Parameters
----------
args: argparse.Namespace object, optional
The argument values. If not specified, the values will be obtained by
parsing the command line arguments using the `argparse` module.
Returns
-------
int
... | [
"Extracts",
"gene",
"-",
"level",
"expression",
"data",
"from",
"StringTie",
"output",
"."
] | python | train |
LonamiWebs/Telethon | telethon/tl/custom/draft.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/draft.py#L73-L84 | async def get_entity(self):
"""
Returns `entity` but will make an API call if necessary.
"""
if not self.entity and await self.get_input_entity():
try:
self._entity =\
await self._client.get_entity(self._input_entity)
except Val... | [
"async",
"def",
"get_entity",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"entity",
"and",
"await",
"self",
".",
"get_input_entity",
"(",
")",
":",
"try",
":",
"self",
".",
"_entity",
"=",
"await",
"self",
".",
"_client",
".",
"get_entity",
"(",
... | Returns `entity` but will make an API call if necessary. | [
"Returns",
"entity",
"but",
"will",
"make",
"an",
"API",
"call",
"if",
"necessary",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L4047-L4051 | def htmlSaveFile(self, filename):
"""Dump an HTML document to a file. If @filename is "-" the
stdout file is used. """
ret = libxml2mod.htmlSaveFile(filename, self._o)
return ret | [
"def",
"htmlSaveFile",
"(",
"self",
",",
"filename",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlSaveFile",
"(",
"filename",
",",
"self",
".",
"_o",
")",
"return",
"ret"
] | Dump an HTML document to a file. If @filename is "-" the
stdout file is used. | [
"Dump",
"an",
"HTML",
"document",
"to",
"a",
"file",
".",
"If"
] | python | train |
counsyl/django-pedant | pedant/decorators.py | https://github.com/counsyl/django-pedant/blob/9a9a77eacbceafebb150c80d81f78c9b19ed4d53/pedant/decorators.py#L242-L254 | def fail_on_template_errors(f, *args, **kwargs):
"""
Decorator that causes templates to fail on template errors.
"""
decorators = [
_fail_template_string_if_invalid,
_always_strict_resolve,
_disallow_catching_UnicodeDecodeError,
]
if django.VERSION < (1, 8):
decor... | [
"def",
"fail_on_template_errors",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"decorators",
"=",
"[",
"_fail_template_string_if_invalid",
",",
"_always_strict_resolve",
",",
"_disallow_catching_UnicodeDecodeError",
",",
"]",
"if",
"django",
".",
... | Decorator that causes templates to fail on template errors. | [
"Decorator",
"that",
"causes",
"templates",
"to",
"fail",
"on",
"template",
"errors",
"."
] | python | train |
pantsbuild/pants | src/python/pants/backend/jvm/tasks/coursier_resolve.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/tasks/coursier_resolve.py#L690-L704 | def execute(self):
"""Resolves the specified confs for the configured targets and returns an iterator over
tuples of (conf, jar path).
"""
jvm_resolve_subsystem = JvmResolveSubsystem.global_instance()
if jvm_resolve_subsystem.get_options().resolver != 'coursier':
return
# executor = self... | [
"def",
"execute",
"(",
"self",
")",
":",
"jvm_resolve_subsystem",
"=",
"JvmResolveSubsystem",
".",
"global_instance",
"(",
")",
"if",
"jvm_resolve_subsystem",
".",
"get_options",
"(",
")",
".",
"resolver",
"!=",
"'coursier'",
":",
"return",
"# executor = self.create... | Resolves the specified confs for the configured targets and returns an iterator over
tuples of (conf, jar path). | [
"Resolves",
"the",
"specified",
"confs",
"for",
"the",
"configured",
"targets",
"and",
"returns",
"an",
"iterator",
"over",
"tuples",
"of",
"(",
"conf",
"jar",
"path",
")",
"."
] | python | train |
sci-bots/mpm | mpm/api.py | https://github.com/sci-bots/mpm/blob/a69651cda4b37ee6b17df4fe0809249e7f4dc536/mpm/api.py#L240-L299 | def rollback(*args, **kwargs):
'''
Restore previous revision of Conda environment according to most recent
action in :attr:`MICRODROP_CONDA_ACTIONS`.
.. versionchanged:: 0.18
Add support for action revision files compressed using ``bz2``.
.. versionchanged:: 0.24
Remove channels ar... | [
"def",
"rollback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"action_files",
"=",
"MICRODROP_CONDA_ACTIONS",
".",
"files",
"(",
")",
"if",
"not",
"action_files",
":",
"# No action files, return current revision.",
"logger",
".",
"debug",
"(",
"'No rol... | Restore previous revision of Conda environment according to most recent
action in :attr:`MICRODROP_CONDA_ACTIONS`.
.. versionchanged:: 0.18
Add support for action revision files compressed using ``bz2``.
.. versionchanged:: 0.24
Remove channels argument. Use Conda channels as configured i... | [
"Restore",
"previous",
"revision",
"of",
"Conda",
"environment",
"according",
"to",
"most",
"recent",
"action",
"in",
":",
"attr",
":",
"MICRODROP_CONDA_ACTIONS",
"."
] | python | train |
pycontribs/pyrax | pyrax/cloudloadbalancers.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudloadbalancers.py#L1210-L1217 | def to_dict(self):
"""
Convert this VirtualIP to a dict representation for passing
to the API.
"""
if self.id:
return {"id": self.id}
return {"type": self.type, "ipVersion": self.ip_version} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
":",
"return",
"{",
"\"id\"",
":",
"self",
".",
"id",
"}",
"return",
"{",
"\"type\"",
":",
"self",
".",
"type",
",",
"\"ipVersion\"",
":",
"self",
".",
"ip_version",
"}"
] | Convert this VirtualIP to a dict representation for passing
to the API. | [
"Convert",
"this",
"VirtualIP",
"to",
"a",
"dict",
"representation",
"for",
"passing",
"to",
"the",
"API",
"."
] | python | train |
juju/charm-helpers | charmhelpers/contrib/openstack/utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1681-L1691 | def token_cache_pkgs(source=None, release=None):
"""Determine additional packages needed for token caching
@param source: source string for charm
@param release: release of OpenStack currently deployed
@returns List of package to enable token caching
"""
packages = []
if enable_memcache(sou... | [
"def",
"token_cache_pkgs",
"(",
"source",
"=",
"None",
",",
"release",
"=",
"None",
")",
":",
"packages",
"=",
"[",
"]",
"if",
"enable_memcache",
"(",
"source",
"=",
"source",
",",
"release",
"=",
"release",
")",
":",
"packages",
".",
"extend",
"(",
"[... | Determine additional packages needed for token caching
@param source: source string for charm
@param release: release of OpenStack currently deployed
@returns List of package to enable token caching | [
"Determine",
"additional",
"packages",
"needed",
"for",
"token",
"caching"
] | python | train |
ManiacalLabs/PixelWeb | pixelweb/bottle.py | https://github.com/ManiacalLabs/PixelWeb/blob/9eacbfd40a1d35011c2dcea15c303da9636c6b9e/pixelweb/bottle.py#L2550-L2566 | def parse_range_header(header, maxlen=0):
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, ... | [
"def",
"parse_range_header",
"(",
"header",
",",
"maxlen",
"=",
"0",
")",
":",
"if",
"not",
"header",
"or",
"header",
"[",
":",
"6",
"]",
"!=",
"'bytes='",
":",
"return",
"ranges",
"=",
"[",
"r",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"for",
"r... | Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive. | [
"Yield",
"(",
"start",
"end",
")",
"ranges",
"parsed",
"from",
"a",
"HTTP",
"Range",
"header",
".",
"Skip",
"unsatisfiable",
"ranges",
".",
"The",
"end",
"index",
"is",
"non",
"-",
"inclusive",
"."
] | python | train |
edeposit/edeposit.app.fields | edeposit/app/fields/utils.py | https://github.com/edeposit/edeposit.app.fields/blob/dfdf1f0bc435e2eac1b55ca9e69f3b29f8153e14/edeposit/app/fields/utils.py#L11-L28 | def normalizeISBN(isbn):
"""
>>> normalizeISBN('978800105473-4')
'978-80-01-05473-4'
>>> normalizeISBN('80978800105473-4')
'80978800105473-4'
>>> normalizeISBN('988800105473-4')
'988800105473-4'
>>> normalizeISBN('978-80-254-94677')
'978-80-254-9467-7'
"""
try:
ret... | [
"def",
"normalizeISBN",
"(",
"isbn",
")",
":",
"try",
":",
"return",
"isbnlib",
".",
"mask",
"(",
"isbnlib",
".",
"canonical",
"(",
"isbn",
")",
")",
"except",
"isbnlib",
".",
"NotValidISBNError",
":",
"return",
"isbn"
] | >>> normalizeISBN('978800105473-4')
'978-80-01-05473-4'
>>> normalizeISBN('80978800105473-4')
'80978800105473-4'
>>> normalizeISBN('988800105473-4')
'988800105473-4'
>>> normalizeISBN('978-80-254-94677')
'978-80-254-9467-7' | [
">>>",
"normalizeISBN",
"(",
"978800105473",
"-",
"4",
")",
"978",
"-",
"80",
"-",
"01",
"-",
"05473",
"-",
"4"
] | python | train |
apache/incubator-mxnet | example/ctc/lstm_ocr_infer.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm_ocr_infer.py#L39-L45 | def lstm_init_states(batch_size):
""" Returns a tuple of names and zero arrays for LSTM init states"""
hp = Hyperparams()
init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden)
init_names = [s[0] for s in init_shapes]
init_arrays = [mx.nd.ze... | [
"def",
"lstm_init_states",
"(",
"batch_size",
")",
":",
"hp",
"=",
"Hyperparams",
"(",
")",
"init_shapes",
"=",
"lstm",
".",
"init_states",
"(",
"batch_size",
"=",
"batch_size",
",",
"num_lstm_layer",
"=",
"hp",
".",
"num_lstm_layer",
",",
"num_hidden",
"=",
... | Returns a tuple of names and zero arrays for LSTM init states | [
"Returns",
"a",
"tuple",
"of",
"names",
"and",
"zero",
"arrays",
"for",
"LSTM",
"init",
"states"
] | python | train |
prompt-toolkit/ptpython | ptpython/completer.py | https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/completer.py#L107-L166 | def get_completions(self, document, complete_event):
"""
Get Python completions.
"""
# Do Path completions
if complete_event.completion_requested or self._complete_path_while_typing(document):
for c in self._path_completer.get_completions(document, complete_event):
... | [
"def",
"get_completions",
"(",
"self",
",",
"document",
",",
"complete_event",
")",
":",
"# Do Path completions",
"if",
"complete_event",
".",
"completion_requested",
"or",
"self",
".",
"_complete_path_while_typing",
"(",
"document",
")",
":",
"for",
"c",
"in",
"s... | Get Python completions. | [
"Get",
"Python",
"completions",
"."
] | python | train |
coghost/izen | izen/helper.py | https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L1115-L1131 | def words(fpth):
"""
ww = words(os.path.join(app_root, 'ig/helper.py'))
for k, v in (ww.most_common(3)):
print(k, v)
:param fpth:
:type fpth:
:return:
:rtype:
"""
from collections import Counter
words__ = Counter()
with open(fpth) as fp:
for line in fp:
... | [
"def",
"words",
"(",
"fpth",
")",
":",
"from",
"collections",
"import",
"Counter",
"words__",
"=",
"Counter",
"(",
")",
"with",
"open",
"(",
"fpth",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"words__",
".",
"update",
"(",
"line",
".",
"... | ww = words(os.path.join(app_root, 'ig/helper.py'))
for k, v in (ww.most_common(3)):
print(k, v)
:param fpth:
:type fpth:
:return:
:rtype: | [
"ww",
"=",
"words",
"(",
"os",
".",
"path",
".",
"join",
"(",
"app_root",
"ig",
"/",
"helper",
".",
"py",
"))",
"for",
"k",
"v",
"in",
"(",
"ww",
".",
"most_common",
"(",
"3",
"))",
":",
"print",
"(",
"k",
"v",
")"
] | python | train |
saltstack/salt | salt/modules/chocolatey.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L90-L109 | def _find_chocolatey(context, salt):
'''
Returns the full path to chocolatey.bat on the host.
'''
if 'chocolatey._path' in context:
return context['chocolatey._path']
choc_defaults = ['C:\\Chocolatey\\bin\\chocolatey.bat',
'C:\\ProgramData\\Chocolatey\\bin\\chocolatey.ex... | [
"def",
"_find_chocolatey",
"(",
"context",
",",
"salt",
")",
":",
"if",
"'chocolatey._path'",
"in",
"context",
":",
"return",
"context",
"[",
"'chocolatey._path'",
"]",
"choc_defaults",
"=",
"[",
"'C:\\\\Chocolatey\\\\bin\\\\chocolatey.bat'",
",",
"'C:\\\\ProgramData\\\... | Returns the full path to chocolatey.bat on the host. | [
"Returns",
"the",
"full",
"path",
"to",
"chocolatey",
".",
"bat",
"on",
"the",
"host",
"."
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/call/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/call/__init__.py#L131-L179 | def stream(self, to=values.unset, from_=values.unset,
parent_call_sid=values.unset, status=values.unset,
start_time_before=values.unset, start_time=values.unset,
start_time_after=values.unset, end_time_before=values.unset,
end_time=values.unset, end_time_after... | [
"def",
"stream",
"(",
"self",
",",
"to",
"=",
"values",
".",
"unset",
",",
"from_",
"=",
"values",
".",
"unset",
",",
"parent_call_sid",
"=",
"values",
".",
"unset",
",",
"status",
"=",
"values",
".",
"unset",
",",
"start_time_before",
"=",
"values",
"... | Streams CallInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode to: Phone number or Client identifie... | [
"Streams",
"CallInstance",
"records",
"from",
"the",
"API",
"as",
"a",
"generator",
"stream",
".",
"This",
"operation",
"lazily",
"loads",
"records",
"as",
"efficiently",
"as",
"possible",
"until",
"the",
"limit",
"is",
"reached",
".",
"The",
"results",
"are",... | python | train |
consbio/ncdjango | ncdjango/geoprocessing/evaluation.py | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L390-L398 | def fn_mean(self, a, axis=None):
"""
Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array.
"""
return numpy.nanmean(self._to_ndarray(a), axis=axis) | [
"def",
"fn_mean",
"(",
"self",
",",
"a",
",",
"axis",
"=",
"None",
")",
":",
"return",
"numpy",
".",
"nanmean",
"(",
"self",
".",
"_to_ndarray",
"(",
"a",
")",
",",
"axis",
"=",
"axis",
")"
] | Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array. | [
"Compute",
"the",
"arithmetic",
"mean",
"of",
"an",
"array",
"ignoring",
"NaNs",
"."
] | python | train |
percipient/django-querysetsequence | queryset_sequence/__init__.py | https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/__init__.py#L29-L35 | def multiply_iterables(it1, it2):
"""
Element-wise iterables multiplications.
"""
assert len(it1) == len(it2),\
"Can not element-wise multiply iterables of different length."
return list(map(mul, it1, it2)) | [
"def",
"multiply_iterables",
"(",
"it1",
",",
"it2",
")",
":",
"assert",
"len",
"(",
"it1",
")",
"==",
"len",
"(",
"it2",
")",
",",
"\"Can not element-wise multiply iterables of different length.\"",
"return",
"list",
"(",
"map",
"(",
"mul",
",",
"it1",
",",
... | Element-wise iterables multiplications. | [
"Element",
"-",
"wise",
"iterables",
"multiplications",
"."
] | python | train |
google/flatbuffers | python/flatbuffers/builder.py | https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L166-L273 | def WriteVtable(self):
"""
WriteVtable serializes the vtable for the current object, if needed.
Before writing out the vtable, this checks pre-existing vtables for
equality to this one. If an equal vtable is found, point the object to
the existing vtable and return.
Bec... | [
"def",
"WriteVtable",
"(",
"self",
")",
":",
"# Prepend a zero scalar to the object. Later in this function we'll",
"# write an offset here that points to the object's vtable:",
"self",
".",
"PrependSOffsetTRelative",
"(",
"0",
")",
"objectOffset",
"=",
"self",
".",
"Offset",
"... | WriteVtable serializes the vtable for the current object, if needed.
Before writing out the vtable, this checks pre-existing vtables for
equality to this one. If an equal vtable is found, point the object to
the existing vtable and return.
Because vtable values are sensitive to alignme... | [
"WriteVtable",
"serializes",
"the",
"vtable",
"for",
"the",
"current",
"object",
"if",
"needed",
"."
] | python | train |
alpacahq/pylivetrader | pylivetrader/loader.py | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/loader.py#L72-L79 | def translate(script):
'''translate zipline script into pylivetrader script.
'''
tree = ast.parse(script)
ZiplineImportVisitor().visit(tree)
return astor.to_source(tree) | [
"def",
"translate",
"(",
"script",
")",
":",
"tree",
"=",
"ast",
".",
"parse",
"(",
"script",
")",
"ZiplineImportVisitor",
"(",
")",
".",
"visit",
"(",
"tree",
")",
"return",
"astor",
".",
"to_source",
"(",
"tree",
")"
] | translate zipline script into pylivetrader script. | [
"translate",
"zipline",
"script",
"into",
"pylivetrader",
"script",
"."
] | python | train |
mitsei/dlkit | dlkit/primordium/transport/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/primordium/transport/objects.py#L63-L76 | def skip(self, n):
"""Skips a specified number of ``bytes`` in the stream.
arg: n (cardinal): the number of ``bytes`` to skip
return: (cardinal) - the actual number of ``bytes`` skipped
raise: IllegalState - this stream has been closed or
``at_end_of_stream()`` is ``... | [
"def",
"skip",
"(",
"self",
",",
"n",
")",
":",
"if",
"self",
".",
"_my_data",
".",
"closed",
"or",
"self",
".",
"at_end_of_stream",
"(",
")",
":",
"raise",
"IllegalState",
"(",
")",
"if",
"n",
"is",
"not",
"None",
":",
"self",
".",
"_my_data",
"."... | Skips a specified number of ``bytes`` in the stream.
arg: n (cardinal): the number of ``bytes`` to skip
return: (cardinal) - the actual number of ``bytes`` skipped
raise: IllegalState - this stream has been closed or
``at_end_of_stream()`` is ``true``
*compliance: ma... | [
"Skips",
"a",
"specified",
"number",
"of",
"bytes",
"in",
"the",
"stream",
"."
] | python | train |
genialis/resolwe | resolwe/flow/executors/local/prepare.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/local/prepare.py#L22-L30 | def extend_settings(self, data_id, files, secrets):
"""Prevent processes requiring access to secrets from being run."""
process = Data.objects.get(pk=data_id).process
if process.requirements.get('resources', {}).get('secrets', False):
raise PermissionDenied(
"Process ... | [
"def",
"extend_settings",
"(",
"self",
",",
"data_id",
",",
"files",
",",
"secrets",
")",
":",
"process",
"=",
"Data",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"data_id",
")",
".",
"process",
"if",
"process",
".",
"requirements",
".",
"get",
"(",
... | Prevent processes requiring access to secrets from being run. | [
"Prevent",
"processes",
"requiring",
"access",
"to",
"secrets",
"from",
"being",
"run",
"."
] | python | train |
The-Politico/politico-civic-demography | demography/management/commands/legacy_census.py | https://github.com/The-Politico/politico-civic-demography/blob/080bb964b64b06db7fd04386530e893ceed1cf98/demography/management/commands/legacy_census.py#L196-L213 | def aggregate_variable(estimate, id):
"""
Aggregate census table variables by a custom label.
"""
estimates = [
variable.estimates.get(division__id=id).estimate
for variable in estimate.variable.label.variables.all()
]
method = estimate.variable.la... | [
"def",
"aggregate_variable",
"(",
"estimate",
",",
"id",
")",
":",
"estimates",
"=",
"[",
"variable",
".",
"estimates",
".",
"get",
"(",
"division__id",
"=",
"id",
")",
".",
"estimate",
"for",
"variable",
"in",
"estimate",
".",
"variable",
".",
"label",
... | Aggregate census table variables by a custom label. | [
"Aggregate",
"census",
"table",
"variables",
"by",
"a",
"custom",
"label",
"."
] | python | train |
saltstack/salt | salt/utils/win_lgpo_netsh.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_lgpo_netsh.py#L148-L224 | def get_settings(profile, section, store='local'):
'''
Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public... | [
"def",
"get_settings",
"(",
"profile",
",",
"section",
",",
"store",
"=",
"'local'",
")",
":",
"# validate input",
"if",
"profile",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'domain'",
",",
"'public'",
",",
"'private'",
")",
":",
"raise",
"ValueError",
... | Get the firewall property from the specified profile in the specified store
as returned by ``netsh advfirewall``.
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
section (str):
The ... | [
"Get",
"the",
"firewall",
"property",
"from",
"the",
"specified",
"profile",
"in",
"the",
"specified",
"store",
"as",
"returned",
"by",
"netsh",
"advfirewall",
"."
] | python | train |
justquick/django-native-tags | native_tags/registry.py | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/registry.py#L121-L125 | def get_doc(self, tag_name):
"Get documentation for the first tag matching the given name"
for tag,func in self.tags:
if tag.startswith(tag_name) and func.__doc__:
return func.__doc__ | [
"def",
"get_doc",
"(",
"self",
",",
"tag_name",
")",
":",
"for",
"tag",
",",
"func",
"in",
"self",
".",
"tags",
":",
"if",
"tag",
".",
"startswith",
"(",
"tag_name",
")",
"and",
"func",
".",
"__doc__",
":",
"return",
"func",
".",
"__doc__"
] | Get documentation for the first tag matching the given name | [
"Get",
"documentation",
"for",
"the",
"first",
"tag",
"matching",
"the",
"given",
"name"
] | python | train |
e-dard/flask-s3 | flask_s3.py | https://github.com/e-dard/flask-s3/blob/b8c72b40eb38a05135eec36a90f1ee0c96248f72/flask_s3.py#L132-L165 | def url_for(endpoint, **values):
"""
Generates a URL to the given endpoint.
If the endpoint is for a static resource then an Amazon S3 URL is
generated, otherwise the call is passed on to `flask.url_for`.
Because this function is set as a jinja environment variable when
`FlaskS3.init_app` is i... | [
"def",
"url_for",
"(",
"endpoint",
",",
"*",
"*",
"values",
")",
":",
"app",
"=",
"current_app",
"if",
"app",
".",
"config",
".",
"get",
"(",
"'TESTING'",
",",
"False",
")",
"and",
"not",
"app",
".",
"config",
".",
"get",
"(",
"'FLASKS3_OVERRIDE_TESTIN... | Generates a URL to the given endpoint.
If the endpoint is for a static resource then an Amazon S3 URL is
generated, otherwise the call is passed on to `flask.url_for`.
Because this function is set as a jinja environment variable when
`FlaskS3.init_app` is invoked, this function replaces
`flask.url... | [
"Generates",
"a",
"URL",
"to",
"the",
"given",
"endpoint",
"."
] | python | train |
tdryer/hangups | hangups/client.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L660-L665 | async def sync_all_new_events(self, sync_all_new_events_request):
"""List all events occurring at or after a timestamp."""
response = hangouts_pb2.SyncAllNewEventsResponse()
await self._pb_request('conversations/syncallnewevents',
sync_all_new_events_request, respo... | [
"async",
"def",
"sync_all_new_events",
"(",
"self",
",",
"sync_all_new_events_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"SyncAllNewEventsResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'conversations/syncallnewevents'",
",",
"sync_all_new... | List all events occurring at or after a timestamp. | [
"List",
"all",
"events",
"occurring",
"at",
"or",
"after",
"a",
"timestamp",
"."
] | python | valid |
pyroscope/pyrocore | src/pyrocore/torrent/formatting.py | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/formatting.py#L352-L390 | def validate_sort_fields(sort_fields):
""" Make sure the fields in the given list exist, and return sorting key.
If field names are prefixed with '-', sort order is reversed for that field (descending).
"""
# Allow descending order per field by prefixing with '-'
descending = set()
def sort... | [
"def",
"validate_sort_fields",
"(",
"sort_fields",
")",
":",
"# Allow descending order per field by prefixing with '-'",
"descending",
"=",
"set",
"(",
")",
"def",
"sort_order_filter",
"(",
"name",
")",
":",
"\"Helper to remove flag and memoize sort order\"",
"if",
"name",
... | Make sure the fields in the given list exist, and return sorting key.
If field names are prefixed with '-', sort order is reversed for that field (descending). | [
"Make",
"sure",
"the",
"fields",
"in",
"the",
"given",
"list",
"exist",
"and",
"return",
"sorting",
"key",
"."
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/contrib/missing/base.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/contrib/missing/base.py#L32-L63 | def fit(self, X, y=None, **kwargs):
"""
The fit method is the primary drawing input for the
visualization since it has both the X and y data required for the
viz and the transform method does not.
Parameters
----------
X : ndarray or DataFrame of shape n x m
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"is_dataframe",
"(",
"X",
")",
":",
"self",
".",
"X",
"=",
"X",
".",
"values",
"if",
"self",
".",
"features_",
"is",
"None",
":",
"self",
"."... | The fit method is the primary drawing input for the
visualization since it has both the X and y data required for the
viz and the transform method does not.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
... | [
"The",
"fit",
"method",
"is",
"the",
"primary",
"drawing",
"input",
"for",
"the",
"visualization",
"since",
"it",
"has",
"both",
"the",
"X",
"and",
"y",
"data",
"required",
"for",
"the",
"viz",
"and",
"the",
"transform",
"method",
"does",
"not",
"."
] | python | train |
aiortc/aiortc | aiortc/rtcrtpsender.py | https://github.com/aiortc/aiortc/blob/60ed036abf4575bd63985724b4493d569e6da29b/aiortc/rtcrtpsender.py#L105-L128 | async def getStats(self):
"""
Returns statistics about the RTP sender.
:rtype: :class:`RTCStatsReport`
"""
self.__stats.add(RTCOutboundRtpStreamStats(
# RTCStats
timestamp=clock.current_datetime(),
type='outbound-rtp',
id='outbound... | [
"async",
"def",
"getStats",
"(",
"self",
")",
":",
"self",
".",
"__stats",
".",
"add",
"(",
"RTCOutboundRtpStreamStats",
"(",
"# RTCStats",
"timestamp",
"=",
"clock",
".",
"current_datetime",
"(",
")",
",",
"type",
"=",
"'outbound-rtp'",
",",
"id",
"=",
"'... | Returns statistics about the RTP sender.
:rtype: :class:`RTCStatsReport` | [
"Returns",
"statistics",
"about",
"the",
"RTP",
"sender",
"."
] | python | train |
hobson/pug-invest | pug/invest/plot.py | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/plot.py#L259-L274 | def thin_string_list(list_of_strings, max_nonempty_strings=50, blank=''):
"""Designed for composing lists of strings suitable for pyplot axis labels
Often the xtick spacing doesn't allow room for 100's of text labels, so this
eliminates every other one, then every other one of those, until they fit.
>... | [
"def",
"thin_string_list",
"(",
"list_of_strings",
",",
"max_nonempty_strings",
"=",
"50",
",",
"blank",
"=",
"''",
")",
":",
"# blank some labels to make sure they don't overlap",
"list_of_strings",
"=",
"list",
"(",
"list_of_strings",
")",
"istep",
"=",
"2",
"while"... | Designed for composing lists of strings suitable for pyplot axis labels
Often the xtick spacing doesn't allow room for 100's of text labels, so this
eliminates every other one, then every other one of those, until they fit.
>>> thin_string_list(['x']*20, 5) # doctring: +NORMALIZE_WHITESPACE
['x', '',... | [
"Designed",
"for",
"composing",
"lists",
"of",
"strings",
"suitable",
"for",
"pyplot",
"axis",
"labels"
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L5822-L5841 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'environment_id') and self.environment_id is not None:
_dict['environment_id'] = self.environment_id
if hasattr(self, 'session_token') and self.session_token is not None:
... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'environment_id'",
")",
"and",
"self",
".",
"environment_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'environment_id'",
"]",
"=",
"self",
".",
"envi... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
ic-labs/django-icekit | icekit/mixins.py | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/mixins.py#L213-L219 | def get_og_title(self):
"""
return meta_title if exists otherwise fall back to title
"""
if hasattr(self, 'meta_title') and self.meta_title:
return self.meta_title
return self.get_title() | [
"def",
"get_og_title",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'meta_title'",
")",
"and",
"self",
".",
"meta_title",
":",
"return",
"self",
".",
"meta_title",
"return",
"self",
".",
"get_title",
"(",
")"
] | return meta_title if exists otherwise fall back to title | [
"return",
"meta_title",
"if",
"exists",
"otherwise",
"fall",
"back",
"to",
"title"
] | python | train |
SBRG/ssbio | ssbio/protein/structure/properties/residues.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/residues.py#L159-L220 | def get_structure_seqrecords(model):
"""Get a dictionary of a PDB file's sequences.
Special cases include:
- Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR
- HETATMs. Currently written as an "X", or unknown amino acid.
Args:
... | [
"def",
"get_structure_seqrecords",
"(",
"model",
")",
":",
"structure_seq_records",
"=",
"[",
"]",
"# Loop over each chain of the PDB",
"for",
"chain",
"in",
"model",
":",
"tracker",
"=",
"0",
"chain_seq",
"=",
"''",
"chain_resnums",
"=",
"[",
"]",
"# Loop over th... | Get a dictionary of a PDB file's sequences.
Special cases include:
- Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR
- HETATMs. Currently written as an "X", or unknown amino acid.
Args:
model: Biopython Model object of a S... | [
"Get",
"a",
"dictionary",
"of",
"a",
"PDB",
"file",
"s",
"sequences",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/xen.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/xen.py#L1056-L1075 | def sr_list(call=None):
'''
Geta list of storage repositories
.. code-block:: bash
salt-cloud -f sr_list myxen
'''
if call != 'function':
raise SaltCloudSystemExit(
'This function must be called with -f, --function argument.'
)
ret = {}
session = _get_s... | [
"def",
"sr_list",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'This function must be called with -f, --function argument.'",
")",
"ret",
"=",
"{",
"}",
"session",
"=",
"_get_session",
"(",
")",
... | Geta list of storage repositories
.. code-block:: bash
salt-cloud -f sr_list myxen | [
"Geta",
"list",
"of",
"storage",
"repositories"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L300-L310 | def python_module_name(self) -> str:
"""
Returns the name of the Python module that this instance refers to,
in dotted Python module notation, or a blank string if it doesn't.
"""
if not self.is_python:
return ""
filepath = self.source_filename_rel_python_root... | [
"def",
"python_module_name",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"is_python",
":",
"return",
"\"\"",
"filepath",
"=",
"self",
".",
"source_filename_rel_python_root",
"dirs_and_base",
"=",
"splitext",
"(",
"filepath",
")",
"[",
"0",
... | Returns the name of the Python module that this instance refers to,
in dotted Python module notation, or a blank string if it doesn't. | [
"Returns",
"the",
"name",
"of",
"the",
"Python",
"module",
"that",
"this",
"instance",
"refers",
"to",
"in",
"dotted",
"Python",
"module",
"notation",
"or",
"a",
"blank",
"string",
"if",
"it",
"doesn",
"t",
"."
] | python | train |
jsommers/switchyard | switchyard/lib/packet/null.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/packet/null.py#L43-L50 | def from_bytes(self, raw):
'''Return a Null header object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < 4:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct a Null object".format(len(raw)))
fields = struct.unpack... | [
"def",
"from_bytes",
"(",
"self",
",",
"raw",
")",
":",
"if",
"len",
"(",
"raw",
")",
"<",
"4",
":",
"raise",
"NotEnoughDataError",
"(",
"\"Not enough bytes ({}) to reconstruct a Null object\"",
".",
"format",
"(",
"len",
"(",
"raw",
")",
")",
")",
"fields",... | Return a Null header object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. | [
"Return",
"a",
"Null",
"header",
"object",
"reconstructed",
"from",
"raw",
"bytes",
"or",
"an",
"Exception",
"if",
"we",
"can",
"t",
"resurrect",
"the",
"packet",
"."
] | python | train |
honmaple/flask-msearch | flask_msearch/elasticsearch_backend.py | https://github.com/honmaple/flask-msearch/blob/4d4dacbe83aa23e852e66a02c51f6f4b1da4445f/flask_msearch/elasticsearch_backend.py#L67-L71 | def update(self, **kwargs):
"Update document not update index."
kw = dict(index=self.name, doc_type=self.doc_type, ignore=[404])
kw.update(**kwargs)
return self._client.update(**kw) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"dict",
"(",
"index",
"=",
"self",
".",
"name",
",",
"doc_type",
"=",
"self",
".",
"doc_type",
",",
"ignore",
"=",
"[",
"404",
"]",
")",
"kw",
".",
"update",
"(",
"*",
... | Update document not update index. | [
"Update",
"document",
"not",
"update",
"index",
"."
] | python | train |
CiscoTestAutomation/yang | ncdiff/src/yang/ncdiff/model.py | https://github.com/CiscoTestAutomation/yang/blob/c70ec5ac5a91f276c4060009203770ece92e76b4/ncdiff/src/yang/ncdiff/model.py#L399-L432 | def convert_tree(self, element1, element2=None):
'''convert_tree
High-level api: Convert cxml tree to an internal schema tree. This
method is recursive.
Parameters
----------
element1 : `Element`
The node to be converted.
element2 : `Element`
... | [
"def",
"convert_tree",
"(",
"self",
",",
"element1",
",",
"element2",
"=",
"None",
")",
":",
"if",
"element2",
"is",
"None",
":",
"attributes",
"=",
"deepcopy",
"(",
"element1",
".",
"attrib",
")",
"tag",
"=",
"attributes",
"[",
"'name'",
"]",
"del",
"... | convert_tree
High-level api: Convert cxml tree to an internal schema tree. This
method is recursive.
Parameters
----------
element1 : `Element`
The node to be converted.
element2 : `Element`
A new node being constructed.
Returns
... | [
"convert_tree"
] | python | train |
riptano/ccm | ccmlib/remote.py | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/remote.py#L171-L242 | def execute(self, command, is_displayed=True, profile=None):
"""
Execute a command on the remote server
:param command: Command to execute remotely
:param is_displayed: True if information should be display; false to return output
(default: true)
:pa... | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"is_displayed",
"=",
"True",
",",
"profile",
"=",
"None",
")",
":",
"# Modify the command for remote execution",
"command",
"=",
"\" \"",
".",
"join",
"(",
"\"'{0}'\"",
".",
"format",
"(",
"argument",
")",
... | Execute a command on the remote server
:param command: Command to execute remotely
:param is_displayed: True if information should be display; false to return output
(default: true)
:param profile: Profile to source (unix like system only should set this)
... | [
"Execute",
"a",
"command",
"on",
"the",
"remote",
"server"
] | python | train |
biocommons/hgvs | hgvs/variantmapper.py | https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/variantmapper.py#L133-L172 | def g_to_n(self, var_g, tx_ac, alt_aln_method=hgvs.global_config.mapping.alt_aln_method):
"""Given a parsed g. variant, return a n. variant on the specified
transcript using the specified alignment method (default is
"splign" from NCBI).
:param hgvs.sequencevariant.SequenceVariant var_g... | [
"def",
"g_to_n",
"(",
"self",
",",
"var_g",
",",
"tx_ac",
",",
"alt_aln_method",
"=",
"hgvs",
".",
"global_config",
".",
"mapping",
".",
"alt_aln_method",
")",
":",
"if",
"not",
"(",
"var_g",
".",
"type",
"==",
"\"g\"",
")",
":",
"raise",
"HGVSInvalidVar... | Given a parsed g. variant, return a n. variant on the specified
transcript using the specified alignment method (default is
"splign" from NCBI).
:param hgvs.sequencevariant.SequenceVariant var_g: a variant object
:param str tx_ac: a transcript accession (e.g., NM_012345.6 or ENST0123456... | [
"Given",
"a",
"parsed",
"g",
".",
"variant",
"return",
"a",
"n",
".",
"variant",
"on",
"the",
"specified",
"transcript",
"using",
"the",
"specified",
"alignment",
"method",
"(",
"default",
"is",
"splign",
"from",
"NCBI",
")",
"."
] | python | train |
bububa/pyTOP | pyTOP/logistics.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/logistics.py#L342-L349 | def remove(self, contact_id, session):
'''taobao.logistics.address.remove 删除卖家地址库
用此接口删除卖家地址库'''
request = TOPRequest('taobao.logistics.address.remove')
request['contact_id'] = contact_id
self.create(self.execute(request, session))
return self.address_result | [
"def",
"remove",
"(",
"self",
",",
"contact_id",
",",
"session",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.logistics.address.remove'",
")",
"request",
"[",
"'contact_id'",
"]",
"=",
"contact_id",
"self",
".",
"create",
"(",
"self",
".",
"execute",
... | taobao.logistics.address.remove 删除卖家地址库
用此接口删除卖家地址库 | [
"taobao",
".",
"logistics",
".",
"address",
".",
"remove",
"删除卖家地址库",
"用此接口删除卖家地址库"
] | python | train |
alefnula/tea | tea/shell/__init__.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L95-L127 | def goto(directory, create=False):
"""Context object for changing directory.
Args:
directory (str): Directory to go to.
create (bool): Create directory if it doesn't exists.
Usage::
>>> with goto(directory) as ok:
... if not ok:
... print 'Error'
... | [
"def",
"goto",
"(",
"directory",
",",
"create",
"=",
"False",
")",
":",
"current",
"=",
"os",
".",
"getcwd",
"(",
")",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"director... | Context object for changing directory.
Args:
directory (str): Directory to go to.
create (bool): Create directory if it doesn't exists.
Usage::
>>> with goto(directory) as ok:
... if not ok:
... print 'Error'
... else:
... print ... | [
"Context",
"object",
"for",
"changing",
"directory",
"."
] | python | train |
intel-analytics/BigDL | pyspark/bigdl/nn/layer.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L576-L584 | def freeze(self, names=None):
"""
freeze module, if names is not None, set an array of layers that match given names
to be freezed
:param names: an array of layer names
:return:
"""
callBigDlFunc(self.bigdl_type, "freeze", self.value, names)
return self | [
"def",
"freeze",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"freeze\"",
",",
"self",
".",
"value",
",",
"names",
")",
"return",
"self"
] | freeze module, if names is not None, set an array of layers that match given names
to be freezed
:param names: an array of layer names
:return: | [
"freeze",
"module",
"if",
"names",
"is",
"not",
"None",
"set",
"an",
"array",
"of",
"layers",
"that",
"match",
"given",
"names",
"to",
"be",
"freezed",
":",
"param",
"names",
":",
"an",
"array",
"of",
"layer",
"names",
":",
"return",
":"
] | python | test |
pallets/werkzeug | src/werkzeug/wrappers/etag.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/wrappers/etag.py#L251-L258 | def freeze(self, no_etag=False):
"""Call this method if you want to make your response object ready for
pickeling. This buffers the generator if there is one. This also
sets the etag unless `no_etag` is set to `True`.
"""
if not no_etag:
self.add_etag()
supe... | [
"def",
"freeze",
"(",
"self",
",",
"no_etag",
"=",
"False",
")",
":",
"if",
"not",
"no_etag",
":",
"self",
".",
"add_etag",
"(",
")",
"super",
"(",
"ETagResponseMixin",
",",
"self",
")",
".",
"freeze",
"(",
")"
] | Call this method if you want to make your response object ready for
pickeling. This buffers the generator if there is one. This also
sets the etag unless `no_etag` is set to `True`. | [
"Call",
"this",
"method",
"if",
"you",
"want",
"to",
"make",
"your",
"response",
"object",
"ready",
"for",
"pickeling",
".",
"This",
"buffers",
"the",
"generator",
"if",
"there",
"is",
"one",
".",
"This",
"also",
"sets",
"the",
"etag",
"unless",
"no_etag",... | python | train |
boakley/robotframework-lint | rflint/parser/tables.py | https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/tables.py#L35-L71 | def statements(self):
'''Return a list of statements
This is done by joining together any rows that
have continuations
'''
# FIXME: no need to do this every time; we should cache the
# result
if len(self.rows) == 0:
return []
current_statemen... | [
"def",
"statements",
"(",
"self",
")",
":",
"# FIXME: no need to do this every time; we should cache the",
"# result",
"if",
"len",
"(",
"self",
".",
"rows",
")",
"==",
"0",
":",
"return",
"[",
"]",
"current_statement",
"=",
"Statement",
"(",
"self",
".",
"rows"... | Return a list of statements
This is done by joining together any rows that
have continuations | [
"Return",
"a",
"list",
"of",
"statements"
] | python | valid |
gem/oq-engine | openquake/hazardlib/gsim/drouet_alpes_2015.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/drouet_alpes_2015.py#L119-L126 | def _compute_mean(self, C, mag, r):
"""
Compute mean value according to equation 30, page 1021.
"""
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, r))
return mean | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"r",
")",
":",
"mean",
"=",
"(",
"C",
"[",
"'c1'",
"]",
"+",
"self",
".",
"_compute_term1",
"(",
"C",
",",
"mag",
")",
"+",
"self",
".",
"_compute_term2",
"(",
"C",
",",
"mag",
","... | Compute mean value according to equation 30, page 1021. | [
"Compute",
"mean",
"value",
"according",
"to",
"equation",
"30",
"page",
"1021",
"."
] | python | train |
smarie/python-valid8 | valid8/composition.py | https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/composition.py#L539-L565 | def pop_kwargs(kwargs,
names_with_defaults, # type: List[Tuple[str, Any]]
allow_others=False
):
"""
Internal utility method to extract optional arguments from kwargs.
:param kwargs:
:param names_with_defaults:
:param allow_others: if False (default) the... | [
"def",
"pop_kwargs",
"(",
"kwargs",
",",
"names_with_defaults",
",",
"# type: List[Tuple[str, Any]]",
"allow_others",
"=",
"False",
")",
":",
"all_arguments",
"=",
"[",
"]",
"for",
"name",
",",
"default_",
"in",
"names_with_defaults",
":",
"try",
":",
"val",
"="... | Internal utility method to extract optional arguments from kwargs.
:param kwargs:
:param names_with_defaults:
:param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end.
:return: | [
"Internal",
"utility",
"method",
"to",
"extract",
"optional",
"arguments",
"from",
"kwargs",
"."
] | python | train |
tdryer/hangups | hangups/conversation.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/conversation.py#L337-L352 | def _wrap_event(event_):
"""Wrap hangouts_pb2.Event in ConversationEvent subclass."""
cls = conversation_event.ConversationEvent
if event_.HasField('chat_message'):
cls = conversation_event.ChatMessageEvent
elif event_.HasField('otr_modification'):
cls = conversat... | [
"def",
"_wrap_event",
"(",
"event_",
")",
":",
"cls",
"=",
"conversation_event",
".",
"ConversationEvent",
"if",
"event_",
".",
"HasField",
"(",
"'chat_message'",
")",
":",
"cls",
"=",
"conversation_event",
".",
"ChatMessageEvent",
"elif",
"event_",
".",
"HasFie... | Wrap hangouts_pb2.Event in ConversationEvent subclass. | [
"Wrap",
"hangouts_pb2",
".",
"Event",
"in",
"ConversationEvent",
"subclass",
"."
] | python | valid |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAData/base_datastruct.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/base_datastruct.py#L618-L627 | def security_gen(self):
'返回一个基于代码的迭代器'
for item in self.index.levels[1]:
yield self.new(
self.data.xs(item,
level=1,
drop_level=False),
dtype=self.type,
if_fq=self.if_fq
) | [
"def",
"security_gen",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"index",
".",
"levels",
"[",
"1",
"]",
":",
"yield",
"self",
".",
"new",
"(",
"self",
".",
"data",
".",
"xs",
"(",
"item",
",",
"level",
"=",
"1",
",",
"drop_level",
... | 返回一个基于代码的迭代器 | [
"返回一个基于代码的迭代器"
] | python | train |
DataBiosphere/toil | src/toil/provisioners/clusterScaler.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/clusterScaler.py#L727-L792 | def getNodes(self, preemptable):
"""
Returns a dictionary mapping node identifiers of preemptable or non-preemptable nodes to
NodeInfo objects, one for each node.
This method is the definitive source on nodes in cluster, & is responsible for consolidating
cluster state between t... | [
"def",
"getNodes",
"(",
"self",
",",
"preemptable",
")",
":",
"def",
"_getInfo",
"(",
"allMesosNodes",
",",
"ip",
")",
":",
"info",
"=",
"None",
"try",
":",
"info",
"=",
"allMesosNodes",
"[",
"ip",
"]",
"except",
"KeyError",
":",
"# never seen by mesos - 1... | Returns a dictionary mapping node identifiers of preemptable or non-preemptable nodes to
NodeInfo objects, one for each node.
This method is the definitive source on nodes in cluster, & is responsible for consolidating
cluster state between the provisioner & batch system.
:param bool p... | [
"Returns",
"a",
"dictionary",
"mapping",
"node",
"identifiers",
"of",
"preemptable",
"or",
"non",
"-",
"preemptable",
"nodes",
"to",
"NodeInfo",
"objects",
"one",
"for",
"each",
"node",
"."
] | python | train |
pytroll/posttroll | posttroll/publisher.py | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/publisher.py#L126-L131 | def stop(self):
"""Stop the publisher.
"""
self.publish.setsockopt(zmq.LINGER, 1)
self.publish.close()
return self | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"publish",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER",
",",
"1",
")",
"self",
".",
"publish",
".",
"close",
"(",
")",
"return",
"self"
] | Stop the publisher. | [
"Stop",
"the",
"publisher",
"."
] | python | train |
luckydonald/pytgbot | code_generation/code_generator.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/code_generator.py#L26-L89 | def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"):
"""
Live template for pycharm:
y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$")
"... | [
"def",
"func",
"(",
"command",
",",
"description",
",",
"link",
",",
"params_string",
",",
"returns",
"=",
"\"On success, the sent Message is returned.\"",
",",
"return_type",
"=",
"\"Message\"",
")",
":",
"description_with_tabs",
"=",
"\"\\t\\t\"",
"+",
"description"... | Live template for pycharm:
y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") | [
"Live",
"template",
"for",
"pycharm",
":"
] | python | train |
autokey/autokey | lib/autokey/scripting.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L1256-L1265 | def run_script_from_macro(self, args):
"""
Used internally by AutoKey for phrase macros
"""
self.__macroArgs = args["args"].split(',')
try:
self.run_script(args["name"])
except Exception as e:
self.set_return_value("{ERROR: %s}" % str(e)) | [
"def",
"run_script_from_macro",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"__macroArgs",
"=",
"args",
"[",
"\"args\"",
"]",
".",
"split",
"(",
"','",
")",
"try",
":",
"self",
".",
"run_script",
"(",
"args",
"[",
"\"name\"",
"]",
")",
"except",
... | Used internally by AutoKey for phrase macros | [
"Used",
"internally",
"by",
"AutoKey",
"for",
"phrase",
"macros"
] | python | train |
anayjoshi/platypus | platypus/cfg/cfg.py | https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/cfg.py#L292-L295 | def add_output_variable(self, var):
"""Adds the argument variable as one of the output variable"""
assert(isinstance(var, Variable))
self.output_variable_list.append(var) | [
"def",
"add_output_variable",
"(",
"self",
",",
"var",
")",
":",
"assert",
"(",
"isinstance",
"(",
"var",
",",
"Variable",
")",
")",
"self",
".",
"output_variable_list",
".",
"append",
"(",
"var",
")"
] | Adds the argument variable as one of the output variable | [
"Adds",
"the",
"argument",
"variable",
"as",
"one",
"of",
"the",
"output",
"variable"
] | python | train |
AndrewIngram/django-extra-views | extra_views/contrib/mixins.py | https://github.com/AndrewIngram/django-extra-views/blob/188e1bf1f15a44d9a599028d020083af9fb43ea7/extra_views/contrib/mixins.py#L120-L131 | def get_params_for_field(self, field_name, sort_type=None):
"""
If sort_type is None - inverse current sort for field, if no sorted - use asc
"""
if not sort_type:
if self.initial_sort == field_name:
sort_type = 'desc' if self.initial_sort_type == 'asc' else '... | [
"def",
"get_params_for_field",
"(",
"self",
",",
"field_name",
",",
"sort_type",
"=",
"None",
")",
":",
"if",
"not",
"sort_type",
":",
"if",
"self",
".",
"initial_sort",
"==",
"field_name",
":",
"sort_type",
"=",
"'desc'",
"if",
"self",
".",
"initial_sort_ty... | If sort_type is None - inverse current sort for field, if no sorted - use asc | [
"If",
"sort_type",
"is",
"None",
"-",
"inverse",
"current",
"sort",
"for",
"field",
"if",
"no",
"sorted",
"-",
"use",
"asc"
] | python | valid |
Karaage-Cluster/karaage | karaage/plugins/kgapplications/views/project.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/plugins/kgapplications/views/project.py#L70-L106 | def _send_invitation(request, project):
""" The logged in project leader OR administrator wants to invite somebody.
"""
form = forms.InviteUserApplicationForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
email = form.cleaned_data['email']
applic... | [
"def",
"_send_invitation",
"(",
"request",
",",
"project",
")",
":",
"form",
"=",
"forms",
".",
"InviteUserApplicationForm",
"(",
"request",
".",
"POST",
"or",
"None",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"form",
".",
"is_valid",... | The logged in project leader OR administrator wants to invite somebody. | [
"The",
"logged",
"in",
"project",
"leader",
"OR",
"administrator",
"wants",
"to",
"invite",
"somebody",
"."
] | python | train |
sentinel-hub/eo-learn | features/eolearn/features/interpolation.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/features/eolearn/features/interpolation.py#L476-L497 | def interpolate_data(self, data, times, resampled_times):
""" Interpolates data feature
:param data: Array in a shape of t x nobs, where nobs = h x w x n
:type data: numpy.ndarray
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy... | [
"def",
"interpolate_data",
"(",
"self",
",",
"data",
",",
"times",
",",
"resampled_times",
")",
":",
"if",
"True",
"in",
"np",
".",
"unique",
"(",
"np",
".",
"isnan",
"(",
"data",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Data must not contain any maske... | Interpolates data feature
:param data: Array in a shape of t x nobs, where nobs = h x w x n
:type data: numpy.ndarray
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param resampled_times: Array of reference times in sec... | [
"Interpolates",
"data",
"feature"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.