repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/widgets/tooltip.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/tooltip.py#L95-L112 | def setup_layout(self, orientation=None):
"""Setup the layout for the tooltip in the given orientation
:param layout: the orentation of the layout
:type layout: QtCore.Qt.Orientation | None
:returns: None
:rtype: None
:raises: None
"""
if orientation == Q... | [
"def",
"setup_layout",
"(",
"self",
",",
"orientation",
"=",
"None",
")",
":",
"if",
"orientation",
"==",
"QtCore",
".",
"Qt",
".",
"Horizontal",
"or",
"orientation",
"is",
"None",
":",
"layout",
"=",
"QtGui",
".",
"QHBoxLayout",
"(",
")",
"elif",
"orien... | Setup the layout for the tooltip in the given orientation
:param layout: the orentation of the layout
:type layout: QtCore.Qt.Orientation | None
:returns: None
:rtype: None
:raises: None | [
"Setup",
"the",
"layout",
"for",
"the",
"tooltip",
"in",
"the",
"given",
"orientation"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/list_all_file_extensions.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/list_all_file_extensions.py#L43-L65 | def list_file_extensions(path: str, reportevery: int = 1) -> List[str]:
"""
Returns a sorted list of every file extension found in a directory
and its subdirectories.
Args:
path: path to scan
reportevery: report directory progress after every *n* steps
Returns:
sorted list ... | [
"def",
"list_file_extensions",
"(",
"path",
":",
"str",
",",
"reportevery",
":",
"int",
"=",
"1",
")",
"->",
"List",
"[",
"str",
"]",
":",
"extensions",
"=",
"set",
"(",
")",
"count",
"=",
"0",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
... | Returns a sorted list of every file extension found in a directory
and its subdirectories.
Args:
path: path to scan
reportevery: report directory progress after every *n* steps
Returns:
sorted list of every file extension found | [
"Returns",
"a",
"sorted",
"list",
"of",
"every",
"file",
"extension",
"found",
"in",
"a",
"directory",
"and",
"its",
"subdirectories",
"."
] | python | train |
openpermissions/perch | perch/model.py | https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/model.py#L568-L583 | def get(cls, resource_id, include_deactivated=False):
"""
Get a resource
:param resource_id: the resource ID
:param include_deactivated: Include deactivated resources in response
:returns: a SubResource instance
:raises: SocketError, CouchException
"""
if... | [
"def",
"get",
"(",
"cls",
",",
"resource_id",
",",
"include_deactivated",
"=",
"False",
")",
":",
"if",
"include_deactivated",
":",
"resource",
"=",
"yield",
"cls",
".",
"view",
".",
"first",
"(",
"key",
"=",
"resource_id",
",",
"include_docs",
"=",
"True"... | Get a resource
:param resource_id: the resource ID
:param include_deactivated: Include deactivated resources in response
:returns: a SubResource instance
:raises: SocketError, CouchException | [
"Get",
"a",
"resource"
] | python | train |
Delgan/loguru | loguru/_logger.py | https://github.com/Delgan/loguru/blob/6571879c37904e3a18567e694d70651c6886b860/loguru/_logger.py#L1638-L1650 | def stop(self, *args, **kwargs):
"""Deprecated function to |remove| an existing handler.
Warnings
--------
.. deprecated:: 0.2.2
``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
confusing name.
"""
warnings.wa... | [
"def",
"stop",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The 'stop()' method is deprecated, please use 'remove()' instead\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"remove",
"(",
"*",
"arg... | Deprecated function to |remove| an existing handler.
Warnings
--------
.. deprecated:: 0.2.2
``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less
confusing name. | [
"Deprecated",
"function",
"to",
"|remove|",
"an",
"existing",
"handler",
"."
] | python | train |
blockstack/pybitcoin | pybitcoin/rpc/namecoind_client.py | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/rpc/namecoind_client.py#L190-L215 | def name_transfer(self, key, new_address, value=None):
""" Check if this name exists and if it does, find the value field
note that update command needs an arg of <new value>.
in case we're simply transferring, need to obtain old value first
"""
key_details = self.name_s... | [
"def",
"name_transfer",
"(",
"self",
",",
"key",
",",
"new_address",
",",
"value",
"=",
"None",
")",
":",
"key_details",
"=",
"self",
".",
"name_show",
"(",
"key",
")",
"if",
"'code'",
"in",
"key_details",
"and",
"key_details",
".",
"get",
"(",
"'code'",... | Check if this name exists and if it does, find the value field
note that update command needs an arg of <new value>.
in case we're simply transferring, need to obtain old value first | [
"Check",
"if",
"this",
"name",
"exists",
"and",
"if",
"it",
"does",
"find",
"the",
"value",
"field",
"note",
"that",
"update",
"command",
"needs",
"an",
"arg",
"of",
"<new",
"value",
">",
".",
"in",
"case",
"we",
"re",
"simply",
"transferring",
"need",
... | python | train |
gouthambs/Flask-Blogging | flask_blogging/sqlastorage.py | https://github.com/gouthambs/Flask-Blogging/blob/6636b8941175e9910f116a329521f96b8b05a9ac/flask_blogging/sqlastorage.py#L362-L397 | def delete_post(self, post_id):
"""
Delete the post defined by ``post_id``
:param post_id: The identifier corresponding to a post
:type post_id: int
:return: Returns True if the post was successfully deleted and False
otherwise.
"""
status = False
... | [
"def",
"delete_post",
"(",
"self",
",",
"post_id",
")",
":",
"status",
"=",
"False",
"success",
"=",
"0",
"post_id",
"=",
"_as_int",
"(",
"post_id",
")",
"with",
"self",
".",
"_engine",
".",
"begin",
"(",
")",
"as",
"conn",
":",
"try",
":",
"post_del... | Delete the post defined by ``post_id``
:param post_id: The identifier corresponding to a post
:type post_id: int
:return: Returns True if the post was successfully deleted and False
otherwise. | [
"Delete",
"the",
"post",
"defined",
"by",
"post_id"
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L4427-L4474 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'credential_type') and self.credential_type is not None:
_dict['credential_type'] = self.credential_type
if hasattr(self, 'client_id') and self.client_id... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'credential_type'",
")",
"and",
"self",
".",
"credential_type",
"is",
"not",
"None",
":",
"_dict",
"[",
"'credential_type'",
"]",
"=",
"self",
".",
"c... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/dotenv/main.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/dotenv/main.py#L209-L232 | def unset_key(dotenv_path, key_to_unset, quote_mode="always"):
"""
Removes a given key from the given .env
If the .env path given doesn't exist, fails
If the given key doesn't exist in the .env, fails
"""
if not os.path.exists(dotenv_path):
warnings.warn("can't delete from %s - it doesn... | [
"def",
"unset_key",
"(",
"dotenv_path",
",",
"key_to_unset",
",",
"quote_mode",
"=",
"\"always\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dotenv_path",
")",
":",
"warnings",
".",
"warn",
"(",
"\"can't delete from %s - it doesn't exist.\""... | Removes a given key from the given .env
If the .env path given doesn't exist, fails
If the given key doesn't exist in the .env, fails | [
"Removes",
"a",
"given",
"key",
"from",
"the",
"given",
".",
"env"
] | python | train |
IBM/pyxcli | pyxcli/helpers/exceptool.py | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/helpers/exceptool.py#L21-L39 | def chained(wrapping_exc):
# pylint: disable=W0212
"""
Embeds the current exception information into the given one (which
will replace the current one).
For example::
try:
...
except OSError as ex:
raise chained(MyError("database not found!"))
"""
t, ... | [
"def",
"chained",
"(",
"wrapping_exc",
")",
":",
"# pylint: disable=W0212",
"t",
",",
"v",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"not",
"t",
":",
"return",
"wrapping_exc",
"wrapping_exc",
".",
"_inner_exc",
"=",
"v",
"lines",
"=",
"trac... | Embeds the current exception information into the given one (which
will replace the current one).
For example::
try:
...
except OSError as ex:
raise chained(MyError("database not found!")) | [
"Embeds",
"the",
"current",
"exception",
"information",
"into",
"the",
"given",
"one",
"(",
"which",
"will",
"replace",
"the",
"current",
"one",
")",
".",
"For",
"example",
"::"
] | python | train |
martinblech/xmltodict | ez_setup.py | https://github.com/martinblech/xmltodict/blob/f3ab7e1740d37d585ffab0154edb4cb664afe4a9/ez_setup.py#L99-L129 | def archive_context(filename):
"""
Unzip filename to a temporary directory, set to the cwd.
The unzipped target is cleaned up after.
"""
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
try:
with Cont... | [
"def",
"archive_context",
"(",
"filename",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"log",
".",
"warn",
"(",
"'Extracting in %s'",
",",
"tmpdir",
")",
"old_wd",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"os",
".",
"chdir",
... | Unzip filename to a temporary directory, set to the cwd.
The unzipped target is cleaned up after. | [
"Unzip",
"filename",
"to",
"a",
"temporary",
"directory",
"set",
"to",
"the",
"cwd",
"."
] | python | train |
fdChasm/txCarbonClient | src/txCarbonClient/carbon_client_service.py | https://github.com/fdChasm/txCarbonClient/blob/c342eff1957d281cba3c83fc578f08c4bf9fcd03/src/txCarbonClient/carbon_client_service.py#L30-L44 | def publish_metric(self, metric_name, metric_value, epoch_seconds=None):
'''Record a single hit on a given metric.
Args:
metric_name: The name of the metric to record with Carbon.
metric_value: The value to record with Carbon.
epoch_seconds: Optionally specify the ti... | [
"def",
"publish_metric",
"(",
"self",
",",
"metric_name",
",",
"metric_value",
",",
"epoch_seconds",
"=",
"None",
")",
":",
"if",
"epoch_seconds",
"is",
"None",
":",
"epoch_seconds",
"=",
"self",
".",
"_reactor",
".",
"seconds",
"(",
")",
"self",
".",
"_cl... | Record a single hit on a given metric.
Args:
metric_name: The name of the metric to record with Carbon.
metric_value: The value to record with Carbon.
epoch_seconds: Optionally specify the time for the metric hit.
Returns:
None | [
"Record",
"a",
"single",
"hit",
"on",
"a",
"given",
"metric",
"."
] | python | train |
tensorflow/mesh | mesh_tensorflow/layers.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L187-L220 | def softmax_cross_entropy_with_logits(logits, targets, vocab_dim, z_loss=0.0):
"""Per-example softmax loss.
if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the
partition function. Example value: z_loss=1e-4. Two uses of z_loss are:
- To keep the logits from drifting too far from zero... | [
"def",
"softmax_cross_entropy_with_logits",
"(",
"logits",
",",
"targets",
",",
"vocab_dim",
",",
"z_loss",
"=",
"0.0",
")",
":",
"if",
"logits",
".",
"shape",
"!=",
"targets",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"logits shape must equal targets shape... | Per-example softmax loss.
if z_loss is nonzero, we add a loss equal to z_loss*log(z)^2, where z is the
partition function. Example value: z_loss=1e-4. Two uses of z_loss are:
- To keep the logits from drifting too far from zero, which can cause
unacceptable roundoff errors in bfloat16.
- To encourage th... | [
"Per",
"-",
"example",
"softmax",
"loss",
"."
] | python | train |
google/grumpy | third_party/stdlib/collections.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/collections.py#L538-L579 | def update(*args, **kwds):
'''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch'... | [
"def",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"# The regular dict.update() operation makes no sense here because the",
"# replace behavior results in the some of original untouched counts",
"# being mixed-in with all of the other counts for a mismash that",
"# doesn... | Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) ... | [
"Like",
"dict",
".",
"update",
"()",
"but",
"add",
"counts",
"instead",
"of",
"replacing",
"them",
"."
] | python | valid |
openmicroscopy/yaclifw | yaclifw/version.py | https://github.com/openmicroscopy/yaclifw/blob/a01179fefb2c2c4260c75e6d1dc6e19de9979d64/yaclifw/version.py#L45-L57 | def _lookup_version(module_file):
"""
For the given module file (usually found by:
from package import __file__ as module_file
in the caller, return the location of
the current RELEASE-VERSION file and the file
itself.
"""
version_dir = path.abspath(path.dirname(module_file))
v... | [
"def",
"_lookup_version",
"(",
"module_file",
")",
":",
"version_dir",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"dirname",
"(",
"module_file",
")",
")",
"version_file",
"=",
"path",
".",
"join",
"(",
"version_dir",
",",
"\"RELEASE-VERSION\"",
")",
"ret... | For the given module file (usually found by:
from package import __file__ as module_file
in the caller, return the location of
the current RELEASE-VERSION file and the file
itself. | [
"For",
"the",
"given",
"module",
"file",
"(",
"usually",
"found",
"by",
":"
] | python | test |
fitnr/convertdate | convertdate/french_republican.py | https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/french_republican.py#L98-L115 | def to_jd(year, month, day, method=None):
'''Obtain Julian day from a given French Revolutionary calendar date.'''
method = method or 'equinox'
if day < 1 or day > 30:
raise ValueError("Invalid day for this calendar")
if month > 13:
raise ValueError("Invalid month for this calendar")
... | [
"def",
"to_jd",
"(",
"year",
",",
"month",
",",
"day",
",",
"method",
"=",
"None",
")",
":",
"method",
"=",
"method",
"or",
"'equinox'",
"if",
"day",
"<",
"1",
"or",
"day",
">",
"30",
":",
"raise",
"ValueError",
"(",
"\"Invalid day for this calendar\"",
... | Obtain Julian day from a given French Revolutionary calendar date. | [
"Obtain",
"Julian",
"day",
"from",
"a",
"given",
"French",
"Revolutionary",
"calendar",
"date",
"."
] | python | train |
olitheolix/qtmacs | qtmacs/extensions/qtmacstextedit_widget.py | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_widget.py#L275-L298 | def reverseCommit(self):
"""
Remove the inserted character(s).
"""
# Move the cursor to the right of the text to delete.
tc = self.qteWidget.textCursor()
# Delete as many characters as necessary. For an image that would
# be exactly 1 even though the HTML code t... | [
"def",
"reverseCommit",
"(",
"self",
")",
":",
"# Move the cursor to the right of the text to delete.",
"tc",
"=",
"self",
".",
"qteWidget",
".",
"textCursor",
"(",
")",
"# Delete as many characters as necessary. For an image that would",
"# be exactly 1 even though the HTML code t... | Remove the inserted character(s). | [
"Remove",
"the",
"inserted",
"character",
"(",
"s",
")",
"."
] | python | train |
zero-os/0-core | client/py-client/zeroos/core0/client/client.py | https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1967-L1976 | def subvol_create(self, path):
"""
Create a btrfs subvolume in the specified path
:param path: path to create
"""
args = {
'path': path
}
self._subvol_chk.check(args)
self._client.sync('btrfs.subvol_create', args) | [
"def",
"subvol_create",
"(",
"self",
",",
"path",
")",
":",
"args",
"=",
"{",
"'path'",
":",
"path",
"}",
"self",
".",
"_subvol_chk",
".",
"check",
"(",
"args",
")",
"self",
".",
"_client",
".",
"sync",
"(",
"'btrfs.subvol_create'",
",",
"args",
")"
] | Create a btrfs subvolume in the specified path
:param path: path to create | [
"Create",
"a",
"btrfs",
"subvolume",
"in",
"the",
"specified",
"path",
":",
"param",
"path",
":",
"path",
"to",
"create"
] | python | train |
tcalmant/ipopo | pelix/threadpool.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/threadpool.py#L105-L113 | def raise_exception(self, exception):
"""
Raises an exception in wait()
:param exception: An Exception object
"""
self.__data = None
self.__exception = exception
self.__event.set() | [
"def",
"raise_exception",
"(",
"self",
",",
"exception",
")",
":",
"self",
".",
"__data",
"=",
"None",
"self",
".",
"__exception",
"=",
"exception",
"self",
".",
"__event",
".",
"set",
"(",
")"
] | Raises an exception in wait()
:param exception: An Exception object | [
"Raises",
"an",
"exception",
"in",
"wait",
"()"
] | python | train |
postlund/pyatv | pyatv/airplay/srp.py | https://github.com/postlund/pyatv/blob/655dfcda4e2f9d1c501540e18da4f480d8bf0e70/pyatv/airplay/srp.py#L63-L70 | def get_common_session_key(self, premaster_secret):
"""K = H(S).
Special implementation for Apple TV.
"""
k_1 = self.hash(premaster_secret, b'\x00\x00\x00\x00', as_bytes=True)
k_2 = self.hash(premaster_secret, b'\x00\x00\x00\x01', as_bytes=True)
return k_1 + k_2 | [
"def",
"get_common_session_key",
"(",
"self",
",",
"premaster_secret",
")",
":",
"k_1",
"=",
"self",
".",
"hash",
"(",
"premaster_secret",
",",
"b'\\x00\\x00\\x00\\x00'",
",",
"as_bytes",
"=",
"True",
")",
"k_2",
"=",
"self",
".",
"hash",
"(",
"premaster_secre... | K = H(S).
Special implementation for Apple TV. | [
"K",
"=",
"H",
"(",
"S",
")",
"."
] | python | train |
twidi/py-dataql | dataql/solvers/resources.py | https://github.com/twidi/py-dataql/blob/5841a3fd559829193ed709c255166085bdde1c52/dataql/solvers/resources.py#L205-L233 | def can_solve(cls, resource):
"""Tells if the solver is able to resolve the given resource.
Arguments
---------
resource : subclass of ``dataql.resources.Resource``
The resource to check if it is solvable by the current solver class
Returns
-------
b... | [
"def",
"can_solve",
"(",
"cls",
",",
"resource",
")",
":",
"for",
"solvable_resource",
"in",
"cls",
".",
"solvable_resources",
":",
"if",
"isinstance",
"(",
"resource",
",",
"solvable_resource",
")",
":",
"return",
"True",
"return",
"False"
] | Tells if the solver is able to resolve the given resource.
Arguments
---------
resource : subclass of ``dataql.resources.Resource``
The resource to check if it is solvable by the current solver class
Returns
-------
boolean
``True`` if the curren... | [
"Tells",
"if",
"the",
"solver",
"is",
"able",
"to",
"resolve",
"the",
"given",
"resource",
"."
] | python | train |
Grokzen/pykwalify | pykwalify/core.py | https://github.com/Grokzen/pykwalify/blob/02b7e21eafb97926f17b7c33e2ee7b3ea67c3ef7/pykwalify/core.py#L919-L966 | def _validate_range(self, max_, min_, max_ex, min_ex, value, path, prefix):
"""
Validate that value is within range values.
"""
if not isinstance(value, int) and not isinstance(value, float):
raise CoreError("Value must be a integer type")
log.debug(
u"Va... | [
"def",
"_validate_range",
"(",
"self",
",",
"max_",
",",
"min_",
",",
"max_ex",
",",
"min_ex",
",",
"value",
",",
"path",
",",
"prefix",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
"and",
"not",
"isinstance",
"(",
"value",
","... | Validate that value is within range values. | [
"Validate",
"that",
"value",
"is",
"within",
"range",
"values",
"."
] | python | train |
earlzo/hfut | hfut/parser.py | https://github.com/earlzo/hfut/blob/09270a9647fba79f26fd1a8a3c53c0678b5257a1/hfut/parser.py#L73-L87 | def flatten_list(multiply_list):
"""
碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list
"""
if isinstance(multiply_list, list):
return [rv for l in multiply_list for rv ... | [
"def",
"flatten_list",
"(",
"multiply_list",
")",
":",
"if",
"isinstance",
"(",
"multiply_list",
",",
"list",
")",
":",
"return",
"[",
"rv",
"for",
"l",
"in",
"multiply_list",
"for",
"rv",
"in",
"flatten_list",
"(",
"l",
")",
"]",
"else",
":",
"return",
... | 碾平 list::
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten_list(a)
[1, 2, 3, 4, 5, 6, 7, 8]
:param multiply_list: 混淆的多层列表
:return: 单层的 list | [
"碾平",
"list",
"::"
] | python | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidgetitem.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetitem.py#L502-L511 | def setSizeHint(self, column, hint):
"""
Sets the size hint for this item to the inputed size. This will also
updated the fixed height property if the hieght of the inputed hint
is larger than the current fixed height.
:param hint | <QtCore.QSize>
""... | [
"def",
"setSizeHint",
"(",
"self",
",",
"column",
",",
"hint",
")",
":",
"self",
".",
"_fixedHeight",
"=",
"max",
"(",
"hint",
".",
"height",
"(",
")",
",",
"self",
".",
"_fixedHeight",
")",
"super",
"(",
"XTreeWidgetItem",
",",
"self",
")",
".",
"se... | Sets the size hint for this item to the inputed size. This will also
updated the fixed height property if the hieght of the inputed hint
is larger than the current fixed height.
:param hint | <QtCore.QSize> | [
"Sets",
"the",
"size",
"hint",
"for",
"this",
"item",
"to",
"the",
"inputed",
"size",
".",
"This",
"will",
"also",
"updated",
"the",
"fixed",
"height",
"property",
"if",
"the",
"hieght",
"of",
"the",
"inputed",
"hint",
"is",
"larger",
"than",
"the",
"cur... | python | train |
ddorn/GUI | GUI/vracabulous.py | https://github.com/ddorn/GUI/blob/e1fcb5286d24e0995f280d5180222e51895c368c/GUI/vracabulous.py#L107-L112 | def on_unselect(self, item, action):
"""Add an action to make when an object is unfocused."""
if not isinstance(item, int):
item = self.items.index(item)
self._on_unselect[item] = action | [
"def",
"on_unselect",
"(",
"self",
",",
"item",
",",
"action",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"int",
")",
":",
"item",
"=",
"self",
".",
"items",
".",
"index",
"(",
"item",
")",
"self",
".",
"_on_unselect",
"[",
"item",
"]",... | Add an action to make when an object is unfocused. | [
"Add",
"an",
"action",
"to",
"make",
"when",
"an",
"object",
"is",
"unfocused",
"."
] | python | train |
quantumlib/Cirq | cirq/sim/density_matrix_simulator.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/density_matrix_simulator.py#L322-L388 | def compute_displays_sweep(
self,
program: Union[circuits.Circuit, schedules.Schedule],
params: Optional[study.Sweepable] = None,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Union[int, np.ndarray] = 0,
) -> List[study.ComputeDisplaysResult]:
... | [
"def",
"compute_displays_sweep",
"(",
"self",
",",
"program",
":",
"Union",
"[",
"circuits",
".",
"Circuit",
",",
"schedules",
".",
"Schedule",
"]",
",",
"params",
":",
"Optional",
"[",
"study",
".",
"Sweepable",
"]",
"=",
"None",
",",
"qubit_order",
":",
... | Computes displays in the supplied Circuit or Schedule.
In contrast to `compute_displays`, this allows for sweeping
over different parameter values.
Args:
program: The circuit or schedule to simulate.
params: Parameters to run with the program.
qubit_order: D... | [
"Computes",
"displays",
"in",
"the",
"supplied",
"Circuit",
"or",
"Schedule",
"."
] | python | train |
python-diamond/Diamond | src/diamond/handler/graphitepickle.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/graphitepickle.py#L46-L55 | def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(GraphitePickleHandler, self).get_default_config_help()
config.update({
})
return config | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"GraphitePickleHandler",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config",
".",
"update",
"(",
"{",
"}",
")",
"return",
"config"
] | Returns the help text for the configuration options for this handler | [
"Returns",
"the",
"help",
"text",
"for",
"the",
"configuration",
"options",
"for",
"this",
"handler"
] | python | train |
nicolargo/glances | glances/plugins/glances_plugin.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_plugin.py#L201-L215 | def get_raw_history(self, item=None, nb=0):
"""Return the history (RAW format).
- the stats history (dict of list) if item is None
- the stats history for the given item (list) instead
- None if item did not exist in the history
"""
s = self.stats_history.get(nb=nb)
... | [
"def",
"get_raw_history",
"(",
"self",
",",
"item",
"=",
"None",
",",
"nb",
"=",
"0",
")",
":",
"s",
"=",
"self",
".",
"stats_history",
".",
"get",
"(",
"nb",
"=",
"nb",
")",
"if",
"item",
"is",
"None",
":",
"return",
"s",
"else",
":",
"if",
"i... | Return the history (RAW format).
- the stats history (dict of list) if item is None
- the stats history for the given item (list) instead
- None if item did not exist in the history | [
"Return",
"the",
"history",
"(",
"RAW",
"format",
")",
"."
] | python | train |
Erotemic/utool | utool/experimental/euler_tour_tree_avl.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/euler_tour_tree_avl.py#L41-L73 | def euler_tour(G, node=None, seen=None, visited=None):
"""
definition from
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.192.8615&rep=rep1&type=pdf
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> edges = [
>>... | [
"def",
"euler_tour",
"(",
"G",
",",
"node",
"=",
"None",
",",
"seen",
"=",
"None",
",",
"visited",
"=",
"None",
")",
":",
"if",
"node",
"is",
"None",
":",
"node",
"=",
"next",
"(",
"G",
".",
"nodes",
"(",
")",
")",
"if",
"visited",
"is",
"None"... | definition from
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.192.8615&rep=rep1&type=pdf
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> edges = [
>>> ('R', 'A'), ('R', 'B'),
>>> ('B', 'C'), ('C', 'D'... | [
"definition",
"from",
"http",
":",
"//",
"citeseerx",
".",
"ist",
".",
"psu",
".",
"edu",
"/",
"viewdoc",
"/",
"download?doi",
"=",
"10",
".",
"1",
".",
"1",
".",
"192",
".",
"8615&rep",
"=",
"rep1&type",
"=",
"pdf"
] | python | train |
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L4465-L4472 | def copychildren(self, newdoc=None, idsuffix=""):
"""Generator creating a deep copy of the children of this element. If idsuffix is a string, if set to True, a random idsuffix will be generated including a random 32-bit hash"""
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #... | [
"def",
"copychildren",
"(",
"self",
",",
"newdoc",
"=",
"None",
",",
"idsuffix",
"=",
"\"\"",
")",
":",
"if",
"idsuffix",
"is",
"True",
":",
"idsuffix",
"=",
"\".copy.\"",
"+",
"\"%08x\"",
"%",
"random",
".",
"getrandbits",
"(",
"32",
")",
"#random 32-bi... | Generator creating a deep copy of the children of this element. If idsuffix is a string, if set to True, a random idsuffix will be generated including a random 32-bit hash | [
"Generator",
"creating",
"a",
"deep",
"copy",
"of",
"the",
"children",
"of",
"this",
"element",
".",
"If",
"idsuffix",
"is",
"a",
"string",
"if",
"set",
"to",
"True",
"a",
"random",
"idsuffix",
"will",
"be",
"generated",
"including",
"a",
"random",
"32",
... | python | train |
javipalanca/spade | spade/behaviour.py | https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L118-L131 | async def _start(self):
"""
Start coroutine. runs on_start coroutine and then
runs the _step coroutine where the body of the behaviour
is called.
"""
self.agent._alive.wait()
try:
await self.on_start()
except Exception as e:
logger.... | [
"async",
"def",
"_start",
"(",
"self",
")",
":",
"self",
".",
"agent",
".",
"_alive",
".",
"wait",
"(",
")",
"try",
":",
"await",
"self",
".",
"on_start",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Exception runn... | Start coroutine. runs on_start coroutine and then
runs the _step coroutine where the body of the behaviour
is called. | [
"Start",
"coroutine",
".",
"runs",
"on_start",
"coroutine",
"and",
"then",
"runs",
"the",
"_step",
"coroutine",
"where",
"the",
"body",
"of",
"the",
"behaviour",
"is",
"called",
"."
] | python | train |
jacobtomlinson/datapoint-python | datapoint/Forecast.py | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Forecast.py#L82-L121 | def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None):
"""
Function to return a future timestep
"""
future = None
# Initialize variables to 0
dd, hh, mm, ss = [0 for i in range(4)]
if (in_days != None):
dd = dd + in_days
... | [
"def",
"future",
"(",
"self",
",",
"in_days",
"=",
"None",
",",
"in_hours",
"=",
"None",
",",
"in_minutes",
"=",
"None",
",",
"in_seconds",
"=",
"None",
")",
":",
"future",
"=",
"None",
"# Initialize variables to 0",
"dd",
",",
"hh",
",",
"mm",
",",
"s... | Function to return a future timestep | [
"Function",
"to",
"return",
"a",
"future",
"timestep"
] | python | train |
neithere/monk | monk/compat.py | https://github.com/neithere/monk/blob/4b2ee5152b081ac288ce8568422a027b5e7d2b1c/monk/compat.py#L63-L76 | def safe_unicode(value):
""" Returns:
* a `unicode` instance in Python 2.x, or
* a `str` instance in Python 3.x.
"""
if sys.version_info < (3,0):
if isinstance(value, str):
return value.decode('utf-8')
else:
return unicode(value)
else:
return str... | [
"def",
"safe_unicode",
"(",
"value",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"return"... | Returns:
* a `unicode` instance in Python 2.x, or
* a `str` instance in Python 3.x. | [
"Returns",
":"
] | python | train |
sosreport/sos | sos/archive.py | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L245-L318 | def _check_path(self, src, path_type, dest=None, force=False):
"""Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive m... | [
"def",
"_check_path",
"(",
"self",
",",
"src",
",",
"path_type",
",",
"dest",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"dest",
"=",
"dest",
"or",
"self",
".",
"dest_path",
"(",
"src",
")",
"if",
"path_type",
"==",
"P_DIR",
":",
"dest_dir",
... | Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive methods: historically the
archive class only needed to test for... | [
"Check",
"a",
"new",
"destination",
"path",
"in",
"the",
"archive",
"."
] | python | train |
titusjan/argos | argos/utils/masks.py | https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L206-L224 | def replaceMaskedValueWithNan(self):
""" Replaces values where the mask is True with the replacement value.
Will change the data type to float if the data is an integer.
If the data is not a float (or int) the function does nothing.
"""
kind = self.data.dtype.kind
... | [
"def",
"replaceMaskedValueWithNan",
"(",
"self",
")",
":",
"kind",
"=",
"self",
".",
"data",
".",
"dtype",
".",
"kind",
"if",
"kind",
"==",
"'i'",
"or",
"kind",
"==",
"'u'",
":",
"# signed/unsigned int",
"self",
".",
"data",
"=",
"self",
".",
"data",
"... | Replaces values where the mask is True with the replacement value.
Will change the data type to float if the data is an integer.
If the data is not a float (or int) the function does nothing. | [
"Replaces",
"values",
"where",
"the",
"mask",
"is",
"True",
"with",
"the",
"replacement",
"value",
"."
] | python | train |
tonybaloney/wily | wily/cache.py | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/cache.py#L94-L139 | def store(config, archiver, revision, stats):
"""
Store a revision record within an archiver folder.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: Th... | [
"def",
"store",
"(",
"config",
",",
"archiver",
",",
"revision",
",",
"stats",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
".",
"name",
"if",
"not",
"root",
".",
"exists",
"(",
")",
":",
"l... | Store a revision record within an archiver folder.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:param revision: The revision ID
:type revision: ``str``
:param... | [
"Store",
"a",
"revision",
"record",
"within",
"an",
"archiver",
"folder",
"."
] | python | train |
rocky/python3-trepan | trepan/lib/sighandler.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L275-L282 | def check_and_adjust_sighandlers(self):
"""Check to see if any of the signal handlers we are interested in have
changed or is not initially set. Change any that are not right. """
for signame in list(self.sigs.keys()):
if not self.check_and_adjust_sighandler(signame, self.sigs):
... | [
"def",
"check_and_adjust_sighandlers",
"(",
"self",
")",
":",
"for",
"signame",
"in",
"list",
"(",
"self",
".",
"sigs",
".",
"keys",
"(",
")",
")",
":",
"if",
"not",
"self",
".",
"check_and_adjust_sighandler",
"(",
"signame",
",",
"self",
".",
"sigs",
")... | Check to see if any of the signal handlers we are interested in have
changed or is not initially set. Change any that are not right. | [
"Check",
"to",
"see",
"if",
"any",
"of",
"the",
"signal",
"handlers",
"we",
"are",
"interested",
"in",
"have",
"changed",
"or",
"is",
"not",
"initially",
"set",
".",
"Change",
"any",
"that",
"are",
"not",
"right",
"."
] | python | test |
Cairnarvon/uptime | src/__init__.py | https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L198-L214 | def _uptime_plan9():
"""Returns uptime in seconds or None, on Plan 9."""
# Apparently Plan 9 only has Python 2.2, which I'm not prepared to
# support. Maybe some Linuxes implement /dev/time, though, someone was
# talking about it somewhere.
try:
# The time file holds one 32-bit number repres... | [
"def",
"_uptime_plan9",
"(",
")",
":",
"# Apparently Plan 9 only has Python 2.2, which I'm not prepared to",
"# support. Maybe some Linuxes implement /dev/time, though, someone was",
"# talking about it somewhere.",
"try",
":",
"# The time file holds one 32-bit number representing the sec-",
"... | Returns uptime in seconds or None, on Plan 9. | [
"Returns",
"uptime",
"in",
"seconds",
"or",
"None",
"on",
"Plan",
"9",
"."
] | python | valid |
quantopian/pyfolio | pyfolio/bayesian.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/bayesian.py#L426-L453 | def compute_bayes_cone(preds, starting_value=1.):
"""
Compute 5, 25, 75 and 95 percentiles of cumulative returns, used
for the Bayesian cone.
Parameters
----------
preds : numpy.array
Multiple (simulated) cumulative returns.
starting_value : int (optional)
Have cumulative re... | [
"def",
"compute_bayes_cone",
"(",
"preds",
",",
"starting_value",
"=",
"1.",
")",
":",
"def",
"scoreatpercentile",
"(",
"cum_preds",
",",
"p",
")",
":",
"return",
"[",
"stats",
".",
"scoreatpercentile",
"(",
"c",
",",
"p",
")",
"for",
"c",
"in",
"cum_pre... | Compute 5, 25, 75 and 95 percentiles of cumulative returns, used
for the Bayesian cone.
Parameters
----------
preds : numpy.array
Multiple (simulated) cumulative returns.
starting_value : int (optional)
Have cumulative returns start around this value.
Default = 1.
Retur... | [
"Compute",
"5",
"25",
"75",
"and",
"95",
"percentiles",
"of",
"cumulative",
"returns",
"used",
"for",
"the",
"Bayesian",
"cone",
"."
] | python | valid |
ikegami-yukino/jctconv | jctconv/jctconv.py | https://github.com/ikegami-yukino/jctconv/blob/cc9bcb25b69c681b01b5c85cacdfb56c1a285407/jctconv/jctconv.py#L146-L161 | def normalize(text, mode='NFKC', ignore=''):
u"""Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana,
Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII
and DIGIT.
Additionally, Full-width wave dash (〜) etc. are normalized
Params:
<unicode> text
<u... | [
"def",
"normalize",
"(",
"text",
",",
"mode",
"=",
"'NFKC'",
",",
"ignore",
"=",
"''",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"u'〜', ",
"u",
"ー').re",
"p",
"l",
"ace(u'~",
"'",
", u'ー'",
")",
"",
"",
"text",
"=",
"text",
".",
"replac... | u"""Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana,
Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII
and DIGIT.
Additionally, Full-width wave dash (〜) etc. are normalized
Params:
<unicode> text
<unicode> ignore
Return:
<unicode> conv... | [
"u",
"Convert",
"Half",
"-",
"width",
"(",
"Hankaku",
")",
"Katakana",
"to",
"Full",
"-",
"width",
"(",
"Zenkaku",
")",
"Katakana",
"Full",
"-",
"width",
"(",
"Zenkaku",
")",
"ASCII",
"and",
"DIGIT",
"to",
"Half",
"-",
"width",
"(",
"Hankaku",
")",
"... | python | train |
PredixDev/predixpy | predix/security/acs.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L305-L311 | def _put_policy_set(self, policy_set_id, body):
"""
Will create or update a policy set for the given path.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._put(uri, body) | [
"def",
"_put_policy_set",
"(",
"self",
",",
"policy_set_id",
",",
"body",
")",
":",
"assert",
"isinstance",
"(",
"body",
",",
"(",
"dict",
")",
")",
",",
"\"PUT requires body to be a dict.\"",
"uri",
"=",
"self",
".",
"_get_policy_set_uri",
"(",
"guid",
"=",
... | Will create or update a policy set for the given path. | [
"Will",
"create",
"or",
"update",
"a",
"policy",
"set",
"for",
"the",
"given",
"path",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/utils/quantization.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/quantization.py#L89-L134 | def simulated_quantize(x, num_bits, noise):
"""Simulate quantization to num_bits bits, with externally-stored scale.
num_bits is the number of bits used to store each value.
noise is a float32 Tensor containing values in [0, 1).
Each value in noise should take different values across
different steps, approxi... | [
"def",
"simulated_quantize",
"(",
"x",
",",
"num_bits",
",",
"noise",
")",
":",
"shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"not",
"(",
"len",
"(",
"shape",
")",
">=",
"2",
"and",
"shape",
"[",
"-",
"1",
"]",
... | Simulate quantization to num_bits bits, with externally-stored scale.
num_bits is the number of bits used to store each value.
noise is a float32 Tensor containing values in [0, 1).
Each value in noise should take different values across
different steps, approximating a uniform distribution over [0, 1).
In t... | [
"Simulate",
"quantization",
"to",
"num_bits",
"bits",
"with",
"externally",
"-",
"stored",
"scale",
"."
] | python | train |
aestrivex/bctpy | bct/algorithms/distance.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/distance.py#L326-L421 | def distance_wei_floyd(adjacency, transform=None):
"""
Computes the topological length of the shortest possible path connecting
every pair of nodes in the network.
Parameters
----------
D : (N x N) array_like
Weighted/unweighted, direct/undirected connection weight/length array
tran... | [
"def",
"distance_wei_floyd",
"(",
"adjacency",
",",
"transform",
"=",
"None",
")",
":",
"if",
"transform",
"is",
"not",
"None",
":",
"if",
"transform",
"==",
"'log'",
":",
"if",
"np",
".",
"logical_or",
"(",
"adjacency",
">",
"1",
",",
"adjacency",
"<",
... | Computes the topological length of the shortest possible path connecting
every pair of nodes in the network.
Parameters
----------
D : (N x N) array_like
Weighted/unweighted, direct/undirected connection weight/length array
transform : str, optional
If `adjacency` is a connection we... | [
"Computes",
"the",
"topological",
"length",
"of",
"the",
"shortest",
"possible",
"path",
"connecting",
"every",
"pair",
"of",
"nodes",
"in",
"the",
"network",
"."
] | python | train |
bspaans/python-mingus | mingus/extra/musicxml.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/musicxml.py#L303-L324 | def write_Composition(composition, filename, zip=False):
"""Create an XML file (or MXL if compressed) for a given composition."""
text = from_Composition(composition)
if not zip:
f = open(filename + '.xml', 'w')
f.write(text)
f.close()
else:
import zipfile
import ... | [
"def",
"write_Composition",
"(",
"composition",
",",
"filename",
",",
"zip",
"=",
"False",
")",
":",
"text",
"=",
"from_Composition",
"(",
"composition",
")",
"if",
"not",
"zip",
":",
"f",
"=",
"open",
"(",
"filename",
"+",
"'.xml'",
",",
"'w'",
")",
"... | Create an XML file (or MXL if compressed) for a given composition. | [
"Create",
"an",
"XML",
"file",
"(",
"or",
"MXL",
"if",
"compressed",
")",
"for",
"a",
"given",
"composition",
"."
] | python | train |
foremast/foremast | src/foremast/awslambda/cloudwatch_log_event/destroy_cloudwatch_log_event/destroy_cloudwatch_log_event.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/awslambda/cloudwatch_log_event/destroy_cloudwatch_log_event/destroy_cloudwatch_log_event.py#L24-L42 | def destroy_cloudwatch_log_event(app='', env='dev', region=''):
"""Destroy Cloudwatch log event.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion.
"""
session = b... | [
"def",
"destroy_cloudwatch_log_event",
"(",
"app",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"region",
"=",
"''",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"cloudwatch_client... | Destroy Cloudwatch log event.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
bool: True upon successful completion. | [
"Destroy",
"Cloudwatch",
"log",
"event",
"."
] | python | train |
commx/python-rrdtool | setup.py | https://github.com/commx/python-rrdtool/blob/74b7dee35c17a2558da475369699ef63408b7b6c/setup.py#L42-L119 | def compile_extensions(macros, compat=False):
"""
Compiler subroutine to test whether some functions are available
on the target system. Since the rrdtool headers shipped with most
packages do not disclose any versioning information, we cannot test
whether a given function is available that way. Ins... | [
"def",
"compile_extensions",
"(",
"macros",
",",
"compat",
"=",
"False",
")",
":",
"import",
"distutils",
".",
"sysconfig",
"import",
"distutils",
".",
"ccompiler",
"import",
"tempfile",
"import",
"shutil",
"from",
"textwrap",
"import",
"dedent",
"# common vars",
... | Compiler subroutine to test whether some functions are available
on the target system. Since the rrdtool headers shipped with most
packages do not disclose any versioning information, we cannot test
whether a given function is available that way. Instead, use this to
manually try to compile code and see... | [
"Compiler",
"subroutine",
"to",
"test",
"whether",
"some",
"functions",
"are",
"available",
"on",
"the",
"target",
"system",
".",
"Since",
"the",
"rrdtool",
"headers",
"shipped",
"with",
"most",
"packages",
"do",
"not",
"disclose",
"any",
"versioning",
"informat... | python | train |
marcotcr/lime | lime/utils/generic_utils.py | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/utils/generic_utils.py#L6-L39 | def has_arg(fn, arg_name):
"""Checks if a callable accepts a given keyword argument.
Args:
fn: callable to inspect
arg_name: string, keyword argument name to check
Returns:
bool, whether `fn` accepts a `arg_name` keyword argument.
"""
if sys.version_info < (3,):
if ... | [
"def",
"has_arg",
"(",
"fn",
",",
"arg_name",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
")",
":",
"if",
"isinstance",
"(",
"fn",
",",
"types",
".",
"FunctionType",
")",
"or",
"isinstance",
"(",
"fn",
",",
"types",
".",
"Method... | Checks if a callable accepts a given keyword argument.
Args:
fn: callable to inspect
arg_name: string, keyword argument name to check
Returns:
bool, whether `fn` accepts a `arg_name` keyword argument. | [
"Checks",
"if",
"a",
"callable",
"accepts",
"a",
"given",
"keyword",
"argument",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L256-L275 | def hide_routemap_holder_route_map_content_match_extcommunity_extcommunity_num(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map ... | [
"def",
"hide_routemap_holder_route_map_content_match_extcommunity_extcommunity_num",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
","... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
stephenmcd/gnotty | gnotty/bots/base.py | https://github.com/stephenmcd/gnotty/blob/bea3762dc9cbc3cb21a5ae7224091cf027273c40/gnotty/bots/base.py#L57-L65 | def _dispatcher(self, connection, event):
"""
This is the method in ``SimpleIRCClient`` that all IRC events
get passed through. Here we map events to our own custom
event handlers, and call them.
"""
super(BaseBot, self)._dispatcher(connection, event)
for handler ... | [
"def",
"_dispatcher",
"(",
"self",
",",
"connection",
",",
"event",
")",
":",
"super",
"(",
"BaseBot",
",",
"self",
")",
".",
"_dispatcher",
"(",
"connection",
",",
"event",
")",
"for",
"handler",
"in",
"self",
".",
"events",
"[",
"event",
".",
"eventt... | This is the method in ``SimpleIRCClient`` that all IRC events
get passed through. Here we map events to our own custom
event handlers, and call them. | [
"This",
"is",
"the",
"method",
"in",
"SimpleIRCClient",
"that",
"all",
"IRC",
"events",
"get",
"passed",
"through",
".",
"Here",
"we",
"map",
"events",
"to",
"our",
"own",
"custom",
"event",
"handlers",
"and",
"call",
"them",
"."
] | python | train |
crytic/slither | slither/core/declarations/function.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L763-L773 | def all_solidity_variables_used_as_args(self):
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solid... | [
"def",
"all_solidity_variables_used_as_args",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_solidity_variables_used_as_args",
"is",
"None",
":",
"self",
".",
"_all_solidity_variables_used_as_args",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"se... | Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender) | [
"Return",
"the",
"Soldiity",
"variables",
"directly",
"used",
"in",
"a",
"call"
] | python | train |
apache/incubator-heron | heron/tools/admin/src/python/standalone.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/admin/src/python/standalone.py#L554-L571 | def wait_for_master_to_start(single_master):
'''
Wait for a nomad master to start
'''
i = 0
while True:
try:
r = requests.get("http://%s:4646/v1/status/leader" % single_master)
if r.status_code == 200:
break
except:
Log.debug(sys.exc_info()[0])
Log.info("Waiting for clu... | [
"def",
"wait_for_master_to_start",
"(",
"single_master",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"\"http://%s:4646/v1/status/leader\"",
"%",
"single_master",
")",
"if",
"r",
".",
"status_code",
"==",
... | Wait for a nomad master to start | [
"Wait",
"for",
"a",
"nomad",
"master",
"to",
"start"
] | python | valid |
RJT1990/pyflux | pyflux/gas/gasllt.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gasllt.py#L311-L356 | def _mean_prediction(self, theta, theta_t, Y, scores, h, t_params):
""" Creates a h-step ahead mean prediction
Parameters
----------
theta : np.array
The past local level
theta_t : np.array
The past local linear trend
Y : np.array
Th... | [
"def",
"_mean_prediction",
"(",
"self",
",",
"theta",
",",
"theta_t",
",",
"Y",
",",
"scores",
",",
"h",
",",
"t_params",
")",
":",
"Y_exp",
"=",
"Y",
".",
"copy",
"(",
")",
"theta_exp",
"=",
"theta",
".",
"copy",
"(",
")",
"theta_t_exp",
"=",
"the... | Creates a h-step ahead mean prediction
Parameters
----------
theta : np.array
The past local level
theta_t : np.array
The past local linear trend
Y : np.array
The past data
scores : np.array
The past scores
h : ... | [
"Creates",
"a",
"h",
"-",
"step",
"ahead",
"mean",
"prediction"
] | python | train |
annoviko/pyclustering | pyclustering/cluster/fcm.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/fcm.py#L279-L287 | def __calculate_changes(self, updated_centers):
"""!
@brief Calculate changes between centers.
@return (float) Maximum change between centers.
"""
changes = numpy.sum(numpy.square(self.__centers - updated_centers), axis=1).T
return numpy.max(changes) | [
"def",
"__calculate_changes",
"(",
"self",
",",
"updated_centers",
")",
":",
"changes",
"=",
"numpy",
".",
"sum",
"(",
"numpy",
".",
"square",
"(",
"self",
".",
"__centers",
"-",
"updated_centers",
")",
",",
"axis",
"=",
"1",
")",
".",
"T",
"return",
"... | !
@brief Calculate changes between centers.
@return (float) Maximum change between centers. | [
"!"
] | python | valid |
autokey/autokey | lib/autokey/iomediator/_iomediator.py | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/iomediator/_iomediator.py#L124-L161 | def send_string(self, string: str):
"""
Sends the given string for output.
"""
if not string:
return
string = string.replace('\n', "<enter>")
string = string.replace('\t', "<tab>")
_logger.debug("Send via event interface")
self.__clea... | [
"def",
"send_string",
"(",
"self",
",",
"string",
":",
"str",
")",
":",
"if",
"not",
"string",
":",
"return",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\n'",
",",
"\"<enter>\"",
")",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\t'",
",",
... | Sends the given string for output. | [
"Sends",
"the",
"given",
"string",
"for",
"output",
"."
] | python | train |
mushkevych/scheduler | synergy/system/time_trigger_factory.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/system/time_trigger_factory.py#L36-L49 | def format_time_trigger_string(timer_instance):
"""
:param timer_instance: either instance of RepeatTimer or EventClock
:return: human-readable and editable string in one of two formats:
- 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM'
- 'every NNN'
"""
if isinstance(timer_instance, Repeat... | [
"def",
"format_time_trigger_string",
"(",
"timer_instance",
")",
":",
"if",
"isinstance",
"(",
"timer_instance",
",",
"RepeatTimer",
")",
":",
"return",
"TRIGGER_PREAMBLE_EVERY",
"+",
"str",
"(",
"timer_instance",
".",
"interval_new",
")",
"elif",
"isinstance",
"(",... | :param timer_instance: either instance of RepeatTimer or EventClock
:return: human-readable and editable string in one of two formats:
- 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM'
- 'every NNN' | [
":",
"param",
"timer_instance",
":",
"either",
"instance",
"of",
"RepeatTimer",
"or",
"EventClock",
":",
"return",
":",
"human",
"-",
"readable",
"and",
"editable",
"string",
"in",
"one",
"of",
"two",
"formats",
":",
"-",
"at",
"Day_of_Week",
"-",
"HH",
":... | python | train |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L1781-L1790 | def facilityMsToNet(SsVersionIndicator_presence=0):
"""FACILITY Section 9.3.9.2"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x3a) # 00111010
c = Facility()
packet = a / b / c
if SsVersionIndicator_presence is 1:
d = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0)
packet = pa... | [
"def",
"facilityMsToNet",
"(",
"SsVersionIndicator_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x3a",
")",
"# 00111010",
"c",
"=",
"Facility",
"(",
")",
"packet",
"=",
"a",... | FACILITY Section 9.3.9.2 | [
"FACILITY",
"Section",
"9",
".",
"3",
".",
"9",
".",
"2"
] | python | train |
dacut/meterer | meterer/client.py | https://github.com/dacut/meterer/blob/441e7f021e3302597f56876948a40fe8799a3375/meterer/client.py#L151-L175 | def set_limits_for_pool(self, pool, **kw):
"""
meterer.set_limits_for_pool(pool, [time_period=value])
Sets the limits for the given pool. The valid time_periods are:
year, month, week, day, hour.
"""
pool_limits = {}
for time_period in ["year", "month", "week", ... | [
"def",
"set_limits_for_pool",
"(",
"self",
",",
"pool",
",",
"*",
"*",
"kw",
")",
":",
"pool_limits",
"=",
"{",
"}",
"for",
"time_period",
"in",
"[",
"\"year\"",
",",
"\"month\"",
",",
"\"week\"",
",",
"\"day\"",
",",
"\"hour\"",
"]",
":",
"if",
"time_... | meterer.set_limits_for_pool(pool, [time_period=value])
Sets the limits for the given pool. The valid time_periods are:
year, month, week, day, hour. | [
"meterer",
".",
"set_limits_for_pool",
"(",
"pool",
"[",
"time_period",
"=",
"value",
"]",
")"
] | python | train |
RI-imaging/qpsphere | qpsphere/models/_bhfield/wrap.py | https://github.com/RI-imaging/qpsphere/blob/3cfa0e9fb8e81be8c820abbeccd47242e7972ac1/qpsphere/models/_bhfield/wrap.py#L306-L316 | def check_simulation(wdir):
"""
Check bhdebug.txt to make sure that you specify enough digits to
overcome roundoff errors.
"""
wdir = pathlib.Path(wdir)
field = wdir / "V_0Ereim.dat"
if not (field.exists() and
field.stat().st_size > 130):
msg = "Output {} does not exist o... | [
"def",
"check_simulation",
"(",
"wdir",
")",
":",
"wdir",
"=",
"pathlib",
".",
"Path",
"(",
"wdir",
")",
"field",
"=",
"wdir",
"/",
"\"V_0Ereim.dat\"",
"if",
"not",
"(",
"field",
".",
"exists",
"(",
")",
"and",
"field",
".",
"stat",
"(",
")",
".",
... | Check bhdebug.txt to make sure that you specify enough digits to
overcome roundoff errors. | [
"Check",
"bhdebug",
".",
"txt",
"to",
"make",
"sure",
"that",
"you",
"specify",
"enough",
"digits",
"to",
"overcome",
"roundoff",
"errors",
"."
] | python | train |
roman-neuhauser/py-impala | impala/__init__.py | https://github.com/roman-neuhauser/py-impala/blob/8a22def2744460d20c620beb24c00332e77125d5/impala/__init__.py#L119-L216 | def load_module(ldr, fqname):
'''Load `fqname` from under `ldr.fspath`.
The `fqname` argument is the fully qualified module name,
eg. "spam.eggs.ham". As explained above, when ::
finder.find_module("spam.eggs.ham")
is called, "spam.eggs" has already been imported and added
t... | [
"def",
"load_module",
"(",
"ldr",
",",
"fqname",
")",
":",
"scope",
"=",
"ldr",
".",
"scope",
".",
"split",
"(",
"'.'",
")",
"modpath",
"=",
"fqname",
".",
"split",
"(",
"'.'",
")",
"if",
"scope",
"!=",
"modpath",
"[",
"0",
":",
"len",
"(",
"scop... | Load `fqname` from under `ldr.fspath`.
The `fqname` argument is the fully qualified module name,
eg. "spam.eggs.ham". As explained above, when ::
finder.find_module("spam.eggs.ham")
is called, "spam.eggs" has already been imported and added
to `sys.modules`. However, the `find_... | [
"Load",
"fqname",
"from",
"under",
"ldr",
".",
"fspath",
"."
] | python | train |
data-8/datascience | datascience/maps.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/maps.py#L42-L44 | def show(self):
"""Publish HTML."""
IPython.display.display(IPython.display.HTML(self.as_html())) | [
"def",
"show",
"(",
"self",
")",
":",
"IPython",
".",
"display",
".",
"display",
"(",
"IPython",
".",
"display",
".",
"HTML",
"(",
"self",
".",
"as_html",
"(",
")",
")",
")"
] | Publish HTML. | [
"Publish",
"HTML",
"."
] | python | train |
saltstack/salt | salt/ext/ipaddress.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L251-L268 | def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
return... | [
"def",
"_count_righthand_zero_bits",
"(",
"number",
",",
"bits",
")",
":",
"if",
"number",
"==",
"0",
":",
"return",
"bits",
"for",
"i",
"in",
"range",
"(",
"bits",
")",
":",
"if",
"(",
"number",
">>",
"i",
")",
"&",
"1",
":",
"return",
"i",
"# All... | Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number. | [
"Count",
"the",
"number",
"of",
"zero",
"bits",
"on",
"the",
"right",
"hand",
"side",
"."
] | python | train |
DerMitch/fritzbox-smarthome | fritzhome/__main__.py | https://github.com/DerMitch/fritzbox-smarthome/blob/84cbd7c1b33e6256add041b0395ff5fccc01f103/fritzhome/__main__.py#L40-L62 | def actors(context):
"""Display a list of actors"""
fritz = context.obj
fritz.login()
for actor in fritz.get_actors():
click.echo("{} ({} {}; AIN {} )".format(
actor.name,
actor.manufacturer,
actor.productname,
actor.actor_id,
))
i... | [
"def",
"actors",
"(",
"context",
")",
":",
"fritz",
"=",
"context",
".",
"obj",
"fritz",
".",
"login",
"(",
")",
"for",
"actor",
"in",
"fritz",
".",
"get_actors",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"{} ({} {}; AIN {} )\"",
".",
"format",
"(",
... | Display a list of actors | [
"Display",
"a",
"list",
"of",
"actors"
] | python | train |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L3653-L3681 | def onReactionAdded(
self,
mid=None,
reaction=None,
author_id=None,
thread_id=None,
thread_type=None,
ts=None,
msg=None,
):
"""
Called when the client is listening, and somebody reacts to a message
:param mid: Message ID, that ... | [
"def",
"onReactionAdded",
"(",
"self",
",",
"mid",
"=",
"None",
",",
"reaction",
"=",
"None",
",",
"author_id",
"=",
"None",
",",
"thread_id",
"=",
"None",
",",
"thread_type",
"=",
"None",
",",
"ts",
"=",
"None",
",",
"msg",
"=",
"None",
",",
")",
... | Called when the client is listening, and somebody reacts to a message
:param mid: Message ID, that user reacted to
:param reaction: Reaction
:param add_reaction: Whether user added or removed reaction
:param author_id: The ID of the person who reacted to the message
:param threa... | [
"Called",
"when",
"the",
"client",
"is",
"listening",
"and",
"somebody",
"reacts",
"to",
"a",
"message"
] | python | train |
instacart/lore | lore/env.py | https://github.com/instacart/lore/blob/0367bde9a52e69162832906acc61e8d65c5ec5d4/lore/env.py#L82-L123 | def require(packages):
"""Ensures that a pypi package has been installed into the App's python environment.
If not, the package will be installed and your env will be rebooted.
Example:
::
lore.env.require('pandas')
# -> pandas is required. Dependencies added to requirement... | [
"def",
"require",
"(",
"packages",
")",
":",
"global",
"INSTALLED_PACKAGES",
",",
"_new_requirements",
"if",
"_new_requirements",
":",
"INSTALLED_PACKAGES",
"=",
"None",
"set_installed_packages",
"(",
")",
"if",
"not",
"INSTALLED_PACKAGES",
":",
"return",
"if",
"not... | Ensures that a pypi package has been installed into the App's python environment.
If not, the package will be installed and your env will be rebooted.
Example:
::
lore.env.require('pandas')
# -> pandas is required. Dependencies added to requirements.txt
:param packages: re... | [
"Ensures",
"that",
"a",
"pypi",
"package",
"has",
"been",
"installed",
"into",
"the",
"App",
"s",
"python",
"environment",
".",
"If",
"not",
"the",
"package",
"will",
"be",
"installed",
"and",
"your",
"env",
"will",
"be",
"rebooted",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3997-L4001 | def htmlDocContentDumpOutput(self, buf, encoding):
"""Dump an HTML document. Formating return/spaces are added. """
if buf is None: buf__o = None
else: buf__o = buf._o
libxml2mod.htmlDocContentDumpOutput(buf__o, self._o, encoding) | [
"def",
"htmlDocContentDumpOutput",
"(",
"self",
",",
"buf",
",",
"encoding",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf__o",
"=",
"None",
"else",
":",
"buf__o",
"=",
"buf",
".",
"_o",
"libxml2mod",
".",
"htmlDocContentDumpOutput",
"(",
"buf__o",
",",
... | Dump an HTML document. Formating return/spaces are added. | [
"Dump",
"an",
"HTML",
"document",
".",
"Formating",
"return",
"/",
"spaces",
"are",
"added",
"."
] | python | train |
projectshift/shift-boiler | boiler/user/util/oauth_providers.py | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/user/util/oauth_providers.py#L57-L65 | def register_token_getter(self, provider):
""" Register callback to retrieve token from session """
app = oauth.remote_apps[provider]
decorator = getattr(app, 'tokengetter')
def getter(token=None):
return self.token_getter(provider, token)
decorator(getter) | [
"def",
"register_token_getter",
"(",
"self",
",",
"provider",
")",
":",
"app",
"=",
"oauth",
".",
"remote_apps",
"[",
"provider",
"]",
"decorator",
"=",
"getattr",
"(",
"app",
",",
"'tokengetter'",
")",
"def",
"getter",
"(",
"token",
"=",
"None",
")",
":... | Register callback to retrieve token from session | [
"Register",
"callback",
"to",
"retrieve",
"token",
"from",
"session"
] | python | train |
lsst-sqre/zenodio | zenodio/harvest.py | https://github.com/lsst-sqre/zenodio/blob/24283e84bee5714450e4f206ec024c4d32f2e761/zenodio/harvest.py#L258-L317 | def _pluralize(value, item_key):
""""Force the value of a datacite3 key to be a list.
>>> _pluralize(xml_input['authors'], 'author')
['Sick, Jonathan', 'Economou, Frossie']
Background
----------
When `xmltodict` proceses metadata, it turns XML tags into new key-value
pairs whenever possibl... | [
"def",
"_pluralize",
"(",
"value",
",",
"item_key",
")",
":",
"v",
"=",
"value",
"[",
"item_key",
"]",
"if",
"not",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"# Force a singular value to be a list",
"return",
"[",
"v",
"]",
"else",
":",
"return",
"v... | Force the value of a datacite3 key to be a list.
>>> _pluralize(xml_input['authors'], 'author')
['Sick, Jonathan', 'Economou, Frossie']
Background
----------
When `xmltodict` proceses metadata, it turns XML tags into new key-value
pairs whenever possible, even if the value should semantically ... | [
"Force",
"the",
"value",
"of",
"a",
"datacite3",
"key",
"to",
"be",
"a",
"list",
"."
] | python | train |
ChrisBeaumont/smother | smother/cli.py | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L59-L65 | def diff(ctx, branch):
"""
Determine which tests intersect a git diff.
"""
diff = GitDiffReporter(branch)
regions = diff.changed_intervals()
_report_from_regions(regions, ctx.obj, file_factory=diff.old_file) | [
"def",
"diff",
"(",
"ctx",
",",
"branch",
")",
":",
"diff",
"=",
"GitDiffReporter",
"(",
"branch",
")",
"regions",
"=",
"diff",
".",
"changed_intervals",
"(",
")",
"_report_from_regions",
"(",
"regions",
",",
"ctx",
".",
"obj",
",",
"file_factory",
"=",
... | Determine which tests intersect a git diff. | [
"Determine",
"which",
"tests",
"intersect",
"a",
"git",
"diff",
"."
] | python | train |
espenak/djangosenchatools | djangosenchatools/buildserver.py | https://github.com/espenak/djangosenchatools/blob/da1bca9365300de303e833de4b4bd57671c1d11a/djangosenchatools/buildserver.py#L23-L38 | def run(self):
"""
Sets up the live server and databases, and then loops over handling
http requests.
"""
server_address = (self.host, self.port)
threading = True
if threading:
httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {})
el... | [
"def",
"run",
"(",
"self",
")",
":",
"server_address",
"=",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"threading",
"=",
"True",
"if",
"threading",
":",
"httpd_cls",
"=",
"type",
"(",
"'WSGIServer'",
",",
"(",
"ThreadingMixIn",
",",
"WSGI... | Sets up the live server and databases, and then loops over handling
http requests. | [
"Sets",
"up",
"the",
"live",
"server",
"and",
"databases",
"and",
"then",
"loops",
"over",
"handling",
"http",
"requests",
"."
] | python | train |
manahl/arctic | arctic/date/_util.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/date/_util.py#L22-L82 | def string_to_daterange(str_range, delimiter='-', as_dates=False, interval=CLOSED_CLOSED):
"""
Convert a string to a DateRange type. If you put only one date, it generates the
relevant range for just that date or datetime till 24 hours later. You can optionally
use mixtures of []/() around the DateRange... | [
"def",
"string_to_daterange",
"(",
"str_range",
",",
"delimiter",
"=",
"'-'",
",",
"as_dates",
"=",
"False",
",",
"interval",
"=",
"CLOSED_CLOSED",
")",
":",
"num_dates",
"=",
"str_range",
".",
"count",
"(",
"delimiter",
")",
"+",
"1",
"if",
"num_dates",
"... | Convert a string to a DateRange type. If you put only one date, it generates the
relevant range for just that date or datetime till 24 hours later. You can optionally
use mixtures of []/() around the DateRange for OPEN/CLOSED interval behaviour.
Parameters
----------
str_range : `String`
Th... | [
"Convert",
"a",
"string",
"to",
"a",
"DateRange",
"type",
".",
"If",
"you",
"put",
"only",
"one",
"date",
"it",
"generates",
"the",
"relevant",
"range",
"for",
"just",
"that",
"date",
"or",
"datetime",
"till",
"24",
"hours",
"later",
".",
"You",
"can",
... | python | train |
wtolson/gnsq | gnsq/nsqd.py | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L580-L583 | def empty_topic(self, topic):
"""Empty all the queued messages for an existing topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/empty', fields={'topic': topic}) | [
"def",
"empty_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/empty'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | Empty all the queued messages for an existing topic. | [
"Empty",
"all",
"the",
"queued",
"messages",
"for",
"an",
"existing",
"topic",
"."
] | python | train |
vertexproject/synapse | synapse/lib/agenda.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/agenda.py#L536-L558 | async def delete(self, iden):
'''
Delete an appointment
'''
appt = self.appts.get(iden)
if appt is None:
raise s_exc.NoSuchIden()
try:
heappos = self.apptheap.index(appt)
except ValueError:
pass # this is OK, just a non-recurr... | [
"async",
"def",
"delete",
"(",
"self",
",",
"iden",
")",
":",
"appt",
"=",
"self",
".",
"appts",
".",
"get",
"(",
"iden",
")",
"if",
"appt",
"is",
"None",
":",
"raise",
"s_exc",
".",
"NoSuchIden",
"(",
")",
"try",
":",
"heappos",
"=",
"self",
"."... | Delete an appointment | [
"Delete",
"an",
"appointment"
] | python | train |
nerdvegas/rez | src/rez/vendor/amqp/method_framing.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/method_framing.py#L99-L130 | def _next_method(self):
"""Read the next method from the source, once one complete method has
been assembled it is placed in the internal queue."""
queue = self.queue
put = self._quick_put
read_frame = self.source.read_frame
while not queue:
try:
... | [
"def",
"_next_method",
"(",
"self",
")",
":",
"queue",
"=",
"self",
".",
"queue",
"put",
"=",
"self",
".",
"_quick_put",
"read_frame",
"=",
"self",
".",
"source",
".",
"read_frame",
"while",
"not",
"queue",
":",
"try",
":",
"frame_type",
",",
"channel",
... | Read the next method from the source, once one complete method has
been assembled it is placed in the internal queue. | [
"Read",
"the",
"next",
"method",
"from",
"the",
"source",
"once",
"one",
"complete",
"method",
"has",
"been",
"assembled",
"it",
"is",
"placed",
"in",
"the",
"internal",
"queue",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/core/selectiontools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/selectiontools.py#L734-L743 | def deselect_nodenames(self, *substrings: str) -> 'Selection':
"""Restrict the current selection to all nodes with a name
not containing at least one of the given substrings (does not
affect any elements).
See the documentation on method |Selection.search_nodenames| for
addition... | [
"def",
"deselect_nodenames",
"(",
"self",
",",
"*",
"substrings",
":",
"str",
")",
"->",
"'Selection'",
":",
"self",
".",
"nodes",
"-=",
"self",
".",
"search_nodenames",
"(",
"*",
"substrings",
")",
".",
"nodes",
"return",
"self"
] | Restrict the current selection to all nodes with a name
not containing at least one of the given substrings (does not
affect any elements).
See the documentation on method |Selection.search_nodenames| for
additional information. | [
"Restrict",
"the",
"current",
"selection",
"to",
"all",
"nodes",
"with",
"a",
"name",
"not",
"containing",
"at",
"least",
"one",
"of",
"the",
"given",
"substrings",
"(",
"does",
"not",
"affect",
"any",
"elements",
")",
"."
] | python | train |
Scoppio/RagnarokEngine3 | Tutorials/Platforming Block - PyGame Release/Game/Code/Ragnarok.py | https://github.com/Scoppio/RagnarokEngine3/blob/4395d419ccd64fe9327c41f200b72ee0176ad896/Tutorials/Platforming Block - PyGame Release/Game/Code/Ragnarok.py#L1097-L1107 | def request_object(self):
"""Grab an object from the pool. If the pool is empty, a new object will be generated and returned."""
obj_to_return = None
if self.queue.count > 0:
obj_to_return = self.__dequeue()
else:
#The queue is empty, generate a new item.
... | [
"def",
"request_object",
"(",
"self",
")",
":",
"obj_to_return",
"=",
"None",
"if",
"self",
".",
"queue",
".",
"count",
">",
"0",
":",
"obj_to_return",
"=",
"self",
".",
"__dequeue",
"(",
")",
"else",
":",
"#The queue is empty, generate a new item.",
"self",
... | Grab an object from the pool. If the pool is empty, a new object will be generated and returned. | [
"Grab",
"an",
"object",
"from",
"the",
"pool",
".",
"If",
"the",
"pool",
"is",
"empty",
"a",
"new",
"object",
"will",
"be",
"generated",
"and",
"returned",
"."
] | python | train |
ga4gh/ga4gh-server | ga4gh/server/datamodel/obo_parser.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/obo_parser.py#L191-L211 | def _add_to_typedef(self, typedef_curr, line, lnum):
"""Add new fields to the current typedef."""
mtch = re.match(r'^(\S+):\s*(\S.*)$', line)
if mtch:
field_name = mtch.group(1)
field_value = mtch.group(2).split('!')[0].rstrip()
if field_name == "id":
... | [
"def",
"_add_to_typedef",
"(",
"self",
",",
"typedef_curr",
",",
"line",
",",
"lnum",
")",
":",
"mtch",
"=",
"re",
".",
"match",
"(",
"r'^(\\S+):\\s*(\\S.*)$'",
",",
"line",
")",
"if",
"mtch",
":",
"field_name",
"=",
"mtch",
".",
"group",
"(",
"1",
")"... | Add new fields to the current typedef. | [
"Add",
"new",
"fields",
"to",
"the",
"current",
"typedef",
"."
] | python | train |
tanghaibao/jcvi | jcvi/variation/cnv.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/cnv.py#L541-L547 | def counter_format(counter):
""" Pretty print a counter so that it appears as: "2:200,3:100,4:20"
"""
if not counter:
return "na"
return ",".join("{}:{}".format(*z) for z in sorted(counter.items())) | [
"def",
"counter_format",
"(",
"counter",
")",
":",
"if",
"not",
"counter",
":",
"return",
"\"na\"",
"return",
"\",\"",
".",
"join",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"*",
"z",
")",
"for",
"z",
"in",
"sorted",
"(",
"counter",
".",
"items",
"(",
")... | Pretty print a counter so that it appears as: "2:200,3:100,4:20" | [
"Pretty",
"print",
"a",
"counter",
"so",
"that",
"it",
"appears",
"as",
":",
"2",
":",
"200",
"3",
":",
"100",
"4",
":",
"20"
] | python | train |
sassoo/goldman | goldman/resources/s3_model.py | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/resources/s3_model.py#L84-L118 | def on_post(self, req, resp, rid):
""" Deserialize the file upload & save it to S3
File uploads are associated with a model of some
kind. Ensure the associating model exists first &
foremost.
"""
signals.pre_req.send(self.model)
signals.pre_req_upload.send(self.... | [
"def",
"on_post",
"(",
"self",
",",
"req",
",",
"resp",
",",
"rid",
")",
":",
"signals",
".",
"pre_req",
".",
"send",
"(",
"self",
".",
"model",
")",
"signals",
".",
"pre_req_upload",
".",
"send",
"(",
"self",
".",
"model",
")",
"props",
"=",
"req"... | Deserialize the file upload & save it to S3
File uploads are associated with a model of some
kind. Ensure the associating model exists first &
foremost. | [
"Deserialize",
"the",
"file",
"upload",
"&",
"save",
"it",
"to",
"S3"
] | python | train |
dcramer/django-ratings | djangoratings/templatetags/ratings.py | https://github.com/dcramer/django-ratings/blob/4d00dedc920a4e32d650dc12d5f480c51fc6216c/djangoratings/templatetags/ratings.py#L34-L52 | def do_rating_by_request(parser, token):
"""
Retrieves the ``Vote`` cast by a user on a particular object and
stores it in a context variable. If the user has not voted, the
context variable will be 0.
Example usage::
{% rating_by_request request on instance as vote %}
"""
... | [
"def",
"do_rating_by_request",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"6",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'%s' tag takes exac... | Retrieves the ``Vote`` cast by a user on a particular object and
stores it in a context variable. If the user has not voted, the
context variable will be 0.
Example usage::
{% rating_by_request request on instance as vote %} | [
"Retrieves",
"the",
"Vote",
"cast",
"by",
"a",
"user",
"on",
"a",
"particular",
"object",
"and",
"stores",
"it",
"in",
"a",
"context",
"variable",
".",
"If",
"the",
"user",
"has",
"not",
"voted",
"the",
"context",
"variable",
"will",
"be",
"0",
".",
"E... | python | train |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/geoff.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/geoff.py#L37-L67 | def edge2geoff(from_node, to_node, properties, edge_relationship_name, encoder):
"""converts a NetworkX edge into a Geoff string.
Parameters
----------
from_node : str or int
the ID of a NetworkX source node
to_node : str or int
the ID of a NetworkX target node
properties : dict... | [
"def",
"edge2geoff",
"(",
"from_node",
",",
"to_node",
",",
"properties",
",",
"edge_relationship_name",
",",
"encoder",
")",
":",
"edge_string",
"=",
"None",
"if",
"properties",
":",
"args",
"=",
"[",
"from_node",
",",
"edge_relationship_name",
",",
"encoder",
... | converts a NetworkX edge into a Geoff string.
Parameters
----------
from_node : str or int
the ID of a NetworkX source node
to_node : str or int
the ID of a NetworkX target node
properties : dict
a dictionary of edge attributes
edge_relationship_name : str
string... | [
"converts",
"a",
"NetworkX",
"edge",
"into",
"a",
"Geoff",
"string",
"."
] | python | train |
mattharrison/rst2odp | odplib/preso.py | https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1705-L1721 | def style_node(self, additional_style_attrib=None):
"""
generate a style node (for automatic-styles)
could specify additional attributes such as
'style:parent-style-name' or 'style:list-style-name'
"""
style_attrib = {"style:name": self.name, "style:family": self.FAMILY... | [
"def",
"style_node",
"(",
"self",
",",
"additional_style_attrib",
"=",
"None",
")",
":",
"style_attrib",
"=",
"{",
"\"style:name\"",
":",
"self",
".",
"name",
",",
"\"style:family\"",
":",
"self",
".",
"FAMILY",
"}",
"if",
"additional_style_attrib",
":",
"styl... | generate a style node (for automatic-styles)
could specify additional attributes such as
'style:parent-style-name' or 'style:list-style-name' | [
"generate",
"a",
"style",
"node",
"(",
"for",
"automatic",
"-",
"styles",
")"
] | python | train |
numenta/htmresearch | htmresearch/regions/ColumnPoolerRegion.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/ColumnPoolerRegion.py#L421-L477 | def compute(self, inputs, outputs):
"""
Run one iteration of compute.
Note that if the reset signal is True (1) we assume this iteration
represents the *end* of a sequence. The output will contain the
representation to this point and any history will then be reset. The output
at the next comput... | [
"def",
"compute",
"(",
"self",
",",
"inputs",
",",
"outputs",
")",
":",
"# Handle reset first (should be sent with an empty signal)",
"if",
"\"resetIn\"",
"in",
"inputs",
":",
"assert",
"len",
"(",
"inputs",
"[",
"\"resetIn\"",
"]",
")",
"==",
"1",
"if",
"inputs... | Run one iteration of compute.
Note that if the reset signal is True (1) we assume this iteration
represents the *end* of a sequence. The output will contain the
representation to this point and any history will then be reset. The output
at the next compute will start fresh, presumably with bursting col... | [
"Run",
"one",
"iteration",
"of",
"compute",
"."
] | python | train |
richardchien/python-cqhttp | cqhttp_helper.py | https://github.com/richardchien/python-cqhttp/blob/1869819a8f89001e3f70668e31afc6c78f7f5bc2/cqhttp_helper.py#L321-L338 | def send_msg_async(self, *, message_type, user_id=None, group_id=None, discuss_id=None, message, auto_escape=False):
"""
发送消息 (异步版本)
------------
:param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组
:param int user_id: 对方 QQ 号(消息类型为 `private` 时需要)
... | [
"def",
"send_msg_async",
"(",
"self",
",",
"*",
",",
"message_type",
",",
"user_id",
"=",
"None",
",",
"group_id",
"=",
"None",
",",
"discuss_id",
"=",
"None",
",",
"message",
",",
"auto_escape",
"=",
"False",
")",
":",
"return",
"super",
"(",
")",
"."... | 发送消息 (异步版本)
------------
:param str message_type: 消息类型,支持 `private`、`group`、`discuss`,分别对应私聊、群组、讨论组
:param int user_id: 对方 QQ 号(消息类型为 `private` 时需要)
:param int group_id: 群号(消息类型为 `group` 时需要)
:param int discuss_id: 讨论组 ID(需要从上报消息中获取,消息类型为 `discuss` 时需要)
:param str | lis... | [
"发送消息",
"(",
"异步版本",
")"
] | python | valid |
HPAC/matchpy | matchpy/expressions/functions.py | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/functions.py#L103-L112 | def get_variables(expression, variables=None):
"""Returns the set of variable names in the given expression."""
if variables is None:
variables = set()
if hasattr(expression, 'variable_name') and expression.variable_name is not None:
variables.add(expression.variable_name)
if isinstance(... | [
"def",
"get_variables",
"(",
"expression",
",",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"set",
"(",
")",
"if",
"hasattr",
"(",
"expression",
",",
"'variable_name'",
")",
"and",
"expression",
".",
"variabl... | Returns the set of variable names in the given expression. | [
"Returns",
"the",
"set",
"of",
"variable",
"names",
"in",
"the",
"given",
"expression",
"."
] | python | train |
odlgroup/odl | odl/operator/tensor_ops.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/tensor_ops.py#L1159-L1199 | def adjoint(self):
"""Adjoint of the sampling operator, a `WeightedSumSamplingOperator`.
If each sampling point occurs only once, the adjoint consists
in inserting the given values into the output at the sampling
points. Duplicate sampling points are weighted with their
multipli... | [
"def",
"adjoint",
"(",
"self",
")",
":",
"if",
"self",
".",
"variant",
"==",
"'point_eval'",
":",
"variant",
"=",
"'dirac'",
"elif",
"self",
".",
"variant",
"==",
"'integrate'",
":",
"variant",
"=",
"'char_fun'",
"else",
":",
"raise",
"RuntimeError",
"(",
... | Adjoint of the sampling operator, a `WeightedSumSamplingOperator`.
If each sampling point occurs only once, the adjoint consists
in inserting the given values into the output at the sampling
points. Duplicate sampling points are weighted with their
multiplicity.
Examples
... | [
"Adjoint",
"of",
"the",
"sampling",
"operator",
"a",
"WeightedSumSamplingOperator",
"."
] | python | train |
RJT1990/pyflux | pyflux/garch/egarchm.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/garch/egarchm.py#L250-L307 | def _sim_prediction(self, lmda, Y, scores, h, t_params, simulations):
""" Simulates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past ... | [
"def",
"_sim_prediction",
"(",
"self",
",",
"lmda",
",",
"Y",
",",
"scores",
",",
"h",
",",
"t_params",
",",
"simulations",
")",
":",
"sim_vector",
"=",
"np",
".",
"zeros",
"(",
"[",
"simulations",
",",
"h",
"]",
")",
"for",
"n",
"in",
"range",
"("... | Simulates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
h : int
How many steps ahead for the prediction
... | [
"Simulates",
"a",
"h",
"-",
"step",
"ahead",
"mean",
"prediction"
] | python | train |
resonai/ybt | yabt/buildcontext.py | https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/buildcontext.py#L350-L441 | def run_in_buildenv(
self, buildenv_target_name: str, cmd: list, cmd_env: dict=None,
work_dir: str=None, auto_uid: bool=True, runtime: str=None,
**kwargs):
"""Run a command in a named BuildEnv Docker image.
:param buildenv_target_name: A named Docker image target in ... | [
"def",
"run_in_buildenv",
"(",
"self",
",",
"buildenv_target_name",
":",
"str",
",",
"cmd",
":",
"list",
",",
"cmd_env",
":",
"dict",
"=",
"None",
",",
"work_dir",
":",
"str",
"=",
"None",
",",
"auto_uid",
":",
"bool",
"=",
"True",
",",
"runtime",
":",... | Run a command in a named BuildEnv Docker image.
:param buildenv_target_name: A named Docker image target in which the
command should be run.
:param cmd: The command to run, as you'd pass to subprocess.run()
:param cmd_env: A dictionary of environment variabl... | [
"Run",
"a",
"command",
"in",
"a",
"named",
"BuildEnv",
"Docker",
"image",
"."
] | python | train |
genialis/resolwe | resolwe/flow/managers/dispatcher.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/dispatcher.py#L343-L353 | def _marshal_settings(self):
"""Marshal Django settings into a serializable object.
:return: The serialized settings.
:rtype: dict
"""
result = {}
for key in dir(settings):
if any(map(key.startswith, ['FLOW_', 'RESOLWE_', 'CELERY_'])):
result[... | [
"def",
"_marshal_settings",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"dir",
"(",
"settings",
")",
":",
"if",
"any",
"(",
"map",
"(",
"key",
".",
"startswith",
",",
"[",
"'FLOW_'",
",",
"'RESOLWE_'",
",",
"'CELERY_'",
"]",
... | Marshal Django settings into a serializable object.
:return: The serialized settings.
:rtype: dict | [
"Marshal",
"Django",
"settings",
"into",
"a",
"serializable",
"object",
"."
] | python | train |
ekmmetering/ekmmeters | ekmmeters.py | https://github.com/ekmmetering/ekmmeters/blob/b3748bdf30263bfa46ea40157bdf8df2522e1904/ekmmeters.py#L3448-L3468 | def request(self, send_terminator = False):
""" Combined A and B read for V4 meter.
Args:
send_terminator (bool): Send termination string at end of read.
Returns:
bool: True on completion.
"""
try:
retA = self.requestA()
retB = se... | [
"def",
"request",
"(",
"self",
",",
"send_terminator",
"=",
"False",
")",
":",
"try",
":",
"retA",
"=",
"self",
".",
"requestA",
"(",
")",
"retB",
"=",
"self",
".",
"requestB",
"(",
")",
"if",
"retA",
"and",
"retB",
":",
"self",
".",
"makeAB",
"(",... | Combined A and B read for V4 meter.
Args:
send_terminator (bool): Send termination string at end of read.
Returns:
bool: True on completion. | [
"Combined",
"A",
"and",
"B",
"read",
"for",
"V4",
"meter",
"."
] | python | test |
Alignak-monitoring/alignak | alignak/objects/satellitelink.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/satellitelink.py#L439-L480 | def manages(self, cfg_part):
"""Tell if the satellite is managing this configuration part
The managed configuration is formed as a dictionary indexed on the link instance_id:
{
u'SchedulerLink_1': {
u'hash': u'4d08630a3483e1eac7898e7a721bd5d7768c8320',
... | [
"def",
"manages",
"(",
"self",
",",
"cfg_part",
")",
":",
"logger",
".",
"debug",
"(",
"\"Do I (%s/%s) manage: %s, my managed configuration(s): %s\"",
",",
"self",
".",
"type",
",",
"self",
".",
"name",
",",
"cfg_part",
",",
"self",
".",
"cfg_managed",
")",
"#... | Tell if the satellite is managing this configuration part
The managed configuration is formed as a dictionary indexed on the link instance_id:
{
u'SchedulerLink_1': {
u'hash': u'4d08630a3483e1eac7898e7a721bd5d7768c8320',
u'push_flavor': u'4d08630a3483e1eac78... | [
"Tell",
"if",
"the",
"satellite",
"is",
"managing",
"this",
"configuration",
"part"
] | python | train |
saltstack/salt | salt/modules/lxc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1070-L1122 | def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
... | [
"def",
"_get_base",
"(",
"*",
"*",
"kwargs",
")",
":",
"profile",
"=",
"get_container_profile",
"(",
"copy",
".",
"deepcopy",
"(",
"kwargs",
".",
"get",
"(",
"'profile'",
")",
")",
")",
"kw_overrides",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
... | If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned. | [
"If",
"the",
"needed",
"base",
"does",
"not",
"exist",
"then",
"create",
"it",
"if",
"it",
"does",
"exist",
"create",
"nothing",
"and",
"return",
"the",
"name",
"of",
"the",
"base",
"lxc",
"container",
"so",
"it",
"can",
"be",
"cloned",
"."
] | python | train |
pycontribs/pyrax | pyrax/object_storage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L1626-L1636 | def download(self, directory, structure=True):
"""
Fetches the object from storage, and writes it to the specified
directory. The directory must exist before calling this method.
If the object name represents a nested folder structure, such as
"foo/bar/baz.txt", that folder stru... | [
"def",
"download",
"(",
"self",
",",
"directory",
",",
"structure",
"=",
"True",
")",
":",
"return",
"self",
".",
"manager",
".",
"download",
"(",
"self",
",",
"directory",
",",
"structure",
"=",
"structure",
")"
] | Fetches the object from storage, and writes it to the specified
directory. The directory must exist before calling this method.
If the object name represents a nested folder structure, such as
"foo/bar/baz.txt", that folder structure will be created in the target
directory by default. I... | [
"Fetches",
"the",
"object",
"from",
"storage",
"and",
"writes",
"it",
"to",
"the",
"specified",
"directory",
".",
"The",
"directory",
"must",
"exist",
"before",
"calling",
"this",
"method",
"."
] | python | train |
jedie/DragonPy | dragonpy/Dragon32/MC6821_PIA.py | https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L346-L367 | def read_PIA0_B_data(self, cpu_cycles, op_address, address):
"""
read from 0xff02 -> PIA 0 B side Data reg.
bit 7 | PB7 | keyboard matrix column 8
bit 6 | PB6 | keyboard matrix column 7 / ram size output
bit 5 | PB5 | keyboard matrix column 6
bit 4 | PB4 | keyboard matri... | [
"def",
"read_PIA0_B_data",
"(",
"self",
",",
"cpu_cycles",
",",
"op_address",
",",
"address",
")",
":",
"value",
"=",
"self",
".",
"pia_0_B_data",
".",
"value",
"# $ff02",
"log",
".",
"debug",
"(",
"\"%04x| read $%04x (PIA 0 B side Data reg.) send $%02x (%s) back.\\t|... | read from 0xff02 -> PIA 0 B side Data reg.
bit 7 | PB7 | keyboard matrix column 8
bit 6 | PB6 | keyboard matrix column 7 / ram size output
bit 5 | PB5 | keyboard matrix column 6
bit 4 | PB4 | keyboard matrix column 5
bit 3 | PB3 | keyboard matrix column 4
bit 2 | PB2 | k... | [
"read",
"from",
"0xff02",
"-",
">",
"PIA",
"0",
"B",
"side",
"Data",
"reg",
"."
] | python | train |
bukun/TorCMS | torcms/model/user_model.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/user_model.py#L241-L250 | def delete_by_user_name(user_name):
'''
Delete user in the database by `user_name`.
'''
try:
del_count = TabMember.delete().where(TabMember.user_name == user_name)
del_count.execute()
return True
except:
return False | [
"def",
"delete_by_user_name",
"(",
"user_name",
")",
":",
"try",
":",
"del_count",
"=",
"TabMember",
".",
"delete",
"(",
")",
".",
"where",
"(",
"TabMember",
".",
"user_name",
"==",
"user_name",
")",
"del_count",
".",
"execute",
"(",
")",
"return",
"True",... | Delete user in the database by `user_name`. | [
"Delete",
"user",
"in",
"the",
"database",
"by",
"user_name",
"."
] | python | train |
wmayner/pyphi | pyphi/actual.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/actual.py#L387-L420 | def find_causal_link(self, direction, mechanism, purviews=False,
allow_neg=False):
"""Return the maximally irreducible cause or effect ratio for a
mechanism.
Args:
direction (str): The temporal direction, specifying cause or
effect.
... | [
"def",
"find_causal_link",
"(",
"self",
",",
"direction",
",",
"mechanism",
",",
"purviews",
"=",
"False",
",",
"allow_neg",
"=",
"False",
")",
":",
"purviews",
"=",
"self",
".",
"potential_purviews",
"(",
"direction",
",",
"mechanism",
",",
"purviews",
")",... | Return the maximally irreducible cause or effect ratio for a
mechanism.
Args:
direction (str): The temporal direction, specifying cause or
effect.
mechanism (tuple[int]): The mechanism to be tested for
irreducibility.
Keyword Args:
... | [
"Return",
"the",
"maximally",
"irreducible",
"cause",
"or",
"effect",
"ratio",
"for",
"a",
"mechanism",
"."
] | python | train |
halcy/Mastodon.py | mastodon/Mastodon.py | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L2443-L2458 | def __datetime_to_epoch(self, date_time):
"""
Converts a python datetime to unix epoch, accounting for
time zones and such.
Assumes UTC if timezone is not given.
"""
date_time_utc = None
if date_time.tzinfo is None:
date_time_utc = date_time.replace(t... | [
"def",
"__datetime_to_epoch",
"(",
"self",
",",
"date_time",
")",
":",
"date_time_utc",
"=",
"None",
"if",
"date_time",
".",
"tzinfo",
"is",
"None",
":",
"date_time_utc",
"=",
"date_time",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"else"... | Converts a python datetime to unix epoch, accounting for
time zones and such.
Assumes UTC if timezone is not given. | [
"Converts",
"a",
"python",
"datetime",
"to",
"unix",
"epoch",
"accounting",
"for",
"time",
"zones",
"and",
"such",
"."
] | python | train |
Terrance/SkPy | skpy/conn.py | https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L312-L327 | def writeToken(self):
"""
Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time.
"""
# Write token file privately.
with os.fdopen(os.open(self.tokenFile, os.O_WRONLY | os.O_CREAT, 0o600), "w") ... | [
"def",
"writeToken",
"(",
"self",
")",
":",
"# Write token file privately.",
"with",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"self",
".",
"tokenFile",
",",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREAT",
",",
"0o600",
")",
",",
"\"w\"",
")"... | Store details of the current connection in the named file.
This can be used by :meth:`readToken` to re-authenticate at a later time. | [
"Store",
"details",
"of",
"the",
"current",
"connection",
"in",
"the",
"named",
"file",
"."
] | python | test |
datosgobar/pydatajson | pydatajson/helpers.py | https://github.com/datosgobar/pydatajson/blob/3141082ffbaa295e2deaf6ffbbc5a59f5859960e/pydatajson/helpers.py#L384-L394 | def find_ws_name(wb, name):
"""Busca una hoja en un workbook sin importar mayúsculas/minúsculas."""
if isinstance(wb, string_types):
# FIXME: importar o borrar segun corresponda
wb = load_workbook(wb, read_only=True, data_only=True)
for sheetname in wb.sheetnames:
if sheetname.lower... | [
"def",
"find_ws_name",
"(",
"wb",
",",
"name",
")",
":",
"if",
"isinstance",
"(",
"wb",
",",
"string_types",
")",
":",
"# FIXME: importar o borrar segun corresponda",
"wb",
"=",
"load_workbook",
"(",
"wb",
",",
"read_only",
"=",
"True",
",",
"data_only",
"=",
... | Busca una hoja en un workbook sin importar mayúsculas/minúsculas. | [
"Busca",
"una",
"hoja",
"en",
"un",
"workbook",
"sin",
"importar",
"mayúsculas",
"/",
"minúsculas",
"."
] | python | train |
EventRegistry/event-registry-python | eventregistry/EventForText.py | https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/EventForText.py#L42-L57 | def compute(self,
text, # text for which to find the most similar event
lang = "eng"): # language in which the text is written
"""
compute the list of most similar events for the given text
"""
params = { "lang": lang, "text": text, "topClusters... | [
"def",
"compute",
"(",
"self",
",",
"text",
",",
"# text for which to find the most similar event",
"lang",
"=",
"\"eng\"",
")",
":",
"# language in which the text is written",
"params",
"=",
"{",
"\"lang\"",
":",
"lang",
",",
"\"text\"",
":",
"text",
",",
"\"topClu... | compute the list of most similar events for the given text | [
"compute",
"the",
"list",
"of",
"most",
"similar",
"events",
"for",
"the",
"given",
"text"
] | python | train |
SiLab-Bonn/basil | basil/HL/GPAC.py | https://github.com/SiLab-Bonn/basil/blob/99052482d9334dd1f5598eb2d2fb4d5399a32291/basil/HL/GPAC.py#L830-L837 | def get_over_current(self, channel):
'''Reading over current status of power channel
'''
try:
bit = self._ch_map[channel]['GPIOOC']['bit']
except KeyError:
raise ValueError('get_over_current() not supported for channel %s' % channel)
return not self._get_p... | [
"def",
"get_over_current",
"(",
"self",
",",
"channel",
")",
":",
"try",
":",
"bit",
"=",
"self",
".",
"_ch_map",
"[",
"channel",
"]",
"[",
"'GPIOOC'",
"]",
"[",
"'bit'",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'get_over_current() not ... | Reading over current status of power channel | [
"Reading",
"over",
"current",
"status",
"of",
"power",
"channel"
] | python | train |
eqcorrscan/EQcorrscan | eqcorrscan/utils/catalog_to_dd.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/catalog_to_dd.py#L194-L214 | def sfiles_to_event(sfile_list):
"""
Write an event.dat file from a list of Seisan events
:type sfile_list: list
:param sfile_list: List of s-files to sort and put into the database
:returns: List of tuples of event ID (int) and Sfile name
"""
event_list = []
sort_list = [(readheader(s... | [
"def",
"sfiles_to_event",
"(",
"sfile_list",
")",
":",
"event_list",
"=",
"[",
"]",
"sort_list",
"=",
"[",
"(",
"readheader",
"(",
"sfile",
")",
".",
"origins",
"[",
"0",
"]",
".",
"time",
",",
"sfile",
")",
"for",
"sfile",
"in",
"sfile_list",
"]",
"... | Write an event.dat file from a list of Seisan events
:type sfile_list: list
:param sfile_list: List of s-files to sort and put into the database
:returns: List of tuples of event ID (int) and Sfile name | [
"Write",
"an",
"event",
".",
"dat",
"file",
"from",
"a",
"list",
"of",
"Seisan",
"events"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.