repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
ChristianKuehnel/btlewrap | btlewrap/bluepy.py | https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/bluepy.py#L97-L104 | def check_backend() -> bool:
"""Check if the backend is available."""
try:
import bluepy.btle # noqa: F401 #pylint: disable=unused-import
return True
except ImportError as importerror:
_LOGGER.error('bluepy not found: %s', str(importerror))
return Fal... | [
"def",
"check_backend",
"(",
")",
"->",
"bool",
":",
"try",
":",
"import",
"bluepy",
".",
"btle",
"# noqa: F401 #pylint: disable=unused-import",
"return",
"True",
"except",
"ImportError",
"as",
"importerror",
":",
"_LOGGER",
".",
"error",
"(",
"'bluepy not found: %s... | Check if the backend is available. | [
"Check",
"if",
"the",
"backend",
"is",
"available",
"."
] | python | train | 39.375 |
davenquinn/Attitude | attitude/geom/conics.py | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L8-L26 | def angle_subtended(ell, **kwargs):
"""
Compute the half angle subtended (or min and max angles)
for an offset elliptical conic
from the origin or an arbitrary viewpoint.
kwargs:
tangent Return tangent instead of angle (default false)
viewpoint Defaults to origin
"""
retu... | [
"def",
"angle_subtended",
"(",
"ell",
",",
"*",
"*",
"kwargs",
")",
":",
"return_tangent",
"=",
"kwargs",
".",
"pop",
"(",
"'tangent'",
",",
"False",
")",
"con",
",",
"transform",
",",
"offset",
"=",
"ell",
".",
"projection",
"(",
"*",
"*",
"kwargs",
... | Compute the half angle subtended (or min and max angles)
for an offset elliptical conic
from the origin or an arbitrary viewpoint.
kwargs:
tangent Return tangent instead of angle (default false)
viewpoint Defaults to origin | [
"Compute",
"the",
"half",
"angle",
"subtended",
"(",
"or",
"min",
"and",
"max",
"angles",
")",
"for",
"an",
"offset",
"elliptical",
"conic",
"from",
"the",
"origin",
"or",
"an",
"arbitrary",
"viewpoint",
"."
] | python | train | 32.421053 |
saulpw/visidata | visidata/vdtui.py | https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L687-L699 | def editText(self, y, x, w, record=True, **kwargs):
'Wrap global editText with `preedit` and `postedit` hooks.'
v = self.callHook('preedit') if record else None
if not v or v[0] is None:
with EnableCursor():
v = editText(self.scr, y, x, w, **kwargs)
else:
... | [
"def",
"editText",
"(",
"self",
",",
"y",
",",
"x",
",",
"w",
",",
"record",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"v",
"=",
"self",
".",
"callHook",
"(",
"'preedit'",
")",
"if",
"record",
"else",
"None",
"if",
"not",
"v",
"or",
"v",
... | Wrap global editText with `preedit` and `postedit` hooks. | [
"Wrap",
"global",
"editText",
"with",
"preedit",
"and",
"postedit",
"hooks",
"."
] | python | train | 36.461538 |
twisted/vertex | vertex/q2q.py | https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/q2q.py#L1185-L1221 | def _sign(self, certificate_request, password):
"""
Respond to a request to sign a CSR for a user or agent located within
our domain.
"""
if self.service.portal is None:
raise BadCertificateRequest("This agent cannot sign certificates.")
subj = certificate_re... | [
"def",
"_sign",
"(",
"self",
",",
"certificate_request",
",",
"password",
")",
":",
"if",
"self",
".",
"service",
".",
"portal",
"is",
"None",
":",
"raise",
"BadCertificateRequest",
"(",
"\"This agent cannot sign certificates.\"",
")",
"subj",
"=",
"certificate_re... | Respond to a request to sign a CSR for a user or agent located within
our domain. | [
"Respond",
"to",
"a",
"request",
"to",
"sign",
"a",
"CSR",
"for",
"a",
"user",
"or",
"agent",
"located",
"within",
"our",
"domain",
"."
] | python | train | 32.243243 |
wesyoung/pyzyre | czmq/_czmq_ctypes.py | https://github.com/wesyoung/pyzyre/blob/22d4c757acefcfdb700d3802adaf30b402bb9eea/czmq/_czmq_ctypes.py#L2407-L2412 | def write(self, chunk, offset):
"""
Write chunk to file at specified position
Return 0 if OK, else -1
"""
return lib.zfile_write(self._as_parameter_, chunk, offset) | [
"def",
"write",
"(",
"self",
",",
"chunk",
",",
"offset",
")",
":",
"return",
"lib",
".",
"zfile_write",
"(",
"self",
".",
"_as_parameter_",
",",
"chunk",
",",
"offset",
")"
] | Write chunk to file at specified position
Return 0 if OK, else -1 | [
"Write",
"chunk",
"to",
"file",
"at",
"specified",
"position",
"Return",
"0",
"if",
"OK",
"else",
"-",
"1"
] | python | train | 31.833333 |
sentinel-hub/sentinelhub-py | sentinelhub/geometry.py | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L230-L240 | def transform(self, crs):
""" Transforms BBox from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Bounding box in target CRS
:rtype: BBox
"""
new_crs = CRS(crs)
return BBox((transform_point(self.lower_left, self.crs, ne... | [
"def",
"transform",
"(",
"self",
",",
"crs",
")",
":",
"new_crs",
"=",
"CRS",
"(",
"crs",
")",
"return",
"BBox",
"(",
"(",
"transform_point",
"(",
"self",
".",
"lower_left",
",",
"self",
".",
"crs",
",",
"new_crs",
")",
",",
"transform_point",
"(",
"... | Transforms BBox from current CRS to target CRS
:param crs: target CRS
:type crs: constants.CRS
:return: Bounding box in target CRS
:rtype: BBox | [
"Transforms",
"BBox",
"from",
"current",
"CRS",
"to",
"target",
"CRS"
] | python | train | 36.909091 |
PredixDev/predixpy | predix/admin/acs.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/acs.py#L23-L30 | def _get_uri(self):
"""
Will return the uri for an existing instance.
"""
if not self.service.exists():
logging.warning("Service does not yet exist.")
return self.service.settings.data['uri'] | [
"def",
"_get_uri",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"service",
".",
"exists",
"(",
")",
":",
"logging",
".",
"warning",
"(",
"\"Service does not yet exist.\"",
")",
"return",
"self",
".",
"service",
".",
"settings",
".",
"data",
"[",
"'ur... | Will return the uri for an existing instance. | [
"Will",
"return",
"the",
"uri",
"for",
"an",
"existing",
"instance",
"."
] | python | train | 29.625 |
todddeluca/python-vagrant | vagrant/__init__.py | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L978-L1005 | def _stream_vagrant_command(self, args):
"""
Execute a vagrant command, returning a generator of the output lines.
Caller should consume the entire generator to avoid the hanging the
subprocess.
:param args: Arguments for the Vagrant command.
:return: generator that yiel... | [
"def",
"_stream_vagrant_command",
"(",
"self",
",",
"args",
")",
":",
"py3",
"=",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
"# Make subprocess command",
"command",
"=",
"self",
".",
"_make_vagrant_command",
"(",
"args",
")",
"with",
"self",
... | Execute a vagrant command, returning a generator of the output lines.
Caller should consume the entire generator to avoid the hanging the
subprocess.
:param args: Arguments for the Vagrant command.
:return: generator that yields each line of the command stdout.
:rtype: generator... | [
"Execute",
"a",
"vagrant",
"command",
"returning",
"a",
"generator",
"of",
"the",
"output",
"lines",
".",
"Caller",
"should",
"consume",
"the",
"entire",
"generator",
"to",
"avoid",
"the",
"hanging",
"the",
"subprocess",
"."
] | python | train | 45.321429 |
JdeRobot/base | src/libs/comm_py/comm/ros/listenerCamera.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/libs/comm_py/comm/ros/listenerCamera.py#L111-L116 | def start (self):
'''
Starts (Subscribes) the client.
'''
self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"sub",
"=",
"rospy",
".",
"Subscriber",
"(",
"self",
".",
"topic",
",",
"ImageROS",
",",
"self",
".",
"__callback",
")"
] | Starts (Subscribes) the client. | [
"Starts",
"(",
"Subscribes",
")",
"the",
"client",
"."
] | python | train | 25.333333 |
mitsei/dlkit | dlkit/json_/assessment/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/managers.py#L1721-L1735 | def get_bank_admin_session(self):
"""Gets the OsidSession associated with the bank administration service.
return: (osid.assessment.BankAdminSession) - a
``BankAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bank_adm... | [
"def",
"get_bank_admin_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_bank_admin",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"BankAdminSession",
"(",
"runtime",... | Gets the OsidSession associated with the bank administration service.
return: (osid.assessment.BankAdminSession) - a
``BankAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bank_admin() is false``
*compliance: optional... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"bank",
"administration",
"service",
"."
] | python | train | 42 |
erdewit/ib_insync | ib_insync/client.py | https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/client.py#L137-L147 | def connectionStats(self) -> ConnectionStats:
"""
Get statistics about the connection.
"""
if not self.isReady():
raise ConnectionError('Not connected')
return ConnectionStats(
self._startTime,
time.time() - self._startTime,
self._n... | [
"def",
"connectionStats",
"(",
"self",
")",
"->",
"ConnectionStats",
":",
"if",
"not",
"self",
".",
"isReady",
"(",
")",
":",
"raise",
"ConnectionError",
"(",
"'Not connected'",
")",
"return",
"ConnectionStats",
"(",
"self",
".",
"_startTime",
",",
"time",
"... | Get statistics about the connection. | [
"Get",
"statistics",
"about",
"the",
"connection",
"."
] | python | train | 36.181818 |
wummel/dosage | scripts/creators.py | https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/scripts/creators.py#L56-L63 | def has_gocomics_comic(name):
"""Test if comic name already exists."""
cname = "Gocomics/%s" % name
for scraperclass in get_scraperclasses():
lname = scraperclass.getName().lower()
if lname == cname.lower():
return True
return False | [
"def",
"has_gocomics_comic",
"(",
"name",
")",
":",
"cname",
"=",
"\"Gocomics/%s\"",
"%",
"name",
"for",
"scraperclass",
"in",
"get_scraperclasses",
"(",
")",
":",
"lname",
"=",
"scraperclass",
".",
"getName",
"(",
")",
".",
"lower",
"(",
")",
"if",
"lname... | Test if comic name already exists. | [
"Test",
"if",
"comic",
"name",
"already",
"exists",
"."
] | python | train | 33.625 |
broadinstitute/fiss | firecloud/api.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/api.py#L184-L200 | def upload_entities(namespace, workspace, entity_data):
"""Upload entities from tab-delimited string.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
entity_data (str): TSV string describing entites
Swagger:
https://api.firecloud.or... | [
"def",
"upload_entities",
"(",
"namespace",
",",
"workspace",
",",
"entity_data",
")",
":",
"body",
"=",
"urlencode",
"(",
"{",
"\"entities\"",
":",
"entity_data",
"}",
")",
"headers",
"=",
"_fiss_agent_header",
"(",
"{",
"'Content-type'",
":",
"\"application/x-... | Upload entities from tab-delimited string.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
entity_data (str): TSV string describing entites
Swagger:
https://api.firecloud.org/#!/Entities/importEntities | [
"Upload",
"entities",
"from",
"tab",
"-",
"delimited",
"string",
"."
] | python | train | 36.352941 |
wonambi-python/wonambi | wonambi/widgets/traces.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L749-L752 | def Y_less(self):
"""Decrease the scaling."""
self.parent.value('y_scale', self.parent.value('y_scale') / 2)
self.parent.traces.display() | [
"def",
"Y_less",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'y_scale'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'y_scale'",
")",
"/",
"2",
")",
"self",
".",
"parent",
".",
"traces",
".",
"display",
"(",
")"
] | Decrease the scaling. | [
"Decrease",
"the",
"scaling",
"."
] | python | train | 39.5 |
tensorflow/tensor2tensor | tensor2tensor/layers/modalities.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/modalities.py#L455-L485 | def get_weights(model_hparams, vocab_size, hidden_dim=None):
"""Create or get concatenated embedding or softmax variable.
Args:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size
Returns:
a lis... | [
"def",
"get_weights",
"(",
"model_hparams",
",",
"vocab_size",
",",
"hidden_dim",
"=",
"None",
")",
":",
"if",
"hidden_dim",
"is",
"None",
":",
"hidden_dim",
"=",
"model_hparams",
".",
"hidden_size",
"num_shards",
"=",
"model_hparams",
".",
"symbol_modality_num_sh... | Create or get concatenated embedding or softmax variable.
Args:
model_hparams: HParams, model hyperparmeters.
vocab_size: int, vocabulary size.
hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size
Returns:
a list of num_shards Tensors. | [
"Create",
"or",
"get",
"concatenated",
"embedding",
"or",
"softmax",
"variable",
"."
] | python | train | 32.16129 |
merll/docker-map | dockermap/dep.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/dep.py#L159-L181 | def merge_dependency(self, item, resolve_parent, parents):
"""
Merge dependencies of element with further dependencies. First parent dependencies are checked, and then
immediate dependencies of the current element should be added to the list, but without duplicating any entries.
:param ... | [
"def",
"merge_dependency",
"(",
"self",
",",
"item",
",",
"resolve_parent",
",",
"parents",
")",
":",
"dep",
"=",
"[",
"]",
"for",
"parent_key",
"in",
"parents",
":",
"if",
"item",
"==",
"parent_key",
":",
"raise",
"CircularDependency",
"(",
"item",
",",
... | Merge dependencies of element with further dependencies. First parent dependencies are checked, and then
immediate dependencies of the current element should be added to the list, but without duplicating any entries.
:param item: Item.
:param resolve_parent: Function to resolve parent dependenc... | [
"Merge",
"dependencies",
"of",
"element",
"with",
"further",
"dependencies",
".",
"First",
"parent",
"dependencies",
"are",
"checked",
"and",
"then",
"immediate",
"dependencies",
"of",
"the",
"current",
"element",
"should",
"be",
"added",
"to",
"the",
"list",
"b... | python | train | 45.434783 |
softlayer/softlayer-python | SoftLayer/CLI/hardware/power.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/power.py#L35-L51 | def reboot(env, identifier, hard):
"""Reboot an active server."""
hardware_server = env.client['Hardware_Server']
mgr = SoftLayer.HardwareManager(env.client)
hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
if not (env.skip_confirmations or
formatting.confirm('This wi... | [
"def",
"reboot",
"(",
"env",
",",
"identifier",
",",
"hard",
")",
":",
"hardware_server",
"=",
"env",
".",
"client",
"[",
"'Hardware_Server'",
"]",
"mgr",
"=",
"SoftLayer",
".",
"HardwareManager",
"(",
"env",
".",
"client",
")",
"hw_id",
"=",
"helpers",
... | Reboot an active server. | [
"Reboot",
"an",
"active",
"server",
"."
] | python | train | 37.352941 |
dnanexus/dx-toolkit | src/python/dxpy/utils/resolver.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/utils/resolver.py#L195-L211 | def object_exists_in_project(obj_id, proj_id):
'''
:param obj_id: object ID
:type obj_id: str
:param proj_id: project ID
:type proj_id: str
Returns True if the specified data object can be found in the specified
project.
'''
if obj_id is None:
raise ValueError("Expected obj_... | [
"def",
"object_exists_in_project",
"(",
"obj_id",
",",
"proj_id",
")",
":",
"if",
"obj_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Expected obj_id to be a string\"",
")",
"if",
"proj_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Expected proj_i... | :param obj_id: object ID
:type obj_id: str
:param proj_id: project ID
:type proj_id: str
Returns True if the specified data object can be found in the specified
project. | [
":",
"param",
"obj_id",
":",
"object",
"ID",
":",
"type",
"obj_id",
":",
"str",
":",
"param",
"proj_id",
":",
"project",
"ID",
":",
"type",
"proj_id",
":",
"str"
] | python | train | 37.058824 |
minorg/pastpy | py/src/pastpy/gen/database/impl/online/online_database_object_detail_image.py | https://github.com/minorg/pastpy/blob/7d5d6d511629481850216565e7451b5dcb8027a9/py/src/pastpy/gen/database/impl/online/online_database_object_detail_image.py#L445-L487 | def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
'''
opro... | [
"def",
"write",
"(",
"self",
",",
"oprot",
")",
":",
"oprot",
".",
"write_struct_begin",
"(",
"'OnlineDatabaseObjectDetailImage'",
")",
"oprot",
".",
"write_field_begin",
"(",
"name",
"=",
"'full_size_url'",
",",
"type",
"=",
"11",
",",
"id",
"=",
"None",
")... | Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage | [
"Write",
"this",
"object",
"to",
"the",
"given",
"output",
"protocol",
"and",
"return",
"self",
"."
] | python | train | 32.906977 |
Esri/ArcREST | src/arcrest/manageportal/administration.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L1799-L1807 | def security(self):
"""
Creates a reference to the Security operations for Portal
"""
url = self._url + "/security"
return _Security(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
... | [
"def",
"security",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/security\"",
"return",
"_Security",
"(",
"url",
"=",
"url",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
... | Creates a reference to the Security operations for Portal | [
"Creates",
"a",
"reference",
"to",
"the",
"Security",
"operations",
"for",
"Portal"
] | python | train | 38.111111 |
modin-project/modin | modin/pandas/base.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/base.py#L1056-L1136 | def fillna(
self,
value=None,
method=None,
axis=None,
inplace=False,
limit=None,
downcast=None,
**kwargs
):
"""Fill NA/NaN values using the specified method.
Args:
value: Value to use to fill holes. This value ... | [
"def",
"fillna",
"(",
"self",
",",
"value",
"=",
"None",
",",
"method",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"limit",
"=",
"None",
",",
"downcast",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO impleme... | Fill NA/NaN values using the specified method.
Args:
value: Value to use to fill holes. This value cannot be a list.
method: Method to use for filling holes in reindexed Series pad.
ffill: propagate last valid observation forward to next valid
bac... | [
"Fill",
"NA",
"/",
"NaN",
"values",
"using",
"the",
"specified",
"method",
".",
"Args",
":",
"value",
":",
"Value",
"to",
"use",
"to",
"fill",
"holes",
".",
"This",
"value",
"cannot",
"be",
"a",
"list",
".",
"method",
":",
"Method",
"to",
"use",
"for... | python | train | 40.061728 |
JohnVinyard/zounds | zounds/nputil/npx.py | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/nputil/npx.py#L332-L343 | def append(self, item):
"""
append a single item to the array, growing the wrapped numpy array
if necessary
"""
try:
self._data[self._position] = item
except IndexError:
self._grow()
self._data[self._position] = item
self._posit... | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"try",
":",
"self",
".",
"_data",
"[",
"self",
".",
"_position",
"]",
"=",
"item",
"except",
"IndexError",
":",
"self",
".",
"_grow",
"(",
")",
"self",
".",
"_data",
"[",
"self",
".",
"_position"... | append a single item to the array, growing the wrapped numpy array
if necessary | [
"append",
"a",
"single",
"item",
"to",
"the",
"array",
"growing",
"the",
"wrapped",
"numpy",
"array",
"if",
"necessary"
] | python | train | 28.083333 |
nuSTORM/gnomon | gnomon/processors/Fitter.py | https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/processors/Fitter.py#L175-L188 | def sort_points(self, points):
"""Take points (z,x,q) and sort by increasing z"""
new_points = []
z_lookup = {}
for z, x, Q in points:
z_lookup[z] = (z, x, Q)
z_keys = z_lookup.keys()
z_keys.sort()
for key in z_keys:
new_points.append(z_l... | [
"def",
"sort_points",
"(",
"self",
",",
"points",
")",
":",
"new_points",
"=",
"[",
"]",
"z_lookup",
"=",
"{",
"}",
"for",
"z",
",",
"x",
",",
"Q",
"in",
"points",
":",
"z_lookup",
"[",
"z",
"]",
"=",
"(",
"z",
",",
"x",
",",
"Q",
")",
"z_key... | Take points (z,x,q) and sort by increasing z | [
"Take",
"points",
"(",
"z",
"x",
"q",
")",
"and",
"sort",
"by",
"increasing",
"z"
] | python | train | 24.642857 |
PyHDI/Pyverilog | pyverilog/vparser/parser.py | https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L1316-L1320 | def p_sens_empty(self, p):
'senslist : empty'
p[0] = SensList(
(Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_sens_empty",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"SensList",
"(",
"(",
"Sens",
"(",
"None",
",",
"'all'",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
",",
")",
",",
"lineno",
"=",
"p",
".",
"l... | senslist : empty | [
"senslist",
":",
"empty"
] | python | train | 37 |
siemens/django-dingos | dingos/core/xml_utils.py | https://github.com/siemens/django-dingos/blob/7154f75b06d2538568e2f2455a76f3d0db0b7d70/dingos/core/xml_utils.py#L21-L44 | def extract_attributes(element, prefix_key_char='@', dict_constructor=dict):
"""
Given an XML node, extract a dictionary of attribute key-value pairs.
Optional arguments:
- prefix_key_char: if a character is given, the attributes keys
in the resulting dictionary are prefixed with that character.
... | [
"def",
"extract_attributes",
"(",
"element",
",",
"prefix_key_char",
"=",
"'@'",
",",
"dict_constructor",
"=",
"dict",
")",
":",
"result",
"=",
"dict_constructor",
"(",
")",
"if",
"element",
".",
"properties",
":",
"for",
"prop",
"in",
"element",
".",
"prope... | Given an XML node, extract a dictionary of attribute key-value pairs.
Optional arguments:
- prefix_key_char: if a character is given, the attributes keys
in the resulting dictionary are prefixed with that character.
- dict_constructor: the class used to create the resulting dictionary.
Default... | [
"Given",
"an",
"XML",
"node",
"extract",
"a",
"dictionary",
"of",
"attribute",
"key",
"-",
"value",
"pairs",
".",
"Optional",
"arguments",
":"
] | python | train | 41.583333 |
reingart/gui2py | gui/resource.py | https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/resource.py#L158-L196 | def dump(obj):
"Recursive convert a live GUI object to a resource list/dict"
from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec
import decimal, datetime
from .font import Font
from .graphic import Bitmap, Color
from . import registry
ret = {'type': obj.__class__.__name_... | [
"def",
"dump",
"(",
"obj",
")",
":",
"from",
".",
"spec",
"import",
"InitSpec",
",",
"DimensionSpec",
",",
"StyleSpec",
",",
"InternalSpec",
"import",
"decimal",
",",
"datetime",
"from",
".",
"font",
"import",
"Font",
"from",
".",
"graphic",
"import",
"Bit... | Recursive convert a live GUI object to a resource list/dict | [
"Recursive",
"convert",
"a",
"live",
"GUI",
"object",
"to",
"a",
"resource",
"list",
"/",
"dict"
] | python | test | 34.846154 |
UCSBarchlab/PyRTL | pyrtl/simulation.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L438-L451 | def inspect(self, w):
""" Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w is ... | [
"def",
"inspect",
"(",
"self",
",",
"w",
")",
":",
"try",
":",
"return",
"self",
".",
"context",
"[",
"self",
".",
"_to_name",
"(",
"w",
")",
"]",
"except",
"AttributeError",
":",
"raise",
"PyrtlError",
"(",
"\"No context available. Please run a simulation ste... | Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w is not being tracked in the simulatio... | [
"Get",
"the",
"value",
"of",
"a",
"wirevector",
"in",
"the",
"last",
"simulation",
"cycle",
"."
] | python | train | 43 |
richardkiss/pycoin | pycoin/coins/bitcoin/SolutionChecker.py | https://github.com/richardkiss/pycoin/blob/1e8d0d9fe20ce0347b97847bb529cd1bd84c7442/pycoin/coins/bitcoin/SolutionChecker.py#L99-L157 | def _signature_hash(self, tx_out_script, unsigned_txs_out_idx, hash_type):
"""
Return the canonical hash for a transaction. We need to
remove references to the signature, since it's a signature
of the hash before the signature is applied.
:param tx_out_script: the script the coi... | [
"def",
"_signature_hash",
"(",
"self",
",",
"tx_out_script",
",",
"unsigned_txs_out_idx",
",",
"hash_type",
")",
":",
"# In case concatenating two scripts ends up with two codeseparators,",
"# or an extra one at the end, this prevents all those possible incompatibilities.",
"tx_out_scrip... | Return the canonical hash for a transaction. We need to
remove references to the signature, since it's a signature
of the hash before the signature is applied.
:param tx_out_script: the script the coins for unsigned_txs_out_idx are coming from
:param unsigned_txs_out_idx: where to put t... | [
"Return",
"the",
"canonical",
"hash",
"for",
"a",
"transaction",
".",
"We",
"need",
"to",
"remove",
"references",
"to",
"the",
"signature",
"since",
"it",
"s",
"a",
"signature",
"of",
"the",
"hash",
"before",
"the",
"signature",
"is",
"applied",
"."
] | python | train | 46.338983 |
saltstack/salt | salt/cloud/clouds/xen.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/xen.py#L934-L957 | def reboot(name, call=None, session=None):
'''
Reboot a vm
.. code-block:: bash
salt-cloud -a reboot xenvm01
'''
if call == 'function':
raise SaltCloudException(
'The show_instnce function must be called with -a or --action.'
)
if session is None:
s... | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudException",
"(",
"'The show_instnce function must be called with -a or --action.'",
")",
"if",
"session",
"is",... | Reboot a vm
.. code-block:: bash
salt-cloud -a reboot xenvm01 | [
"Reboot",
"a",
"vm"
] | python | train | 28.375 |
aws/aws-xray-sdk-python | aws_xray_sdk/core/sampling/connector.py | https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/sampling/connector.py#L49-L73 | def fetch_sampling_rules(self):
"""
Use X-Ray botocore client to get the centralized sampling rules
from X-Ray service. The call is proxied and signed by X-Ray Daemon.
"""
new_rules = []
resp = self._xray_client.get_sampling_rules()
records = resp['SamplingRuleRe... | [
"def",
"fetch_sampling_rules",
"(",
"self",
")",
":",
"new_rules",
"=",
"[",
"]",
"resp",
"=",
"self",
".",
"_xray_client",
".",
"get_sampling_rules",
"(",
")",
"records",
"=",
"resp",
"[",
"'SamplingRuleRecords'",
"]",
"for",
"record",
"in",
"records",
":",... | Use X-Ray botocore client to get the centralized sampling rules
from X-Ray service. The call is proxied and signed by X-Ray Daemon. | [
"Use",
"X",
"-",
"Ray",
"botocore",
"client",
"to",
"get",
"the",
"centralized",
"sampling",
"rules",
"from",
"X",
"-",
"Ray",
"service",
".",
"The",
"call",
"is",
"proxied",
"and",
"signed",
"by",
"X",
"-",
"Ray",
"Daemon",
"."
] | python | train | 43.8 |
pantsbuild/pants | src/python/pants/engine/legacy/graph.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/legacy/graph.py#L571-L582 | def create_legacy_graph_tasks():
"""Create tasks to recursively parse the legacy graph."""
return [
transitive_hydrated_targets,
transitive_hydrated_target,
hydrated_targets,
hydrate_target,
find_owners,
hydrate_sources,
hydrate_bundles,
RootRule(OwnersRequest),
] | [
"def",
"create_legacy_graph_tasks",
"(",
")",
":",
"return",
"[",
"transitive_hydrated_targets",
",",
"transitive_hydrated_target",
",",
"hydrated_targets",
",",
"hydrate_target",
",",
"find_owners",
",",
"hydrate_sources",
",",
"hydrate_bundles",
",",
"RootRule",
"(",
... | Create tasks to recursively parse the legacy graph. | [
"Create",
"tasks",
"to",
"recursively",
"parse",
"the",
"legacy",
"graph",
"."
] | python | train | 24.25 |
drcloud/magiclog | magiclog.py | https://github.com/drcloud/magiclog/blob/f045a68f9d3eff946c0a0d3147edff0ec0c0b344/magiclog.py#L68-L83 | def auto(cls, syslog=None, stderr=None, level=None, extended=None,
server=None):
"""Tries to guess a sound logging configuration.
"""
level = norm_level(level) or logging.INFO
if syslog is None and stderr is None:
if sys.stderr.isatty() or syslog_path() is None:
... | [
"def",
"auto",
"(",
"cls",
",",
"syslog",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"level",
"=",
"None",
",",
"extended",
"=",
"None",
",",
"server",
"=",
"None",
")",
":",
"level",
"=",
"norm_level",
"(",
"level",
")",
"or",
"logging",
".",
... | Tries to guess a sound logging configuration. | [
"Tries",
"to",
"guess",
"a",
"sound",
"logging",
"configuration",
"."
] | python | train | 45.875 |
eqcorrscan/EQcorrscan | eqcorrscan/utils/catalog_to_dd.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/catalog_to_dd.py#L77-L127 | def _av_weight(W1, W2):
"""
Function to convert from two seisan weights (0-4) to one hypoDD \
weight(0-1).
:type W1: str
:param W1: Seisan input weight (0-4)
:type W2: str
:param W2: Seisan input weight (0-4)
:returns: str
.. rubric:: Example
>>> print(_av_weight(1, 4))
0.... | [
"def",
"_av_weight",
"(",
"W1",
",",
"W2",
")",
":",
"if",
"str",
"(",
"W1",
")",
"in",
"[",
"' '",
",",
"''",
"]",
":",
"W1",
"=",
"1",
"elif",
"str",
"(",
"W1",
")",
"in",
"[",
"'-9'",
",",
"'9'",
",",
"'9.0'",
",",
"'-9.0'",
"]",
":",
... | Function to convert from two seisan weights (0-4) to one hypoDD \
weight(0-1).
:type W1: str
:param W1: Seisan input weight (0-4)
:type W2: str
:param W2: Seisan input weight (0-4)
:returns: str
.. rubric:: Example
>>> print(_av_weight(1, 4))
0.3750
>>> print(_av_weight(0, 0))... | [
"Function",
"to",
"convert",
"from",
"two",
"seisan",
"weights",
"(",
"0",
"-",
"4",
")",
"to",
"one",
"hypoDD",
"\\",
"weight",
"(",
"0",
"-",
"1",
")",
"."
] | python | train | 24.019608 |
psd-tools/psd-tools | src/psd_tools/api/shape.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/shape.py#L208-L211 | def line_cap_type(self):
"""Cap type, one of `butt`, `round`, `square`."""
key = self._data.get(b'strokeStyleLineCapType').enum
return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key)) | [
"def",
"line_cap_type",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"b'strokeStyleLineCapType'",
")",
".",
"enum",
"return",
"self",
".",
"STROKE_STYLE_LINE_CAP_TYPES",
".",
"get",
"(",
"key",
",",
"str",
"(",
"key",
")",
")... | Cap type, one of `butt`, `round`, `square`. | [
"Cap",
"type",
"one",
"of",
"butt",
"round",
"square",
"."
] | python | train | 51.75 |
mongodb/mongo-python-driver | pymongo/monitor.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/monitor.py#L170-L184 | def _check_with_socket(self, sock_info):
"""Return (IsMaster, round_trip_time).
Can raise ConnectionFailure or OperationFailure.
"""
start = _time()
try:
return (sock_info.ismaster(self._pool.opts.metadata,
self._topology.max_cl... | [
"def",
"_check_with_socket",
"(",
"self",
",",
"sock_info",
")",
":",
"start",
"=",
"_time",
"(",
")",
"try",
":",
"return",
"(",
"sock_info",
".",
"ismaster",
"(",
"self",
".",
"_pool",
".",
"opts",
".",
"metadata",
",",
"self",
".",
"_topology",
".",... | Return (IsMaster, round_trip_time).
Can raise ConnectionFailure or OperationFailure. | [
"Return",
"(",
"IsMaster",
"round_trip_time",
")",
"."
] | python | train | 38.466667 |
fabric-bolt/fabric-bolt | fabric_bolt/projects/models.py | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/models.py#L304-L310 | def add_output(self, line):
"""
Appends {line} of output to the output instantly. (directly hits the database)
:param line: the line of text to append
:return: None
"""
Deployment.objects.filter(pk=self.id).update(output=CF('output')+line) | [
"def",
"add_output",
"(",
"self",
",",
"line",
")",
":",
"Deployment",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"id",
")",
".",
"update",
"(",
"output",
"=",
"CF",
"(",
"'output'",
")",
"+",
"line",
")"
] | Appends {line} of output to the output instantly. (directly hits the database)
:param line: the line of text to append
:return: None | [
"Appends",
"{",
"line",
"}",
"of",
"output",
"to",
"the",
"output",
"instantly",
".",
"(",
"directly",
"hits",
"the",
"database",
")",
":",
"param",
"line",
":",
"the",
"line",
"of",
"text",
"to",
"append",
":",
"return",
":",
"None"
] | python | train | 40.142857 |
OpenKMIP/PyKMIP | kmip/pie/client.py | https://github.com/OpenKMIP/PyKMIP/blob/b51c5b044bd05f8c85a1d65d13a583a4d8fc1b0e/kmip/pie/client.py#L921-L951 | def activate(self, uid=None):
"""
Activate a managed object stored by a KMIP appliance.
Args:
uid (string): The unique ID of the managed object to activate.
Optional, defaults to None.
Returns:
None
Raises:
ClientConnectionNo... | [
"def",
"activate",
"(",
"self",
",",
"uid",
"=",
"None",
")",
":",
"# Check input",
"if",
"uid",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"uid",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"TypeError",
"(",
"\"uid must be a strin... | Activate a managed object stored by a KMIP appliance.
Args:
uid (string): The unique ID of the managed object to activate.
Optional, defaults to None.
Returns:
None
Raises:
ClientConnectionNotOpen: if the client connection is unusable
... | [
"Activate",
"a",
"managed",
"object",
"stored",
"by",
"a",
"KMIP",
"appliance",
"."
] | python | test | 33.419355 |
SCIP-Interfaces/PySCIPOpt | examples/unfinished/staff_sched_mo.py | https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/unfinished/staff_sched_mo.py#L13-L62 | def staff_mo(I,T,N,J,S,c,b):
"""
staff: staff scheduling
Parameters:
- I: set of members in the staff
- T: number of periods in a cycle
- N: number of working periods required for staff's elements in a cycle
- J: set of shifts in each period (shift 0 == rest)
- S: sub... | [
"def",
"staff_mo",
"(",
"I",
",",
"T",
",",
"N",
",",
"J",
",",
"S",
",",
"c",
",",
"b",
")",
":",
"Ts",
"=",
"range",
"(",
"1",
",",
"T",
"+",
"1",
")",
"model",
"=",
"Model",
"(",
"\"staff scheduling -- multiobjective version\"",
")",
"x",
",",... | staff: staff scheduling
Parameters:
- I: set of members in the staff
- T: number of periods in a cycle
- N: number of working periods required for staff's elements in a cycle
- J: set of shifts in each period (shift 0 == rest)
- S: subset of shifts that must be kept at least ... | [
"staff",
":",
"staff",
"scheduling",
"Parameters",
":",
"-",
"I",
":",
"set",
"of",
"members",
"in",
"the",
"staff",
"-",
"T",
":",
"number",
"of",
"periods",
"in",
"a",
"cycle",
"-",
"N",
":",
"number",
"of",
"working",
"periods",
"required",
"for",
... | python | train | 39.06 |
maas/python-libmaas | maas/client/viscera/machines.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L800-L805 | async def restore_networking_configuration(self):
"""
Restore machine's networking configuration to its initial state.
"""
self._data = await self._handler.restore_networking_configuration(
system_id=self.system_id) | [
"async",
"def",
"restore_networking_configuration",
"(",
"self",
")",
":",
"self",
".",
"_data",
"=",
"await",
"self",
".",
"_handler",
".",
"restore_networking_configuration",
"(",
"system_id",
"=",
"self",
".",
"system_id",
")"
] | Restore machine's networking configuration to its initial state. | [
"Restore",
"machine",
"s",
"networking",
"configuration",
"to",
"its",
"initial",
"state",
"."
] | python | train | 42.333333 |
odlgroup/odl | odl/discr/lp_discr.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/discr/lp_discr.py#L716-L760 | def conj(self, out=None):
"""Complex conjugate of this element.
Parameters
----------
out : `DiscreteLpElement`, optional
Element to which the complex conjugate is written.
Must be an element of this element's space.
Returns
-------
out :... | [
"def",
"conj",
"(",
"self",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"return",
"self",
".",
"space",
".",
"element",
"(",
"self",
".",
"tensor",
".",
"conj",
"(",
")",
")",
"else",
":",
"self",
".",
"tensor",
".",
"con... | Complex conjugate of this element.
Parameters
----------
out : `DiscreteLpElement`, optional
Element to which the complex conjugate is written.
Must be an element of this element's space.
Returns
-------
out : `DiscreteLpElement`
The ... | [
"Complex",
"conjugate",
"of",
"this",
"element",
"."
] | python | train | 27.644444 |
welbornprod/colr | colr/colr.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L1976-L2008 | def as_colr(
self, label_args=None, type_args=None, type_val_args=None,
value_args=None, spec_args=None):
""" Like __str__, except it returns a colorized Colr instance. """
label_args = label_args or {'fore': 'red'}
type_args = type_args or {'fore': 'yellow'}
type... | [
"def",
"as_colr",
"(",
"self",
",",
"label_args",
"=",
"None",
",",
"type_args",
"=",
"None",
",",
"type_val_args",
"=",
"None",
",",
"value_args",
"=",
"None",
",",
"spec_args",
"=",
"None",
")",
":",
"label_args",
"=",
"label_args",
"or",
"{",
"'fore'"... | Like __str__, except it returns a colorized Colr instance. | [
"Like",
"__str__",
"except",
"it",
"returns",
"a",
"colorized",
"Colr",
"instance",
"."
] | python | train | 40.969697 |
pgmpy/pgmpy | pgmpy/models/LinearGaussianBayesianNetwork.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/models/LinearGaussianBayesianNetwork.py#L23-L64 | def add_cpds(self, *cpds):
"""
Add linear Gaussian CPD (Conditional Probability Distribution)
to the Bayesian Model.
Parameters
----------
cpds : instances of LinearGaussianCPD
List of LinearGaussianCPDs which will be associated with the model
Exam... | [
"def",
"add_cpds",
"(",
"self",
",",
"*",
"cpds",
")",
":",
"for",
"cpd",
"in",
"cpds",
":",
"if",
"not",
"isinstance",
"(",
"cpd",
",",
"LinearGaussianCPD",
")",
":",
"raise",
"ValueError",
"(",
"'Only LinearGaussianCPD can be added.'",
")",
"if",
"set",
... | Add linear Gaussian CPD (Conditional Probability Distribution)
to the Bayesian Model.
Parameters
----------
cpds : instances of LinearGaussianCPD
List of LinearGaussianCPDs which will be associated with the model
Examples
--------
>>> from pgmpy.mo... | [
"Add",
"linear",
"Gaussian",
"CPD",
"(",
"Conditional",
"Probability",
"Distribution",
")",
"to",
"the",
"Bayesian",
"Model",
"."
] | python | train | 38.5 |
textX/textX | textx/metamodel.py | https://github.com/textX/textX/blob/5796ac38116ad86584392dbecdbf923ede746361/textx/metamodel.py#L536-L575 | def internal_model_from_file(
self, file_name, encoding='utf-8', debug=None,
pre_ref_resolution_callback=None, is_main_model=True):
"""
Instantiates model from the given file.
:param pre_ref_resolution_callback: called before references are
resolved. This c... | [
"def",
"internal_model_from_file",
"(",
"self",
",",
"file_name",
",",
"encoding",
"=",
"'utf-8'",
",",
"debug",
"=",
"None",
",",
"pre_ref_resolution_callback",
"=",
"None",
",",
"is_main_model",
"=",
"True",
")",
":",
"model",
"=",
"None",
"callback",
"=",
... | Instantiates model from the given file.
:param pre_ref_resolution_callback: called before references are
resolved. This can be useful to manage models distributed
across files (scoping) | [
"Instantiates",
"model",
"from",
"the",
"given",
"file",
".",
":",
"param",
"pre_ref_resolution_callback",
":",
"called",
"before",
"references",
"are",
"resolved",
".",
"This",
"can",
"be",
"useful",
"to",
"manage",
"models",
"distributed",
"across",
"files",
"... | python | train | 44.05 |
pyblish/pyblish-qml | pyblish_qml/ipc/formatting.py | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/ipc/formatting.py#L97-L110 | def format_error(error):
"""Serialise exception"""
formatted = {"message": str(error)}
if hasattr(error, "traceback"):
fname, line_no, func, exc = error.traceback
formatted.update({
"fname": fname,
"line_number": line_no,
"func": func,
"exc": ... | [
"def",
"format_error",
"(",
"error",
")",
":",
"formatted",
"=",
"{",
"\"message\"",
":",
"str",
"(",
"error",
")",
"}",
"if",
"hasattr",
"(",
"error",
",",
"\"traceback\"",
")",
":",
"fname",
",",
"line_no",
",",
"func",
",",
"exc",
"=",
"error",
".... | Serialise exception | [
"Serialise",
"exception"
] | python | train | 24.5 |
explosion/spaCy | spacy/util.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L176-L190 | def load_model_from_init_py(init_file, **overrides):
"""Helper function to use in the `load()` method of a model package's
__init__.py.
init_file (unicode): Path to model's __init__.py, i.e. `__file__`.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Langu... | [
"def",
"load_model_from_init_py",
"(",
"init_file",
",",
"*",
"*",
"overrides",
")",
":",
"model_path",
"=",
"Path",
"(",
"init_file",
")",
".",
"parent",
"meta",
"=",
"get_model_meta",
"(",
"model_path",
")",
"data_dir",
"=",
"\"%s_%s-%s\"",
"%",
"(",
"meta... | Helper function to use in the `load()` method of a model package's
__init__.py.
init_file (unicode): Path to model's __init__.py, i.e. `__file__`.
**overrides: Specific overrides, like pipeline components to disable.
RETURNS (Language): `Language` class with loaded model. | [
"Helper",
"function",
"to",
"use",
"in",
"the",
"load",
"()",
"method",
"of",
"a",
"model",
"package",
"s",
"__init__",
".",
"py",
"."
] | python | train | 46.333333 |
kata198/indexedredis | IndexedRedis/__init__.py | https://github.com/kata198/indexedredis/blob/f9c85adcf5218dac25acb06eedc63fc2950816fa/IndexedRedis/__init__.py#L1685-L1702 | def random(self, cascadeFetch=False):
'''
Random - Returns a random record in current filterset.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@return - Instance of M... | [
"def",
"random",
"(",
"self",
",",
"cascadeFetch",
"=",
"False",
")",
":",
"matchedKeys",
"=",
"list",
"(",
"self",
".",
"getPrimaryKeys",
"(",
")",
")",
"obj",
"=",
"None",
"# Loop so we don't return None when there are items, if item is deleted between getting key and... | Random - Returns a random record in current filterset.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@return - Instance of Model object, or None if no items math current f... | [
"Random",
"-",
"Returns",
"a",
"random",
"record",
"in",
"current",
"filterset",
"."
] | python | valid | 38.333333 |
ethereum/pyethereum | ethereum/vm.py | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/vm.py#L202-L242 | def vm_trace(ext, msg, compustate, opcode, pushcache, tracer=log_vm_op):
"""
This diverges from normal logging, as we use the logging namespace
only to decide which features get logged in 'eth.vm.op'
i.e. tracing can not be activated by activating a sub
like 'eth.vm.op.stack'
"""
op, in_arg... | [
"def",
"vm_trace",
"(",
"ext",
",",
"msg",
",",
"compustate",
",",
"opcode",
",",
"pushcache",
",",
"tracer",
"=",
"log_vm_op",
")",
":",
"op",
",",
"in_args",
",",
"out_args",
",",
"fee",
"=",
"opcodes",
".",
"opcodes",
"[",
"opcode",
"]",
"trace_data... | This diverges from normal logging, as we use the logging namespace
only to decide which features get logged in 'eth.vm.op'
i.e. tracing can not be activated by activating a sub
like 'eth.vm.op.stack' | [
"This",
"diverges",
"from",
"normal",
"logging",
"as",
"we",
"use",
"the",
"logging",
"namespace",
"only",
"to",
"decide",
"which",
"features",
"get",
"logged",
"in",
"eth",
".",
"vm",
".",
"op",
"i",
".",
"e",
".",
"tracing",
"can",
"not",
"be",
"acti... | python | train | 43.219512 |
PeerAssets/pypeerassets | pypeerassets/provider/explorer.py | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L106-L109 | def getaddress(self, address: str) -> dict:
'''Returns information for given address.'''
return cast(dict, self.ext_fetch('getaddress/' + address)) | [
"def",
"getaddress",
"(",
"self",
",",
"address",
":",
"str",
")",
"->",
"dict",
":",
"return",
"cast",
"(",
"dict",
",",
"self",
".",
"ext_fetch",
"(",
"'getaddress/'",
"+",
"address",
")",
")"
] | Returns information for given address. | [
"Returns",
"information",
"for",
"given",
"address",
"."
] | python | train | 40.25 |
hobson/aima | aima/nlp.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/nlp.py#L166-L171 | def predictor(self, (i, j, A, alpha, Bb)):
"Add to chart any rules for B that could help extend this edge."
B = Bb[0]
if B in self.grammar.rules:
for rhs in self.grammar.rewrites_for(B):
self.add_edge([j, j, B, [], rhs]) | [
"def",
"predictor",
"(",
"self",
",",
"(",
"i",
",",
"j",
",",
"A",
",",
"alpha",
",",
"Bb",
")",
")",
":",
"B",
"=",
"Bb",
"[",
"0",
"]",
"if",
"B",
"in",
"self",
".",
"grammar",
".",
"rules",
":",
"for",
"rhs",
"in",
"self",
".",
"grammar... | Add to chart any rules for B that could help extend this edge. | [
"Add",
"to",
"chart",
"any",
"rules",
"for",
"B",
"that",
"could",
"help",
"extend",
"this",
"edge",
"."
] | python | valid | 44.5 |
hearsaycorp/normalize | normalize/property/meta.py | https://github.com/hearsaycorp/normalize/blob/8b36522ddca6d41b434580bd848f3bdaa7a999c8/normalize/property/meta.py#L36-L113 | def has(selfie, self, args, kwargs):
"""This is called 'has' but is called indirectly. Each Property sub-class
is installed with this function which replaces their __new__.
It is called 'has', because it runs during property declaration, processes
the arguments and is responsible for returning an appr... | [
"def",
"has",
"(",
"selfie",
",",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"args",
":",
"raise",
"exc",
".",
"PositionalArgumentsProhibited",
"(",
")",
"extra_traits",
"=",
"set",
"(",
"kwargs",
".",
"pop",
"(",
"'traits'",
",",
"tuple",
"("... | This is called 'has' but is called indirectly. Each Property sub-class
is installed with this function which replaces their __new__.
It is called 'has', because it runs during property declaration, processes
the arguments and is responsible for returning an appropriate Property
subclass. As such it i... | [
"This",
"is",
"called",
"has",
"but",
"is",
"called",
"indirectly",
".",
"Each",
"Property",
"sub",
"-",
"class",
"is",
"installed",
"with",
"this",
"function",
"which",
"replaces",
"their",
"__new__",
"."
] | python | train | 40.128205 |
StackStorm/pybind | pybind/slxos/v17s_1_02/mpls_state/ldp/fec/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_state/ldp/fec/__init__.py#L269-L290 | def _set_ldp_fec_prefix_prefix(self, v, load=False):
"""
Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_fec_prefix_prefix is considered as a priv... | [
"def",
"_set_ldp_fec_prefix_prefix",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | Setter method for ldp_fec_prefix_prefix, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_prefix_prefix (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_fec_prefix_prefix is considered as a private
method. Backends looking to populate this variable should... | [
"Setter",
"method",
"for",
"ldp_fec_prefix_prefix",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_state",
"/",
"ldp",
"/",
"fec",
"/",
"ldp_fec_prefix_prefix",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
... | python | train | 85 |
LISE-B26/pylabcontrol | build/lib/pylabcontrol/src/core/scripts.py | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L340-L351 | def remaining_time(self):
"""
estimates the time remaining until script is finished
"""
elapsed_time = (datetime.datetime.now() - self.start_time).total_seconds()
# safety to avoid devision by zero
if self.progress == 0:
self.progress = 1
estimated_to... | [
"def",
"remaining_time",
"(",
"self",
")",
":",
"elapsed_time",
"=",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"start_time",
")",
".",
"total_seconds",
"(",
")",
"# safety to avoid devision by zero",
"if",
"self",
".",
"progre... | estimates the time remaining until script is finished | [
"estimates",
"the",
"time",
"remaining",
"until",
"script",
"is",
"finished"
] | python | train | 37.083333 |
square/pylink | pylink/threads.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/threads.py#L41-L56 | def run(self):
"""Runs the thread.
Args:
self (ThreadReturn): the ``ThreadReturn`` instance
Returns:
``None``
"""
target = getattr(self, '_Thread__target', getattr(self, '_target', None))
args = getattr(self, '_Thread__args', getattr(self, '_args', N... | [
"def",
"run",
"(",
"self",
")",
":",
"target",
"=",
"getattr",
"(",
"self",
",",
"'_Thread__target'",
",",
"getattr",
"(",
"self",
",",
"'_target'",
",",
"None",
")",
")",
"args",
"=",
"getattr",
"(",
"self",
",",
"'_Thread__args'",
",",
"getattr",
"("... | Runs the thread.
Args:
self (ThreadReturn): the ``ThreadReturn`` instance
Returns:
``None`` | [
"Runs",
"the",
"thread",
"."
] | python | train | 30.9375 |
ebroecker/canmatrix | src/canmatrix/canmatrix.py | https://github.com/ebroecker/canmatrix/blob/d6150b7a648350f051a11c431e9628308c8d5593/src/canmatrix/canmatrix.py#L523-L548 | def unpack_bitstring(length, is_float, is_signed, bits):
# type: (int, bool, bool, typing.Any) -> typing.Union[float, int]
"""
returns a value calculated from bits
:param length: length of signal in bits
:param is_float: value is float
:param bits: value as bits (array/iterable)
:param is_si... | [
"def",
"unpack_bitstring",
"(",
"length",
",",
"is_float",
",",
"is_signed",
",",
"bits",
")",
":",
"# type: (int, bool, bool, typing.Any) -> typing.Union[float, int]",
"if",
"is_float",
":",
"types",
"=",
"{",
"32",
":",
"'>f'",
",",
"64",
":",
"'>d'",
"}",
"fl... | returns a value calculated from bits
:param length: length of signal in bits
:param is_float: value is float
:param bits: value as bits (array/iterable)
:param is_signed: value is signed
:return: | [
"returns",
"a",
"value",
"calculated",
"from",
"bits",
":",
"param",
"length",
":",
"length",
"of",
"signal",
"in",
"bits",
":",
"param",
"is_float",
":",
"value",
"is",
"float",
":",
"param",
"bits",
":",
"value",
"as",
"bits",
"(",
"array",
"/",
"ite... | python | train | 26.923077 |
vertexproject/synapse | synapse/lib/crypto/tinfoil.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/crypto/tinfoil.py#L35-L51 | def enc(self, byts, asscd=None):
'''
Encrypt the given bytes and return an envelope dict in msgpack form.
Args:
byts (bytes): The message to be encrypted.
asscd (bytes): Extra data that needs to be authenticated (but not encrypted).
Returns:
bytes: T... | [
"def",
"enc",
"(",
"self",
",",
"byts",
",",
"asscd",
"=",
"None",
")",
":",
"iv",
"=",
"os",
".",
"urandom",
"(",
"16",
")",
"encryptor",
"=",
"AESGCM",
"(",
"self",
".",
"ekey",
")",
"byts",
"=",
"encryptor",
".",
"encrypt",
"(",
"iv",
",",
"... | Encrypt the given bytes and return an envelope dict in msgpack form.
Args:
byts (bytes): The message to be encrypted.
asscd (bytes): Extra data that needs to be authenticated (but not encrypted).
Returns:
bytes: The encrypted message. This is a msgpacked dictionary
... | [
"Encrypt",
"the",
"given",
"bytes",
"and",
"return",
"an",
"envelope",
"dict",
"in",
"msgpack",
"form",
"."
] | python | train | 37.529412 |
limodou/uliweb | uliweb/i18n/pygettext.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/i18n/pygettext.py#L353-L380 | def getFilesForName(name):
"""Get a list of module files for a filename, a module or package name,
or a directory.
"""
if not os.path.exists(name):
# check for glob chars
if containsAny(name, "*?[]"):
files = glob.glob(name)
list = []
for file in files... | [
"def",
"getFilesForName",
"(",
"name",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"# check for glob chars",
"if",
"containsAny",
"(",
"name",
",",
"\"*?[]\"",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"name"... | Get a list of module files for a filename, a module or package name,
or a directory. | [
"Get",
"a",
"list",
"of",
"module",
"files",
"for",
"a",
"filename",
"a",
"module",
"or",
"package",
"name",
"or",
"a",
"directory",
"."
] | python | train | 26.571429 |
reflexsc/reflex | src/rfxmon/__init__.py | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/src/rfxmon/__init__.py#L222-L235 | def worker_thread(self):
"""
The primary worker thread--this thread pulls from the monitor queue and
runs the monitor, submitting the results to the handler queue.
Calls a sub method based on type of monitor.
"""
self.thread_debug("Starting monitor thread")
while... | [
"def",
"worker_thread",
"(",
"self",
")",
":",
"self",
".",
"thread_debug",
"(",
"\"Starting monitor thread\"",
")",
"while",
"not",
"self",
".",
"thread_stopper",
".",
"is_set",
"(",
")",
":",
"mon",
"=",
"self",
".",
"workers_queue",
".",
"get",
"(",
")"... | The primary worker thread--this thread pulls from the monitor queue and
runs the monitor, submitting the results to the handler queue.
Calls a sub method based on type of monitor. | [
"The",
"primary",
"worker",
"thread",
"--",
"this",
"thread",
"pulls",
"from",
"the",
"monitor",
"queue",
"and",
"runs",
"the",
"monitor",
"submitting",
"the",
"results",
"to",
"the",
"handler",
"queue",
"."
] | python | train | 46.357143 |
python-visualization/folium | folium/features.py | https://github.com/python-visualization/folium/blob/8595240517135d1637ca4cf7cc624045f1d911b3/folium/features.py#L147-L188 | def render(self, **kwargs):
"""Renders the HTML representation of the element."""
self.json = json.dumps(self.data)
self._parent.html.add_child(Element(Template("""
<div id="{{this.get_name()}}"></div>
""").render(this=self, kwargs=kwargs)), name=self.get_name())
... | [
"def",
"render",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"json",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"data",
")",
"self",
".",
"_parent",
".",
"html",
".",
"add_child",
"(",
"Element",
"(",
"Template",
"(",
"\"\"\"\n ... | Renders the HTML representation of the element. | [
"Renders",
"the",
"HTML",
"representation",
"of",
"the",
"element",
"."
] | python | train | 42 |
zhmcclient/python-zhmcclient | zhmcclient/_manager.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L427-L455 | def _matches_filters(self, obj, filter_args):
"""
Return a boolean indicating whether a resource object matches a set
of filter arguments.
This is used for client-side filtering.
Depending on the properties specified in the filter arguments, this
method retrieves the res... | [
"def",
"_matches_filters",
"(",
"self",
",",
"obj",
",",
"filter_args",
")",
":",
"if",
"filter_args",
"is",
"not",
"None",
":",
"for",
"prop_name",
"in",
"filter_args",
":",
"prop_match",
"=",
"filter_args",
"[",
"prop_name",
"]",
"if",
"not",
"self",
"."... | Return a boolean indicating whether a resource object matches a set
of filter arguments.
This is used for client-side filtering.
Depending on the properties specified in the filter arguments, this
method retrieves the resource properties from the HMC.
Parameters:
obj... | [
"Return",
"a",
"boolean",
"indicating",
"whether",
"a",
"resource",
"object",
"matches",
"a",
"set",
"of",
"filter",
"arguments",
".",
"This",
"is",
"used",
"for",
"client",
"-",
"side",
"filtering",
"."
] | python | train | 32.586207 |
edx/XBlock | xblock/runtime.py | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L1023-L1048 | def handle(self, block, handler_name, request, suffix=''):
"""
Handles any calls to the specified `handler_name`.
Provides a fallback handler if the specified handler isn't found.
:param handler_name: The name of the handler to call
:param request: The request to handle
... | [
"def",
"handle",
"(",
"self",
",",
"block",
",",
"handler_name",
",",
"request",
",",
"suffix",
"=",
"''",
")",
":",
"handler",
"=",
"getattr",
"(",
"block",
",",
"handler_name",
",",
"None",
")",
"if",
"handler",
"and",
"getattr",
"(",
"handler",
",",... | Handles any calls to the specified `handler_name`.
Provides a fallback handler if the specified handler isn't found.
:param handler_name: The name of the handler to call
:param request: The request to handle
:type request: webob.Request
:param suffix: The remainder of the url, ... | [
"Handles",
"any",
"calls",
"to",
"the",
"specified",
"handler_name",
"."
] | python | train | 45.384615 |
urinieto/msaf | msaf/algorithms/fmc2d/xmeans.py | https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/algorithms/fmc2d/xmeans.py#L84-L131 | def estimate_K_knee(self, th=.015, maxK=12):
"""Estimates the K using K-means and BIC, by sweeping various K and
choosing the optimal BIC."""
# Sweep K-means
if self.X.shape[0] < maxK:
maxK = self.X.shape[0]
if maxK < 2:
maxK = 2
K = np.arange(... | [
"def",
"estimate_K_knee",
"(",
"self",
",",
"th",
"=",
".015",
",",
"maxK",
"=",
"12",
")",
":",
"# Sweep K-means",
"if",
"self",
".",
"X",
".",
"shape",
"[",
"0",
"]",
"<",
"maxK",
":",
"maxK",
"=",
"self",
".",
"X",
".",
"shape",
"[",
"0",
"]... | Estimates the K using K-means and BIC, by sweeping various K and
choosing the optimal BIC. | [
"Estimates",
"the",
"K",
"using",
"K",
"-",
"means",
"and",
"BIC",
"by",
"sweeping",
"various",
"K",
"and",
"choosing",
"the",
"optimal",
"BIC",
"."
] | python | test | 30.583333 |
ml4ai/delphi | delphi/utils/misc.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/misc.py#L30-L38 | def multiple_replace(d: Dict[str, str], text: str) -> str:
""" Performs string replacement from dict in a single pass. Taken from
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html
"""
# Create a regular expression from all of the dictionary keys
regex = re.compile("|".join(m... | [
"def",
"multiple_replace",
"(",
"d",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"text",
":",
"str",
")",
"->",
"str",
":",
"# Create a regular expression from all of the dictionary keys",
"regex",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"("... | Performs string replacement from dict in a single pass. Taken from
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s15.html | [
"Performs",
"string",
"replacement",
"from",
"dict",
"in",
"a",
"single",
"pass",
".",
"Taken",
"from",
"https",
":",
"//",
"www",
".",
"oreilly",
".",
"com",
"/",
"library",
"/",
"view",
"/",
"python",
"-",
"cookbook",
"/",
"0596001673",
"/",
"ch03s15",... | python | train | 52 |
saltstack/salt | salt/cache/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/__init__.py#L227-L244 | def list(self, bank):
'''
Lists entries stored in the specified bank.
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:return:
An iterable object containing all bank entries. Returns an empty
... | [
"def",
"list",
"(",
"self",
",",
"bank",
")",
":",
"fun",
"=",
"'{0}.list'",
".",
"format",
"(",
"self",
".",
"driver",
")",
"return",
"self",
".",
"modules",
"[",
"fun",
"]",
"(",
"bank",
",",
"*",
"*",
"self",
".",
"_kwargs",
")"
] | Lists entries stored in the specified bank.
:param bank:
The name of the location inside the cache which will hold the key
and its associated data.
:return:
An iterable object containing all bank entries. Returns an empty
iterator if the bank doesn't exi... | [
"Lists",
"entries",
"stored",
"in",
"the",
"specified",
"bank",
"."
] | python | train | 35.222222 |
push-things/django-th | django_th/services/services.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/services/services.py#L91-L107 | def set_content(self, data):
"""
handle the content from the data
:param data: contains the data from the provider
:type data: dict
:rtype: string
"""
content = self._get_content(data, 'content')
if content == '':
content = sel... | [
"def",
"set_content",
"(",
"self",
",",
"data",
")",
":",
"content",
"=",
"self",
".",
"_get_content",
"(",
"data",
",",
"'content'",
")",
"if",
"content",
"==",
"''",
":",
"content",
"=",
"self",
".",
"_get_content",
"(",
"data",
",",
"'summary_detail'"... | handle the content from the data
:param data: contains the data from the provider
:type data: dict
:rtype: string | [
"handle",
"the",
"content",
"from",
"the",
"data",
":",
"param",
"data",
":",
"contains",
"the",
"data",
"from",
"the",
"provider",
":",
"type",
"data",
":",
"dict",
":",
"rtype",
":",
"string"
] | python | train | 28.411765 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L130-L145 | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'charset_size':
if v not in (1, 2, 4):
raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v))
elif k == 'wide_charset_size... | [
"def",
"validate_options",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"super",
"(",
")",
".",
"validate_options",
"(",
"k",
",",
"v",
")",
"if",
"k",
"==",
"'charset_size'",
":",
"if",
"v",
"not",
"in",
"(",
"1",
",",
"2",
",",
"4",
")",
":",
... | Validate options. | [
"Validate",
"options",
"."
] | python | train | 49.375 |
mfcloud/python-zvm-sdk | smtLayer/vmUtils.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/vmUtils.py#L955-L1016 | def waitForOSState(rh, userid, desiredState, maxQueries=90, sleepSecs=5):
"""
Wait for the virtual OS to go into the indicated state.
Input:
Request Handle
userid whose state is to be monitored
Desired state, 'up' or 'down', case sensitive
Maximum attempts to wait for desired st... | [
"def",
"waitForOSState",
"(",
"rh",
",",
"userid",
",",
"desiredState",
",",
"maxQueries",
"=",
"90",
",",
"sleepSecs",
"=",
"5",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter vmUtils.waitForOSState, userid: \"",
"+",
"userid",
"+",
"\" state: \"",
"+",
"d... | Wait for the virtual OS to go into the indicated state.
Input:
Request Handle
userid whose state is to be monitored
Desired state, 'up' or 'down', case sensitive
Maximum attempts to wait for desired state before giving up
Sleep duration between waits
Output:
Dictionar... | [
"Wait",
"for",
"the",
"virtual",
"OS",
"to",
"go",
"into",
"the",
"indicated",
"state",
"."
] | python | train | 30.790323 |
brbsix/subnuker | subnuker.py | https://github.com/brbsix/subnuker/blob/a94260a6e84b790a9e39e0b1793443ffd4e1f496/subnuker.py#L308-L318 | def search(self):
"""Return list of cells to be removed."""
matches = []
for index, cell in enumerate(self.cells):
for pattern in Config.patterns:
if ismatch(cell, pattern):
matches.append(index)
break
return matches | [
"def",
"search",
"(",
"self",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"index",
",",
"cell",
"in",
"enumerate",
"(",
"self",
".",
"cells",
")",
":",
"for",
"pattern",
"in",
"Config",
".",
"patterns",
":",
"if",
"ismatch",
"(",
"cell",
",",
"patte... | Return list of cells to be removed. | [
"Return",
"list",
"of",
"cells",
"to",
"be",
"removed",
"."
] | python | train | 28 |
apache/incubator-superset | superset/views/core.py | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L126-L143 | def check_slice_perms(self, slice_id):
"""
Check if user can access a cached response from slice_json.
This function takes `self` since it must have the same signature as the
the decorated method.
"""
form_data, slc = get_form_data(slice_id, use_slice_data=True)
datasource_type = slc.datas... | [
"def",
"check_slice_perms",
"(",
"self",
",",
"slice_id",
")",
":",
"form_data",
",",
"slc",
"=",
"get_form_data",
"(",
"slice_id",
",",
"use_slice_data",
"=",
"True",
")",
"datasource_type",
"=",
"slc",
".",
"datasource",
".",
"type",
"datasource_id",
"=",
... | Check if user can access a cached response from slice_json.
This function takes `self` since it must have the same signature as the
the decorated method. | [
"Check",
"if",
"user",
"can",
"access",
"a",
"cached",
"response",
"from",
"slice_json",
"."
] | python | train | 32.111111 |
AltSchool/dynamic-rest | dynamic_rest/metadata.py | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/metadata.py#L22-L37 | def determine_metadata(self, request, view):
"""Adds `properties` and `features` to the metadata response."""
metadata = super(
DynamicMetadata,
self).determine_metadata(
request,
view)
metadata['features'] = getattr(view, 'features', [])
i... | [
"def",
"determine_metadata",
"(",
"self",
",",
"request",
",",
"view",
")",
":",
"metadata",
"=",
"super",
"(",
"DynamicMetadata",
",",
"self",
")",
".",
"determine_metadata",
"(",
"request",
",",
"view",
")",
"metadata",
"[",
"'features'",
"]",
"=",
"geta... | Adds `properties` and `features` to the metadata response. | [
"Adds",
"properties",
"and",
"features",
"to",
"the",
"metadata",
"response",
"."
] | python | train | 46.375 |
globus/globus-cli | globus_cli/commands/config/filename.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/config/filename.py#L10-L20 | def filename_command():
"""
Executor for `globus config filename`
"""
try:
config = get_config_obj(file_error=True)
except IOError as e:
safeprint(e, write_to_stderr=True)
click.get_current_context().exit(1)
else:
safeprint(config.filename) | [
"def",
"filename_command",
"(",
")",
":",
"try",
":",
"config",
"=",
"get_config_obj",
"(",
"file_error",
"=",
"True",
")",
"except",
"IOError",
"as",
"e",
":",
"safeprint",
"(",
"e",
",",
"write_to_stderr",
"=",
"True",
")",
"click",
".",
"get_current_con... | Executor for `globus config filename` | [
"Executor",
"for",
"globus",
"config",
"filename"
] | python | train | 26 |
Bogdanp/dramatiq | dramatiq/actor.py | https://github.com/Bogdanp/dramatiq/blob/a8cc2728478e794952a5a50c3fb19ec455fe91b6/dramatiq/actor.py#L157-L225 | def actor(fn=None, *, actor_class=Actor, actor_name=None, queue_name="default", priority=0, broker=None, **options):
"""Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x10... | [
"def",
"actor",
"(",
"fn",
"=",
"None",
",",
"*",
",",
"actor_class",
"=",
"Actor",
",",
"actor_name",
"=",
"None",
",",
"queue_name",
"=",
"\"default\"",
",",
"priority",
"=",
"0",
",",
"broker",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"d... | Declare an actor.
Examples:
>>> import dramatiq
>>> @dramatiq.actor
... def add(x, y):
... print(x + y)
...
>>> add
Actor(<function add at 0x106c6d488>, queue_name='default', actor_name='add')
>>> add(1, 2)
3
>>> add.send(1, 2)
Message(
... | [
"Declare",
"an",
"actor",
"."
] | python | train | 35.318841 |
apache/incubator-mxnet | example/gluon/lipnet/data_loader.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/lipnet/data_loader.py#L45-L71 | def _list_images(self, root):
"""
Description : generate list for lip images
"""
self.labels = []
self.items = []
valid_unseen_sub_idx = [1, 2, 20, 22]
skip_sub_idx = [21]
if self._mode == 'train':
sub_idx = ['s' + str(i) for i in range(1, 35... | [
"def",
"_list_images",
"(",
"self",
",",
"root",
")",
":",
"self",
".",
"labels",
"=",
"[",
"]",
"self",
".",
"items",
"=",
"[",
"]",
"valid_unseen_sub_idx",
"=",
"[",
"1",
",",
"2",
",",
"20",
",",
"22",
"]",
"skip_sub_idx",
"=",
"[",
"21",
"]",... | Description : generate list for lip images | [
"Description",
":",
"generate",
"list",
"for",
"lip",
"images"
] | python | train | 33 |
olt/scriptine | scriptine/_path.py | https://github.com/olt/scriptine/blob/f4cfea939f2f3ad352b24c5f6410f79e78723d0e/scriptine/_path.py#L252-L257 | def joinpath(self, *args):
""" Join two or more path components, adding a separator
character (os.sep) if needed. Returns a new path
object.
"""
return self.__class__(os.path.join(self, *args)) | [
"def",
"joinpath",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
",",
"*",
"args",
")",
")"
] | Join two or more path components, adding a separator
character (os.sep) if needed. Returns a new path
object. | [
"Join",
"two",
"or",
"more",
"path",
"components",
"adding",
"a",
"separator",
"character",
"(",
"os",
".",
"sep",
")",
"if",
"needed",
".",
"Returns",
"a",
"new",
"path",
"object",
"."
] | python | train | 38.166667 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/shuffler.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/shuffler.py#L510-L543 | def write(self, data):
"""Write data.
Args:
data: actual data yielded from handler. Type is writer-specific.
"""
ctx = context.get()
if len(data) != 2:
logging.error("Got bad tuple of length %d (2-tuple expected): %s",
len(data), data)
try:
key = str(data[... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"ctx",
"=",
"context",
".",
"get",
"(",
")",
"if",
"len",
"(",
"data",
")",
"!=",
"2",
":",
"logging",
".",
"error",
"(",
"\"Got bad tuple of length %d (2-tuple expected): %s\"",
",",
"len",
"(",
"data"... | Write data.
Args:
data: actual data yielded from handler. Type is writer-specific. | [
"Write",
"data",
"."
] | python | train | 31.852941 |
davgeo/clear | clear/util.py | https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/util.py#L382-L406 | def ArchiveProcessedFile(filePath, archiveDir):
"""
Move file from given file path to archive directory. Note the archive
directory is relative to the file path directory.
Parameters
----------
filePath : string
File path
archiveDir : string
Name of archive directory
"""
targetDir = ... | [
"def",
"ArchiveProcessedFile",
"(",
"filePath",
",",
"archiveDir",
")",
":",
"targetDir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filePath",
")",
",",
"archiveDir",
")",
"goodlogging",
".",
"Log",
".",
"Info",
... | Move file from given file path to archive directory. Note the archive
directory is relative to the file path directory.
Parameters
----------
filePath : string
File path
archiveDir : string
Name of archive directory | [
"Move",
"file",
"from",
"given",
"file",
"path",
"to",
"archive",
"directory",
".",
"Note",
"the",
"archive",
"directory",
"is",
"relative",
"to",
"the",
"file",
"path",
"directory",
"."
] | python | train | 35.48 |
romana/vpc-router | vpcrouter/monitor/plugins/multi.py | https://github.com/romana/vpc-router/blob/d696c2e023f1111ceb61f9c6fbabfafed8e14040/vpcrouter/monitor/plugins/multi.py#L327-L342 | def stop(self):
"""
Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop.
"""
super(Multi, self).stop()
self.monitor_thread.join()
logging.info("Multi-plugin health m... | [
"def",
"stop",
"(",
"self",
")",
":",
"super",
"(",
"Multi",
",",
"self",
")",
".",
"stop",
"(",
")",
"self",
".",
"monitor_thread",
".",
"join",
"(",
")",
"logging",
".",
"info",
"(",
"\"Multi-plugin health monitor: Stopping plugins\"",
")",
"for",
"p",
... | Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop. | [
"Stop",
"the",
"monitoring",
"thread",
"of",
"the",
"plugin",
"."
] | python | train | 27.8125 |
paolodragone/pymzn | pymzn/dzn/marsh.py | https://github.com/paolodragone/pymzn/blob/35b04cfb244918551649b9bb8a0ab65d37c31fe4/pymzn/dzn/marsh.py#L215-L247 | def val2dzn(val, wrap=True):
"""Serializes a value into its dzn representation.
The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``.
Parameters
----------
val
The value to serialize
wrap : bool
Whether to wrap the serialized value.
Returns
-------
... | [
"def",
"val2dzn",
"(",
"val",
",",
"wrap",
"=",
"True",
")",
":",
"if",
"_is_value",
"(",
"val",
")",
":",
"dzn_val",
"=",
"_dzn_val",
"(",
"val",
")",
"elif",
"_is_set",
"(",
"val",
")",
":",
"dzn_val",
"=",
"_dzn_set",
"(",
"val",
")",
"elif",
... | Serializes a value into its dzn representation.
The supported types are ``bool``, ``int``, ``float``, ``set``, ``array``.
Parameters
----------
val
The value to serialize
wrap : bool
Whether to wrap the serialized value.
Returns
-------
str
The serialized dzn r... | [
"Serializes",
"a",
"value",
"into",
"its",
"dzn",
"representation",
"."
] | python | train | 23.151515 |
gtalarico/airtable-python-wrapper | airtable/airtable.py | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L512-L534 | def delete_by_field(self, field_name, field_value, **options):
"""
Deletes first record to match provided ``field_name`` and
``field_value``.
>>> record = airtable.delete_by_field('Employee Id', 'DD13332454')
Args:
field_name (``str``): Name of field to mat... | [
"def",
"delete_by_field",
"(",
"self",
",",
"field_name",
",",
"field_value",
",",
"*",
"*",
"options",
")",
":",
"record",
"=",
"self",
".",
"match",
"(",
"field_name",
",",
"field_value",
",",
"*",
"*",
"options",
")",
"record_url",
"=",
"self",
".",
... | Deletes first record to match provided ``field_name`` and
``field_value``.
>>> record = airtable.delete_by_field('Employee Id', 'DD13332454')
Args:
field_name (``str``): Name of field to match (column name).
field_value (``str``): Value of field to match.
... | [
"Deletes",
"first",
"record",
"to",
"match",
"provided",
"field_name",
"and",
"field_value",
".",
">>>",
"record",
"=",
"airtable",
".",
"delete_by_field",
"(",
"Employee",
"Id",
"DD13332454",
")",
"Args",
":",
"field_name",
"(",
"str",
")",
":",
"Name",
"of... | python | train | 38.130435 |
Erotemic/utool | utool/util_str.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L164-L169 | def bbox_str(bbox, pad=4, sep=', '):
r""" makes a string from an integer bounding box """
if bbox is None:
return 'None'
fmtstr = sep.join(['%' + six.text_type(pad) + 'd'] * 4)
return '(' + fmtstr % tuple(bbox) + ')' | [
"def",
"bbox_str",
"(",
"bbox",
",",
"pad",
"=",
"4",
",",
"sep",
"=",
"', '",
")",
":",
"if",
"bbox",
"is",
"None",
":",
"return",
"'None'",
"fmtstr",
"=",
"sep",
".",
"join",
"(",
"[",
"'%'",
"+",
"six",
".",
"text_type",
"(",
"pad",
")",
"+"... | r""" makes a string from an integer bounding box | [
"r",
"makes",
"a",
"string",
"from",
"an",
"integer",
"bounding",
"box"
] | python | train | 39.166667 |
mlavin/django-selectable | selectable/decorators.py | https://github.com/mlavin/django-selectable/blob/3d7b8db0526dd924a774c599f0c665eff98fb375/selectable/decorators.py#L16-L39 | def results_decorator(func):
"""
Helper for constructing simple decorators around Lookup.results.
func is a function which takes a request as the first parameter. If func
returns an HttpReponse it is returned otherwise the original Lookup.results
is returned.
"""
# Wrap function to maintian... | [
"def",
"results_decorator",
"(",
"func",
")",
":",
"# Wrap function to maintian the original doc string, etc",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorator",
"(",
"lookup_cls",
")",
":",
"# Construct a class decorator from the original function",
"original",
"=",
"look... | Helper for constructing simple decorators around Lookup.results.
func is a function which takes a request as the first parameter. If func
returns an HttpReponse it is returned otherwise the original Lookup.results
is returned. | [
"Helper",
"for",
"constructing",
"simple",
"decorators",
"around",
"Lookup",
".",
"results",
"."
] | python | train | 39.166667 |
basho/riak-python-client | riak/client/operations.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/client/operations.py#L192-L236 | def paginate_index(self, bucket, index, startkey, endkey=None,
max_results=1000, return_terms=None,
continuation=None, timeout=None, term_regex=None):
"""
Iterates over a paginated index query. This is equivalent to calling
:meth:`get_index` and then... | [
"def",
"paginate_index",
"(",
"self",
",",
"bucket",
",",
"index",
",",
"startkey",
",",
"endkey",
"=",
"None",
",",
"max_results",
"=",
"1000",
",",
"return_terms",
"=",
"None",
",",
"continuation",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"term_r... | Iterates over a paginated index query. This is equivalent to calling
:meth:`get_index` and then successively calling
:meth:`~riak.client.index_page.IndexPage.next_page` until all
results are exhausted.
Because limiting the result set is necessary to invoke pagination,
the ``max_... | [
"Iterates",
"over",
"a",
"paginated",
"index",
"query",
".",
"This",
"is",
"equivalent",
"to",
"calling",
":",
"meth",
":",
"get_index",
"and",
"then",
"successively",
"calling",
":",
"meth",
":",
"~riak",
".",
"client",
".",
"index_page",
".",
"IndexPage",
... | python | train | 45.977778 |
saltstack/salt | salt/modules/vsphere.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vsphere.py#L8315-L8359 | def _create_network_adapters(network_interfaces, parent=None):
'''
Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
the interfaces to be created for a virtual machine
network_interfaces
List of network interfaces and properties
parent
Parent object reference
... | [
"def",
"_create_network_adapters",
"(",
"network_interfaces",
",",
"parent",
"=",
"None",
")",
":",
"network_specs",
"=",
"[",
"]",
"nics_settings",
"=",
"[",
"]",
"keys",
"=",
"range",
"(",
"-",
"4000",
",",
"-",
"4050",
",",
"-",
"1",
")",
"if",
"net... | Returns a list of vim.vm.device.VirtualDeviceSpec objects representing
the interfaces to be created for a virtual machine
network_interfaces
List of network interfaces and properties
parent
Parent object reference
.. code-block: bash
interfaces:
adapter: 'Network ad... | [
"Returns",
"a",
"list",
"of",
"vim",
".",
"vm",
".",
"device",
".",
"VirtualDeviceSpec",
"objects",
"representing",
"the",
"interfaces",
"to",
"be",
"created",
"for",
"a",
"virtual",
"machine"
] | python | train | 39.177778 |
librosa/librosa | librosa/core/constantq.py | https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/constantq.py#L707-L740 | def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning,
filter_scale, norm, sparsity, hop_length=None,
window='hann'):
'''Generate the frequency domain constant-Q filter basis.'''
basis, lengths = filters.constant_q(sr,
f... | [
"def",
"__cqt_filter_fft",
"(",
"sr",
",",
"fmin",
",",
"n_bins",
",",
"bins_per_octave",
",",
"tuning",
",",
"filter_scale",
",",
"norm",
",",
"sparsity",
",",
"hop_length",
"=",
"None",
",",
"window",
"=",
"'hann'",
")",
":",
"basis",
",",
"lengths",
"... | Generate the frequency domain constant-Q filter basis. | [
"Generate",
"the",
"frequency",
"domain",
"constant",
"-",
"Q",
"filter",
"basis",
"."
] | python | test | 39.705882 |
Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L52-L85 | def json2space(in_x, name=ROOT):
"""
Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
... | [
"def",
"json2space",
"(",
"in_x",
",",
"name",
"=",
"ROOT",
")",
":",
"out_y",
"=",
"copy",
".",
"deepcopy",
"(",
"in_x",
")",
"if",
"isinstance",
"(",
"in_x",
",",
"dict",
")",
":",
"if",
"TYPE",
"in",
"in_x",
".",
"keys",
"(",
")",
":",
"_type"... | Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX. | [
"Change",
"json",
"to",
"search",
"space",
"in",
"hyperopt",
"."
] | python | train | 33.647059 |
nwilming/ocupy | ocupy/utils.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/utils.py#L205-L233 | def find_common_beginning(string_list, boundary_char = None):
"""Given a list of strings, finds finds the longest string that is common
to the *beginning* of all strings in the list.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char.
... | [
"def",
"find_common_beginning",
"(",
"string_list",
",",
"boundary_char",
"=",
"None",
")",
":",
"common",
"=",
"''",
"# by definition there is nothing common to 1 item...",
"if",
"len",
"(",
"string_list",
")",
">",
"1",
":",
"shortestLen",
"=",
"min",
"(",
"[",
... | Given a list of strings, finds finds the longest string that is common
to the *beginning* of all strings in the list.
boundary_char defines a boundary that must be preserved, so that the
common string removed must end with this char. | [
"Given",
"a",
"list",
"of",
"strings",
"finds",
"finds",
"the",
"longest",
"string",
"that",
"is",
"common",
"to",
"the",
"*",
"beginning",
"*",
"of",
"all",
"strings",
"in",
"the",
"list",
".",
"boundary_char",
"defines",
"a",
"boundary",
"that",
"must",
... | python | train | 31.827586 |
limodou/uliweb | uliweb/lib/werkzeug/utils.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/utils.py#L338-L365 | def redirect(location, code=302):
"""Return a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a r... | [
"def",
"redirect",
"(",
"location",
",",
"code",
"=",
"302",
")",
":",
"from",
"werkzeug",
".",
"wrappers",
"import",
"Response",
"display_location",
"=",
"escape",
"(",
"location",
")",
"if",
"isinstance",
"(",
"location",
",",
"text_type",
")",
":",
"fro... | Return a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a request
with defined If-Modified-Since... | [
"Return",
"a",
"response",
"object",
"(",
"a",
"WSGI",
"application",
")",
"that",
"if",
"called",
"redirects",
"the",
"client",
"to",
"the",
"target",
"location",
".",
"Supported",
"codes",
"are",
"301",
"302",
"303",
"305",
"and",
"307",
".",
"300",
"i... | python | train | 44.928571 |
HttpRunner/HttpRunner | httprunner/loader.py | https://github.com/HttpRunner/HttpRunner/blob/f259551bf9c8ba905eae5c1afcf2efea20ae0871/httprunner/loader.py#L297-L321 | def __extend_with_api_ref(raw_testinfo):
""" extend with api reference
Raises:
exceptions.ApiNotFound: api not found
"""
api_name = raw_testinfo["api"]
# api maybe defined in two types:
# 1, individual file: each file is corresponding to one api definition
# 2, api sets file: one ... | [
"def",
"__extend_with_api_ref",
"(",
"raw_testinfo",
")",
":",
"api_name",
"=",
"raw_testinfo",
"[",
"\"api\"",
"]",
"# api maybe defined in two types:",
"# 1, individual file: each file is corresponding to one api definition",
"# 2, api sets file: one file contains a list of api definit... | extend with api reference
Raises:
exceptions.ApiNotFound: api not found | [
"extend",
"with",
"api",
"reference"
] | python | train | 36.24 |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L467-L473 | def database_remove_types(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /database-xxxx/removeTypes API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes
"""
return DXHTTPRequest('/%s/removeTypes... | [
"def",
"database_remove_types",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/removeTypes'",
"%",
"object_id",
",",
"input_params",
",",
"always_... | Invokes the /database-xxxx/removeTypes API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Types#API-method%3A-%2Fclass-xxxx%2FremoveTypes | [
"Invokes",
"the",
"/",
"database",
"-",
"xxxx",
"/",
"removeTypes",
"API",
"method",
"."
] | python | train | 54.142857 |
biocore/burrito-fillings | bfillings/vsearch.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/vsearch.py#L225-L318 | def vsearch_dereplicate_exact_seqs(
fasta_filepath,
output_filepath,
output_uc=False,
working_dir=None,
strand="both",
maxuniquesize=None,
minuniquesize=None,
sizein=False,
sizeout=True,
log_name="derep.log",
HALT_EXEC=False):
""" Generates clusters and fasta file of
... | [
"def",
"vsearch_dereplicate_exact_seqs",
"(",
"fasta_filepath",
",",
"output_filepath",
",",
"output_uc",
"=",
"False",
",",
"working_dir",
"=",
"None",
",",
"strand",
"=",
"\"both\"",
",",
"maxuniquesize",
"=",
"None",
",",
"minuniquesize",
"=",
"None",
",",
"s... | Generates clusters and fasta file of
dereplicated subsequences
Parameters
----------
fasta_filepath : string
input filepath of fasta file to be dereplicated
output_filepath : string
write the dereplicated sequences to output_filepath
working_dir : ... | [
"Generates",
"clusters",
"and",
"fasta",
"file",
"of",
"dereplicated",
"subsequences"
] | python | train | 33.989362 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_hardware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_hardware.py#L24-L36 | def hardware_connector_sfp_breakout(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
connector = ET.SubElement(hardware, "connector")
name_key = ET.SubElem... | [
"def",
"hardware_connector_sfp_breakout",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hardware",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hardware\"",
",",
"xmlns",
"=",
"\"urn:b... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 43.076923 |
getsentry/rb | rb/clients.py | https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/clients.py#L129-L134 | def enqueue_command(self, command_name, args, options):
"""Enqueue a new command into this pipeline."""
assert_open(self)
promise = Promise()
self.commands.append((command_name, args, options, promise))
return promise | [
"def",
"enqueue_command",
"(",
"self",
",",
"command_name",
",",
"args",
",",
"options",
")",
":",
"assert_open",
"(",
"self",
")",
"promise",
"=",
"Promise",
"(",
")",
"self",
".",
"commands",
".",
"append",
"(",
"(",
"command_name",
",",
"args",
",",
... | Enqueue a new command into this pipeline. | [
"Enqueue",
"a",
"new",
"command",
"into",
"this",
"pipeline",
"."
] | python | train | 42 |
inasafe/inasafe | scripts/create_api_docs.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/scripts/create_api_docs.py#L52-L85 | def create_package_level_rst_index_file(
package_name, max_depth, modules, inner_packages=None):
"""Function for creating text for index for a package.
:param package_name: name of the package
:type package_name: str
:param max_depth: Value for max_depth in the index file.
:type max_depth:... | [
"def",
"create_package_level_rst_index_file",
"(",
"package_name",
",",
"max_depth",
",",
"modules",
",",
"inner_packages",
"=",
"None",
")",
":",
"if",
"inner_packages",
"is",
"None",
":",
"inner_packages",
"=",
"[",
"]",
"return_text",
"=",
"'Package::'",
"+",
... | Function for creating text for index for a package.
:param package_name: name of the package
:type package_name: str
:param max_depth: Value for max_depth in the index file.
:type max_depth: int
:param modules: list of module in the package.
:type modules: list
:return: A text for the co... | [
"Function",
"for",
"creating",
"text",
"for",
"index",
"for",
"a",
"package",
"."
] | python | train | 33.794118 |
captin411/ofxclient | ofxclient/cli.py | https://github.com/captin411/ofxclient/blob/4da2719f0ecbbf5eee62fb82c1b3b34ec955ee5e/ofxclient/cli.py#L226-L249 | def client_args_for_bank(bank_info, ofx_version):
"""
Return the client arguments to use for a particular Institution, as found
from ofxhome. This provides us with an extension point to override or
augment ofxhome data for specific institutions, such as those that
require specific User-Agent headers... | [
"def",
"client_args_for_bank",
"(",
"bank_info",
",",
"ofx_version",
")",
":",
"client_args",
"=",
"{",
"'ofx_version'",
":",
"str",
"(",
"ofx_version",
")",
"}",
"if",
"'ofx.discovercard.com'",
"in",
"bank_info",
"[",
"'url'",
"]",
":",
"# Discover needs no User-... | Return the client arguments to use for a particular Institution, as found
from ofxhome. This provides us with an extension point to override or
augment ofxhome data for specific institutions, such as those that
require specific User-Agent headers (or no User-Agent header).
:param bank_info: OFXHome ban... | [
"Return",
"the",
"client",
"arguments",
"to",
"use",
"for",
"a",
"particular",
"Institution",
"as",
"found",
"from",
"ofxhome",
".",
"This",
"provides",
"us",
"with",
"an",
"extension",
"point",
"to",
"override",
"or",
"augment",
"ofxhome",
"data",
"for",
"s... | python | train | 43.5 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dogpile_cache.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dogpile_cache.py#L121-L144 | def get_namespace(fn: Callable, namespace: Optional[str]) -> str:
"""
Returns a representation of a function's name (perhaps within a namespace),
like
.. code-block:: none
mymodule:MyClass.myclassfunc # with no namespace
mymodule:MyClass.myclassfunc|somenamespace # with a namespace
... | [
"def",
"get_namespace",
"(",
"fn",
":",
"Callable",
",",
"namespace",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"str",
":",
"# noqa",
"# See hidden attributes with dir(fn)",
"# noinspection PyUnresolvedReferences",
"return",
"\"{module}:{name}{extra}\"",
".",
"format... | Returns a representation of a function's name (perhaps within a namespace),
like
.. code-block:: none
mymodule:MyClass.myclassfunc # with no namespace
mymodule:MyClass.myclassfunc|somenamespace # with a namespace
Args:
fn: a function
namespace: an optional namespace, whi... | [
"Returns",
"a",
"representation",
"of",
"a",
"function",
"s",
"name",
"(",
"perhaps",
"within",
"a",
"namespace",
")",
"like"
] | python | train | 40.166667 |
xtream1101/web-wrapper | web_wrapper/driver_selenium_phantomjs.py | https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_phantomjs.py#L110-L121 | def reset(self):
"""
Kills old session and creates a new one with no proxies or headers
"""
# Kill old connection
self.quit()
# Clear proxy data
self.driver_args['service_args'] = self.default_service_args
# Clear headers
self.dcap = dict(webdriver... | [
"def",
"reset",
"(",
"self",
")",
":",
"# Kill old connection",
"self",
".",
"quit",
"(",
")",
"# Clear proxy data",
"self",
".",
"driver_args",
"[",
"'service_args'",
"]",
"=",
"self",
".",
"default_service_args",
"# Clear headers",
"self",
".",
"dcap",
"=",
... | Kills old session and creates a new one with no proxies or headers | [
"Kills",
"old",
"session",
"and",
"creates",
"a",
"new",
"one",
"with",
"no",
"proxies",
"or",
"headers"
] | python | train | 33.583333 |
camsci/meteor-pi | src/pythonModules/meteorpi_db/meteorpi_db/__init__.py | https://github.com/camsci/meteor-pi/blob/7b01527650bd1b2b76d6f364e8122e25b8812c8d/src/pythonModules/meteorpi_db/meteorpi_db/__init__.py#L599-L623 | def search_observations(self, search):
"""
Search for :class:`meteorpi_model.Observation` entities
:param search:
an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from
the DB
:return:
a structure of ... | [
"def",
"search_observations",
"(",
"self",
",",
"search",
")",
":",
"b",
"=",
"search_observations_sql_builder",
"(",
"search",
")",
"sql",
"=",
"b",
".",
"get_select_sql",
"(",
"columns",
"=",
"'l.publicId AS obstory_id, l.name AS obstory_name, '",
"'o.obsTime, s.name ... | Search for :class:`meteorpi_model.Observation` entities
:param search:
an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from
the DB
:return:
a structure of {count:int total rows of an unrestricted search, observatio... | [
"Search",
"for",
":",
"class",
":",
"meteorpi_model",
".",
"Observation",
"entities"
] | python | train | 50.36 |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L2972-L2982 | def uncancel_confirmation(self, confirmation_id):
"""
Uncancelles an confirmation
:param confirmation_id: the confirmation id
"""
return self._create_put_request(
resource=CONFIRMATIONS,
billomat_id=confirmation_id,
command=UNCANCEL,
) | [
"def",
"uncancel_confirmation",
"(",
"self",
",",
"confirmation_id",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"CONFIRMATIONS",
",",
"billomat_id",
"=",
"confirmation_id",
",",
"command",
"=",
"UNCANCEL",
",",
")"
] | Uncancelles an confirmation
:param confirmation_id: the confirmation id | [
"Uncancelles",
"an",
"confirmation"
] | python | train | 28.181818 |
reingart/pyafipws | padron.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L129-L179 | def Descargar(self, url=URL, filename="padron.txt", proxy=None):
"Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado"
proxies = {}
if proxy:
proxies['http'] = proxy
proxies['https'] = proxy
proxy_handler = urllib2.ProxyHandler(proxies)
... | [
"def",
"Descargar",
"(",
"self",
",",
"url",
"=",
"URL",
",",
"filename",
"=",
"\"padron.txt\"",
",",
"proxy",
"=",
"None",
")",
":",
"proxies",
"=",
"{",
"}",
"if",
"proxy",
":",
"proxies",
"[",
"'http'",
"]",
"=",
"proxy",
"proxies",
"[",
"'https'"... | Descarga el archivo de AFIP, devuelve 200 o 304 si no fue modificado | [
"Descarga",
"el",
"archivo",
"de",
"AFIP",
"devuelve",
"200",
"o",
"304",
"si",
"no",
"fue",
"modificado"
] | python | train | 34.470588 |
tcalmant/ipopo | pelix/framework.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1323-L1350 | def unregister_service(self, registration):
# type: (ServiceRegistration) -> bool
"""
Unregisters the given service
:param registration: A ServiceRegistration to the service to unregister
:raise BundleException: Invalid reference
"""
# Get the Service Reference
... | [
"def",
"unregister_service",
"(",
"self",
",",
"registration",
")",
":",
"# type: (ServiceRegistration) -> bool",
"# Get the Service Reference",
"reference",
"=",
"registration",
".",
"get_reference",
"(",
")",
"# Remove the service from the registry",
"svc_instance",
"=",
"s... | Unregisters the given service
:param registration: A ServiceRegistration to the service to unregister
:raise BundleException: Invalid reference | [
"Unregisters",
"the",
"given",
"service"
] | python | train | 35 |
crunchyroll/ef-open | efopen/ef_check_config.py | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_check_config.py#L38-L60 | def handle_args(args):
"""
Handle command line arguments
Raises:
Exception if the config path wasn't explicitly state and dead reckoning based on script location fails
"""
parser = argparse.ArgumentParser()
parser.add_argument("configpath", default=None, nargs="?",
help="/path/to/c... | [
"def",
"handle_args",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"configpath\"",
",",
"default",
"=",
"None",
",",
"nargs",
"=",
"\"?\"",
",",
"help",
"=",
"\"/path/to/configs (alw... | Handle command line arguments
Raises:
Exception if the config path wasn't explicitly state and dead reckoning based on script location fails | [
"Handle",
"command",
"line",
"arguments",
"Raises",
":",
"Exception",
"if",
"the",
"config",
"path",
"wasn",
"t",
"explicitly",
"state",
"and",
"dead",
"reckoning",
"based",
"on",
"script",
"location",
"fails"
] | python | train | 51.565217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.