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 |
|---|---|---|---|---|---|---|---|---|
pandas-dev/pandas | pandas/core/computation/scope.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/computation/scope.py#L22-L26 | def _ensure_scope(level, global_dict=None, local_dict=None, resolvers=(),
target=None, **kwargs):
"""Ensure that we are grabbing the correct scope."""
return Scope(level + 1, global_dict=global_dict, local_dict=local_dict,
resolvers=resolvers, target=target) | [
"def",
"_ensure_scope",
"(",
"level",
",",
"global_dict",
"=",
"None",
",",
"local_dict",
"=",
"None",
",",
"resolvers",
"=",
"(",
")",
",",
"target",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Scope",
"(",
"level",
"+",
"1",
",",
"... | Ensure that we are grabbing the correct scope. | [
"Ensure",
"that",
"we",
"are",
"grabbing",
"the",
"correct",
"scope",
"."
] | python | train |
ebu/PlugIt | plugit_proxy/utils.py | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/utils.py#L10-L18 | def create_secret(*args, **kwargs):
"""Return a secure key generated from the user and the object. As we load elements fron any class from user imput, this prevent the user to specify arbitrary class"""
to_sign = '-!'.join(args) + '$$'.join(kwargs.values())
key = settings.SECRET_FOR_SIGNS
hashed = hm... | [
"def",
"create_secret",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"to_sign",
"=",
"'-!'",
".",
"join",
"(",
"args",
")",
"+",
"'$$'",
".",
"join",
"(",
"kwargs",
".",
"values",
"(",
")",
")",
"key",
"=",
"settings",
".",
"SECRET_FOR_SIGN... | Return a secure key generated from the user and the object. As we load elements fron any class from user imput, this prevent the user to specify arbitrary class | [
"Return",
"a",
"secure",
"key",
"generated",
"from",
"the",
"user",
"and",
"the",
"object",
".",
"As",
"we",
"load",
"elements",
"fron",
"any",
"class",
"from",
"user",
"imput",
"this",
"prevent",
"the",
"user",
"to",
"specify",
"arbitrary",
"class"
] | python | train |
praekeltfoundation/seaworthy | seaworthy/stream/matchers.py | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/seaworthy/stream/matchers.py#L99-L106 | def args_str(self):
"""
Return an args string for the repr.
"""
matched = [str(m) for m in self._matchers[:self._position]]
unmatched = [str(m) for m in self._matchers[self._position:]]
return 'matched=[{}], unmatched=[{}]'.format(
', '.join(matched), ', '.joi... | [
"def",
"args_str",
"(",
"self",
")",
":",
"matched",
"=",
"[",
"str",
"(",
"m",
")",
"for",
"m",
"in",
"self",
".",
"_matchers",
"[",
":",
"self",
".",
"_position",
"]",
"]",
"unmatched",
"=",
"[",
"str",
"(",
"m",
")",
"for",
"m",
"in",
"self"... | Return an args string for the repr. | [
"Return",
"an",
"args",
"string",
"for",
"the",
"repr",
"."
] | python | train |
dw/mitogen | mitogen/core.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/core.py#L2953-L2962 | def _call(self, stream, func):
"""
Call `func(self)`, catching any exception that might occur, logging it,
and force-disconnecting the related `stream`.
"""
try:
func(self)
except Exception:
LOG.exception('%r crashed', stream)
stream.on... | [
"def",
"_call",
"(",
"self",
",",
"stream",
",",
"func",
")",
":",
"try",
":",
"func",
"(",
"self",
")",
"except",
"Exception",
":",
"LOG",
".",
"exception",
"(",
"'%r crashed'",
",",
"stream",
")",
"stream",
".",
"on_disconnect",
"(",
"self",
")"
] | Call `func(self)`, catching any exception that might occur, logging it,
and force-disconnecting the related `stream`. | [
"Call",
"func",
"(",
"self",
")",
"catching",
"any",
"exception",
"that",
"might",
"occur",
"logging",
"it",
"and",
"force",
"-",
"disconnecting",
"the",
"related",
"stream",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/msazure.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L415-L692 | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'azu... | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"'azure... | Create a single VM from a data dict | [
"Create",
"a",
"single",
"VM",
"from",
"a",
"data",
"dict"
] | python | train |
urschrei/pyzotero | pyzotero/zotero.py | https://github.com/urschrei/pyzotero/blob/b378966b30146a952f7953c23202fb5a1ddf81d9/pyzotero/zotero.py#L1448-L1482 | def delete_item(self, payload, last_modified=None):
"""
Delete Items from a Zotero library
Accepts a single argument:
a dict containing item data
OR a list of dicts containing item data
"""
params = None
if isinstance(payload, list):
pa... | [
"def",
"delete_item",
"(",
"self",
",",
"payload",
",",
"last_modified",
"=",
"None",
")",
":",
"params",
"=",
"None",
"if",
"isinstance",
"(",
"payload",
",",
"list",
")",
":",
"params",
"=",
"{",
"\"itemKey\"",
":",
"\",\"",
".",
"join",
"(",
"[",
... | Delete Items from a Zotero library
Accepts a single argument:
a dict containing item data
OR a list of dicts containing item data | [
"Delete",
"Items",
"from",
"a",
"Zotero",
"library",
"Accepts",
"a",
"single",
"argument",
":",
"a",
"dict",
"containing",
"item",
"data",
"OR",
"a",
"list",
"of",
"dicts",
"containing",
"item",
"data"
] | python | valid |
tBaxter/tango-articles | build/lib/articles/signals.py | https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/signals.py#L10-L52 | def auto_tweet(sender, instance, *args, **kwargs):
"""
Allows auto-tweeting newly created object to twitter
on accounts configured in settings.
You MUST create an app to allow oAuth authentication to work:
-- https://dev.twitter.com/apps/
You also must set the app to "Read and Write" access le... | [
"def",
"auto_tweet",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"twitter",
"or",
"getattr",
"(",
"settings",
",",
"'TWITTER_SETTINGS'",
")",
"is",
"False",
":",
"#print 'WARNING: Twitter account not config... | Allows auto-tweeting newly created object to twitter
on accounts configured in settings.
You MUST create an app to allow oAuth authentication to work:
-- https://dev.twitter.com/apps/
You also must set the app to "Read and Write" access level,
and create an access token. Whew. | [
"Allows",
"auto",
"-",
"tweeting",
"newly",
"created",
"object",
"to",
"twitter",
"on",
"accounts",
"configured",
"in",
"settings",
"."
] | python | train |
delfick/harpoon | harpoon/actions.py | https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/actions.py#L159-L169 | def make(collector, image, **kwargs):
"""Just create an image"""
tag = kwargs.get("artifact", NotSpecified)
if tag is NotSpecified:
tag = collector.configuration["harpoon"].tag
if tag is not NotSpecified:
image.tag = tag
Builder().make_image(image, collector.configuration["images"]... | [
"def",
"make",
"(",
"collector",
",",
"image",
",",
"*",
"*",
"kwargs",
")",
":",
"tag",
"=",
"kwargs",
".",
"get",
"(",
"\"artifact\"",
",",
"NotSpecified",
")",
"if",
"tag",
"is",
"NotSpecified",
":",
"tag",
"=",
"collector",
".",
"configuration",
"[... | Just create an image | [
"Just",
"create",
"an",
"image"
] | python | train |
SeabornGames/RequestClient | seaborn/request_client/connection_basic.py | https://github.com/SeabornGames/RequestClient/blob/21aeb951ddfdb6ee453ad0edc896ff224e06425d/seaborn/request_client/connection_basic.py#L37-L51 | def no_history_check(func):
"""
Decorator function to setup a check to see if history has been turned off,
because if it has then the decorated function needs to throw an exception
:param func: function to decorate
:return: original results or exception
"""
def no_history_check_decorator(se... | [
"def",
"no_history_check",
"(",
"func",
")",
":",
"def",
"no_history_check_decorator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ConnectionBasic",
".",
"max_history",
"is",
"0",
":",
"raise",
"IndexError",
"(",
"\"ConnectionBas... | Decorator function to setup a check to see if history has been turned off,
because if it has then the decorated function needs to throw an exception
:param func: function to decorate
:return: original results or exception | [
"Decorator",
"function",
"to",
"setup",
"a",
"check",
"to",
"see",
"if",
"history",
"has",
"been",
"turned",
"off",
"because",
"if",
"it",
"has",
"then",
"the",
"decorated",
"function",
"needs",
"to",
"throw",
"an",
"exception",
":",
"param",
"func",
":",
... | python | train |
gabstopper/smc-python | smc/elements/service.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/service.py#L138-L156 | def create(cls, name, protocol_number, protocol_agent=None, comment=None):
"""
Create the IP Service
:param str name: name of ip-service
:param int protocol_number: ip proto number for this service
:param str,ProtocolAgent protocol_agent: optional protocol agent for
... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"protocol_number",
",",
"protocol_agent",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"json",
"=",
"{",
"'name'",
":",
"name",
",",
"'protocol_number'",
":",
"protocol_number",
",",
"'protocol_agent_ref'... | Create the IP Service
:param str name: name of ip-service
:param int protocol_number: ip proto number for this service
:param str,ProtocolAgent protocol_agent: optional protocol agent for
this service
:param str comment: optional comment
:raises CreateElementFailed: ... | [
"Create",
"the",
"IP",
"Service"
] | python | train |
saltstack/salt | salt/modules/lxc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4141-L4152 | def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# D... | [
"def",
"_get_md5",
"(",
"name",
",",
"path",
")",
":",
"output",
"=",
"run_stdout",
"(",
"name",
",",
"'md5sum \"{0}\"'",
".",
"format",
"(",
"path",
")",
",",
"chroot_fallback",
"=",
"True",
",",
"ignore_retcode",
"=",
"True",
")",
"try",
":",
"return",... | Get the MD5 checksum of a file from a container | [
"Get",
"the",
"MD5",
"checksum",
"of",
"a",
"file",
"from",
"a",
"container"
] | python | train |
taskcluster/taskcluster-client.py | taskcluster/queue.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/queue.py#L693-L715 | def declareProvisioner(self, *args, **kwargs):
"""
Update a provisioner
Declare a provisioner, supplying some details about it.
`declareProvisioner` allows updating one or more properties of a provisioner as long as the required scopes are
possessed. For example, a request to u... | [
"def",
"declareProvisioner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"declareProvisioner\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Update a provisioner
Declare a provisioner, supplying some details about it.
`declareProvisioner` allows updating one or more properties of a provisioner as long as the required scopes are
possessed. For example, a request to update the `aws-provisioner-v1`
provisioner with a body `{de... | [
"Update",
"a",
"provisioner"
] | python | train |
raiden-network/raiden | raiden/network/proxies/token_network_registry.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/proxies/token_network_registry.py#L119-L131 | def add_token_without_limits(
self,
token_address: TokenAddress,
) -> Address:
"""
Register token of `token_address` with the token network.
This applies for versions prior to 0.13.0 of raiden-contracts,
since limits were hardcoded into the TokenNetwork contra... | [
"def",
"add_token_without_limits",
"(",
"self",
",",
"token_address",
":",
"TokenAddress",
",",
")",
"->",
"Address",
":",
"return",
"self",
".",
"_add_token",
"(",
"token_address",
"=",
"token_address",
",",
"additional_arguments",
"=",
"dict",
"(",
")",
",",
... | Register token of `token_address` with the token network.
This applies for versions prior to 0.13.0 of raiden-contracts,
since limits were hardcoded into the TokenNetwork contract. | [
"Register",
"token",
"of",
"token_address",
"with",
"the",
"token",
"network",
".",
"This",
"applies",
"for",
"versions",
"prior",
"to",
"0",
".",
"13",
".",
"0",
"of",
"raiden",
"-",
"contracts",
"since",
"limits",
"were",
"hardcoded",
"into",
"the",
"Tok... | python | train |
saltstack/salt | salt/modules/dockermod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockermod.py#L521-L556 | def _get_exec_driver():
'''
Get the method to be used in shell commands
'''
contextkey = 'docker.exec_driver'
if contextkey not in __context__:
from_config = __salt__['config.get'](contextkey, None)
# This if block can be removed once we make docker-exec a default
# option, a... | [
"def",
"_get_exec_driver",
"(",
")",
":",
"contextkey",
"=",
"'docker.exec_driver'",
"if",
"contextkey",
"not",
"in",
"__context__",
":",
"from_config",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"contextkey",
",",
"None",
")",
"# This if block can be removed o... | Get the method to be used in shell commands | [
"Get",
"the",
"method",
"to",
"be",
"used",
"in",
"shell",
"commands"
] | python | train |
gwastro/pycbc | pycbc/coordinates.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/coordinates.py#L84-L109 | def cartesian_to_spherical(x, y, z):
""" Maps cartesian coordinates (x,y,z) to spherical coordinates
(rho,phi,theta) where phi is in [0,2*pi] and theta is in [0,pi].
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
z : {nump... | [
"def",
"cartesian_to_spherical",
"(",
"x",
",",
"y",
",",
"z",
")",
":",
"rho",
"=",
"cartesian_to_spherical_rho",
"(",
"x",
",",
"y",
",",
"z",
")",
"phi",
"=",
"cartesian_to_spherical_azimuthal",
"(",
"x",
",",
"y",
")",
"theta",
"=",
"cartesian_to_spher... | Maps cartesian coordinates (x,y,z) to spherical coordinates
(rho,phi,theta) where phi is in [0,2*pi] and theta is in [0,pi].
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
z : {numpy.array, float}
Z-coordinate.
Re... | [
"Maps",
"cartesian",
"coordinates",
"(",
"x",
"y",
"z",
")",
"to",
"spherical",
"coordinates",
"(",
"rho",
"phi",
"theta",
")",
"where",
"phi",
"is",
"in",
"[",
"0",
"2",
"*",
"pi",
"]",
"and",
"theta",
"is",
"in",
"[",
"0",
"pi",
"]",
"."
] | python | train |
cloudmesh/cloudmesh-common | cloudmesh/common/ConfigDict.py | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/ConfigDict.py#L264-L285 | def load(self, filename):
"""
loads the configuration from the yaml filename
:param filename:
:type filename: string
:return:
"""
# print ("LOAD CONFIGDICT", filename)
self.data = BaseConfigDict(filename=Config.path_expand(filename))
try:
... | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"# print (\"LOAD CONFIGDICT\", filename)",
"self",
".",
"data",
"=",
"BaseConfigDict",
"(",
"filename",
"=",
"Config",
".",
"path_expand",
"(",
"filename",
")",
")",
"try",
":",
"version",
"=",
"str",
"(... | loads the configuration from the yaml filename
:param filename:
:type filename: string
:return: | [
"loads",
"the",
"configuration",
"from",
"the",
"yaml",
"filename",
":",
"param",
"filename",
":",
":",
"type",
"filename",
":",
"string",
":",
"return",
":"
] | python | train |
nerdvegas/rez | src/rez/vendor/version/version.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/version.py#L861-L874 | def inverse(self):
"""Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range).
"""
if self.is_any():
return None
else:
... | [
"def",
"inverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_any",
"(",
")",
":",
"return",
"None",
"else",
":",
"bounds",
"=",
"self",
".",
"_inverse",
"(",
"self",
".",
"bounds",
")",
"range",
"=",
"VersionRange",
"(",
"None",
")",
"range",
".... | Calculate the inverse of the range.
Returns:
New VersionRange object representing the inverse of this range, or
None if there is no inverse (ie, this range is the any range). | [
"Calculate",
"the",
"inverse",
"of",
"the",
"range",
"."
] | python | train |
odlgroup/odl | odl/tomo/geometry/parallel.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/geometry/parallel.py#L947-L1013 | def det_axes(self, angles):
"""Return the detector axes tuple at ``angles``.
Parameters
----------
angles : `array-like` or sequence
Euler angles in radians describing the rotation of the detector.
The length of the provided argument (along the first axis in
... | [
"def",
"det_axes",
"(",
"self",
",",
"angles",
")",
":",
"# Transpose to take dot along axis 1",
"axes",
"=",
"self",
".",
"rotation_matrix",
"(",
"angles",
")",
".",
"dot",
"(",
"self",
".",
"det_axes_init",
".",
"T",
")",
"# `axes` has shape (a, 3, 2), need to r... | Return the detector axes tuple at ``angles``.
Parameters
----------
angles : `array-like` or sequence
Euler angles in radians describing the rotation of the detector.
The length of the provided argument (along the first axis in
case of an array) must be equal... | [
"Return",
"the",
"detector",
"axes",
"tuple",
"at",
"angles",
"."
] | python | train |
peri-source/peri | peri/comp/objs.py | https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/comp/objs.py#L160-L163 | def _tile(self, n):
"""Get the update tile surrounding particle `n` """
pos = self._trans(self.pos[n])
return Tile(pos, pos).pad(self.support_pad) | [
"def",
"_tile",
"(",
"self",
",",
"n",
")",
":",
"pos",
"=",
"self",
".",
"_trans",
"(",
"self",
".",
"pos",
"[",
"n",
"]",
")",
"return",
"Tile",
"(",
"pos",
",",
"pos",
")",
".",
"pad",
"(",
"self",
".",
"support_pad",
")"
] | Get the update tile surrounding particle `n` | [
"Get",
"the",
"update",
"tile",
"surrounding",
"particle",
"n"
] | python | valid |
OpenTreeOfLife/peyotl | peyotl/nexson_syntax/__init__.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/nexson_syntax/__init__.py#L973-L1053 | def nexson_frag_write_newick(out,
edges,
nodes,
otu_group,
label_key,
leaf_labels,
root_id,
needs_quotes_pattern=NEWI... | [
"def",
"nexson_frag_write_newick",
"(",
"out",
",",
"edges",
",",
"nodes",
",",
"otu_group",
",",
"label_key",
",",
"leaf_labels",
",",
"root_id",
",",
"needs_quotes_pattern",
"=",
"NEWICK_NEEDING_QUOTING",
",",
"ingroup_id",
"=",
"None",
",",
"bracket_ingroup",
"... | `label_key` is a string (a key in the otu object) or a callable that takes two arguments:
the node, and the otu (which may be None for an internal node)
If `leaf_labels` is not None, it shoulr be a (list, dict) pair which will be filled. The list will
hold the order encountered,
and the dict... | [
"label_key",
"is",
"a",
"string",
"(",
"a",
"key",
"in",
"the",
"otu",
"object",
")",
"or",
"a",
"callable",
"that",
"takes",
"two",
"arguments",
":",
"the",
"node",
"and",
"the",
"otu",
"(",
"which",
"may",
"be",
"None",
"for",
"an",
"internal",
"no... | python | train |
alantygel/ckanext-semantictags | ckanext/semantictags/db.py | https://github.com/alantygel/ckanext-semantictags/blob/10bb31d29f34b2b5a6feae693961842f93007ce1/ckanext/semantictags/db.py#L252-L260 | def list_unique(cls):
'''Return all unique namespaces
:returns: a list of all predicates
:rtype: list of ckan.model.semantictag.Predicate objects
'''
query = meta.Session.query(Predicate).distinct(Predicate.namespace)
return query.all() | [
"def",
"list_unique",
"(",
"cls",
")",
":",
"query",
"=",
"meta",
".",
"Session",
".",
"query",
"(",
"Predicate",
")",
".",
"distinct",
"(",
"Predicate",
".",
"namespace",
")",
"return",
"query",
".",
"all",
"(",
")"
] | Return all unique namespaces
:returns: a list of all predicates
:rtype: list of ckan.model.semantictag.Predicate objects | [
"Return",
"all",
"unique",
"namespaces"
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/brownanrs/rs.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/brownanrs/rs.py#L248-L371 | def decode(self, r, nostrip=False, k=None, erasures_pos=None, only_erasures=False, return_string=True):
'''Given a received string or byte array or list r of values between
0 and gf2_charac, attempts to decode it. If it's a valid codeword, or
if there are no more than (n-k)/2 errors, the repaire... | [
"def",
"decode",
"(",
"self",
",",
"r",
",",
"nostrip",
"=",
"False",
",",
"k",
"=",
"None",
",",
"erasures_pos",
"=",
"None",
",",
"only_erasures",
"=",
"False",
",",
"return_string",
"=",
"True",
")",
":",
"n",
"=",
"self",
".",
"n",
"if",
"not",... | Given a received string or byte array or list r of values between
0 and gf2_charac, attempts to decode it. If it's a valid codeword, or
if there are no more than (n-k)/2 errors, the repaired message is returned.
A message always has k bytes, if a message contained less it is left
padded... | [
"Given",
"a",
"received",
"string",
"or",
"byte",
"array",
"or",
"list",
"r",
"of",
"values",
"between",
"0",
"and",
"gf2_charac",
"attempts",
"to",
"decode",
"it",
".",
"If",
"it",
"s",
"a",
"valid",
"codeword",
"or",
"if",
"there",
"are",
"no",
"more... | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_firmware_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_firmware_ext.py#L53-L65 | def show_firmware_version_output_show_firmware_version_os_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_firmware_vers... | [
"def",
"show_firmware_version_output_show_firmware_version_os_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_firmware_version",
"=",
"ET",
".",
"Element",
"(",
"\"show_firmware_version\"",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
senaite/senaite.core | bika/lims/browser/analyses/view.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analyses/view.py#L296-L320 | def is_result_edition_allowed(self, analysis_brain):
"""Checks if the edition of the result field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False
"""
# Always check general edition first
... | [
"def",
"is_result_edition_allowed",
"(",
"self",
",",
"analysis_brain",
")",
":",
"# Always check general edition first",
"if",
"not",
"self",
".",
"is_analysis_edition_allowed",
"(",
"analysis_brain",
")",
":",
"return",
"False",
"# Get the ananylsis object",
"obj",
"=",... | Checks if the edition of the result field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False | [
"Checks",
"if",
"the",
"edition",
"of",
"the",
"result",
"field",
"is",
"allowed"
] | python | train |
GoogleCloudPlatform/appengine-pipelines | python/src/pipeline/pipeline.py | https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/python/src/pipeline/pipeline.py#L1989-L2359 | def evaluate(self, pipeline_key, purpose=None, attempt=0):
"""Evaluates the given Pipeline and enqueues sub-stages for execution.
Args:
pipeline_key: The db.Key or stringified key of the _PipelineRecord to run.
purpose: Why evaluate was called ('start', 'finalize', or 'abort').
attempt: The a... | [
"def",
"evaluate",
"(",
"self",
",",
"pipeline_key",
",",
"purpose",
"=",
"None",
",",
"attempt",
"=",
"0",
")",
":",
"After",
".",
"_thread_init",
"(",
")",
"InOrder",
".",
"_thread_init",
"(",
")",
"InOrder",
".",
"_local",
".",
"_activated",
"=",
"F... | Evaluates the given Pipeline and enqueues sub-stages for execution.
Args:
pipeline_key: The db.Key or stringified key of the _PipelineRecord to run.
purpose: Why evaluate was called ('start', 'finalize', or 'abort').
attempt: The attempt number that should be tried. | [
"Evaluates",
"the",
"given",
"Pipeline",
"and",
"enqueues",
"sub",
"-",
"stages",
"for",
"execution",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/pkg_resources.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/pkg_resources.py#L1663-L1689 | def get_importer(path_item):
"""Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook.
"""
try:
importer = sys.path_importer_cache[... | [
"def",
"get_importer",
"(",
"path_item",
")",
":",
"try",
":",
"importer",
"=",
"sys",
".",
"path_importer_cache",
"[",
"path_item",
"]",
"except",
"KeyError",
":",
"for",
"hook",
"in",
"sys",
".",
"path_hooks",
":",
"try",
":",
"importer",
"=",
"hook",
... | Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook. | [
"Retrieve",
"a",
"PEP",
"302",
"importer",
"for",
"the",
"given",
"path",
"item"
] | python | test |
balloob/pychromecast | pychromecast/__init__.py | https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/__init__.py#L306-L313 | def volume_down(self, delta=0.1):
""" Decrement the volume by 0.1 (or delta) unless it is already 0.
Returns the new volume.
"""
if delta <= 0:
raise ValueError(
"volume delta must be greater than zero, not {}".format(delta))
return self.set_volume(sel... | [
"def",
"volume_down",
"(",
"self",
",",
"delta",
"=",
"0.1",
")",
":",
"if",
"delta",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"volume delta must be greater than zero, not {}\"",
".",
"format",
"(",
"delta",
")",
")",
"return",
"self",
".",
"set_volume",
... | Decrement the volume by 0.1 (or delta) unless it is already 0.
Returns the new volume. | [
"Decrement",
"the",
"volume",
"by",
"0",
".",
"1",
"(",
"or",
"delta",
")",
"unless",
"it",
"is",
"already",
"0",
".",
"Returns",
"the",
"new",
"volume",
"."
] | python | train |
geophysics-ubonn/crtomo_tools | lib/crtomo/grid.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/lib/crtomo/grid.py#L160-L229 | def _read_elem_nodes(self, fid):
""" Read the nodes from an opened elem.dat file. Correct for CutMcK
transformations.
We store three typed of nodes in the dict 'nodes':
* "raw" : as read from the elem.dat file
* "presort" : pre-sorted so we can directly read node number... | [
"def",
"_read_elem_nodes",
"(",
"self",
",",
"fid",
")",
":",
"nodes",
"=",
"{",
"}",
"# # prepare nodes",
"# nodes_sorted = np.zeros((number_of_nodes, 3), dtype=float)",
"# nodes = np.zeros((number_of_nodes, 3), dtype=float)",
"# read in nodes",
"nodes_raw",
"=",
"np",
"... | Read the nodes from an opened elem.dat file. Correct for CutMcK
transformations.
We store three typed of nodes in the dict 'nodes':
* "raw" : as read from the elem.dat file
* "presort" : pre-sorted so we can directly read node numbers from
a elec.dat file and use ... | [
"Read",
"the",
"nodes",
"from",
"an",
"opened",
"elem",
".",
"dat",
"file",
".",
"Correct",
"for",
"CutMcK",
"transformations",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17r_1_01a/isis_state/interface_detail/isis_intf/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/isis_state/interface_detail/isis_intf/__init__.py#L837-L860 | def _set_ldp_sync_info(self, v, load=False):
"""
Setter method for ldp_sync_info, mapped from YANG variable /isis_state/interface_detail/isis_intf/ldp_sync_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_sync_info is considered as a private
metho... | [
"def",
"_set_ldp_sync_info",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | Setter method for ldp_sync_info, mapped from YANG variable /isis_state/interface_detail/isis_intf/ldp_sync_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_sync_info is considered as a private
method. Backends looking to populate this variable should
... | [
"Setter",
"method",
"for",
"ldp_sync_info",
"mapped",
"from",
"YANG",
"variable",
"/",
"isis_state",
"/",
"interface_detail",
"/",
"isis_intf",
"/",
"ldp_sync_info",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":"... | python | train |
lambdalisue/django-permission | src/permission/logics/oneself.py | https://github.com/lambdalisue/django-permission/blob/580f7a1f857701d06ccf41163f188ac04fbc4fac/src/permission/logics/oneself.py#L58-L118 | def has_perm(self, user_obj, perm, obj=None):
"""
Check if user have permission of himself
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).... | [
"def",
"has_perm",
"(",
"self",
",",
"user_obj",
",",
"perm",
",",
"obj",
"=",
"None",
")",
":",
"if",
"not",
"is_authenticated",
"(",
"user_obj",
")",
":",
"return",
"False",
"# construct the permission full name",
"change_permission",
"=",
"self",
".",
"get_... | Check if user have permission of himself
If the user_obj is not authenticated, it return ``False``.
If no object is specified, it return ``True`` when the corresponding
permission was specified to ``True`` (changed from v0.7.0).
This behavior is based on the django system.
http... | [
"Check",
"if",
"user",
"have",
"permission",
"of",
"himself"
] | python | train |
kennethreitz/requests-html | requests_html.py | https://github.com/kennethreitz/requests-html/blob/b59a9f2fb9333d7d467154a0fd82978efdb9d23b/requests_html.py#L291-L304 | def links(self) -> _Links:
"""All found links on page, in as–is form."""
def gen():
for link in self.find('a'):
try:
href = link.attrs['href'].strip()
if href and not (href.startswith('#') and self.skip_anchors) and not href.startswit... | [
"def",
"links",
"(",
"self",
")",
"->",
"_Links",
":",
"def",
"gen",
"(",
")",
":",
"for",
"link",
"in",
"self",
".",
"find",
"(",
"'a'",
")",
":",
"try",
":",
"href",
"=",
"link",
".",
"attrs",
"[",
"'href'",
"]",
".",
"strip",
"(",
")",
"if... | All found links on page, in as–is form. | [
"All",
"found",
"links",
"on",
"page",
"in",
"as–is",
"form",
"."
] | python | train |
adubkov/py-cloudwatch | pycloudwatch/sender.py | https://github.com/adubkov/py-cloudwatch/blob/755bac7c153f75c4f0aa73ce14ca333cc4affb36/pycloudwatch/sender.py#L14-L23 | def put(self, metrics):
"""
Put metrics to cloudwatch. Metric shoult be instance or list of
instances of CloudWatchMetric
"""
if type(metrics) == list:
for metric in metrics:
self.c.put_metric_data(**metric)
else:
self.c.put_metric_... | [
"def",
"put",
"(",
"self",
",",
"metrics",
")",
":",
"if",
"type",
"(",
"metrics",
")",
"==",
"list",
":",
"for",
"metric",
"in",
"metrics",
":",
"self",
".",
"c",
".",
"put_metric_data",
"(",
"*",
"*",
"metric",
")",
"else",
":",
"self",
".",
"c... | Put metrics to cloudwatch. Metric shoult be instance or list of
instances of CloudWatchMetric | [
"Put",
"metrics",
"to",
"cloudwatch",
".",
"Metric",
"shoult",
"be",
"instance",
"or",
"list",
"of",
"instances",
"of",
"CloudWatchMetric"
] | python | valid |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L370-L400 | def parse(cls, root):
"""
Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child o... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"subsection",
"=",
"root",
".",
"tag",
".",
"replace",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
",",
"\"\"",
",",
"1",
")",
"if",
"subsection",
"not",
"in",
"cls",
".",
"ALLOWED_SUBSECTIONS... | Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child of root is not mdRef or mdWrap. | [
"Create",
"a",
"new",
"SubSection",
"by",
"parsing",
"root",
"."
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_spinner.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_spinner.py#L65-L75 | def init_widget(self):
""" Initialize the underlying widget.
"""
w = self.widget
# Selection listener
w.setAdapter(self.adapter)
w.setOnItemSelectedListener(w.getId())
w.onItemSelected.connect(self.on_item_selected)
w.onNothingSelected.connect(self.on_not... | [
"def",
"init_widget",
"(",
"self",
")",
":",
"w",
"=",
"self",
".",
"widget",
"# Selection listener",
"w",
".",
"setAdapter",
"(",
"self",
".",
"adapter",
")",
"w",
".",
"setOnItemSelectedListener",
"(",
"w",
".",
"getId",
"(",
")",
")",
"w",
".",
"onI... | Initialize the underlying widget. | [
"Initialize",
"the",
"underlying",
"widget",
"."
] | python | train |
ramses-tech/nefertari | nefertari/utils/utils.py | https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/utils.py#L95-L107 | def maybe_dotted(module, throw=True):
""" If ``module`` is a dotted string pointing to the module,
imports and returns the module object.
"""
try:
return Configurator().maybe_dotted(module)
except ImportError as e:
err = '%s not found. %s' % (module, e)
if throw:
... | [
"def",
"maybe_dotted",
"(",
"module",
",",
"throw",
"=",
"True",
")",
":",
"try",
":",
"return",
"Configurator",
"(",
")",
".",
"maybe_dotted",
"(",
"module",
")",
"except",
"ImportError",
"as",
"e",
":",
"err",
"=",
"'%s not found. %s'",
"%",
"(",
"modu... | If ``module`` is a dotted string pointing to the module,
imports and returns the module object. | [
"If",
"module",
"is",
"a",
"dotted",
"string",
"pointing",
"to",
"the",
"module",
"imports",
"and",
"returns",
"the",
"module",
"object",
"."
] | python | train |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/decorators.py | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/decorators.py#L10-L84 | def observable(
_method_or_viewset=None, poll_interval=None, primary_key=None, dependencies=None
):
"""Make ViewSet or ViewSet method observable.
Decorating a ViewSet class is the same as decorating its `list` method.
If decorated method returns a response containing a list of items, it must
use t... | [
"def",
"observable",
"(",
"_method_or_viewset",
"=",
"None",
",",
"poll_interval",
"=",
"None",
",",
"primary_key",
"=",
"None",
",",
"dependencies",
"=",
"None",
")",
":",
"if",
"poll_interval",
"and",
"dependencies",
":",
"raise",
"ValueError",
"(",
"'Only o... | Make ViewSet or ViewSet method observable.
Decorating a ViewSet class is the same as decorating its `list` method.
If decorated method returns a response containing a list of items, it must
use the provided `LimitOffsetPagination` for any pagination. In case a
non-list response is returned, the result... | [
"Make",
"ViewSet",
"or",
"ViewSet",
"method",
"observable",
"."
] | python | train |
uuazed/numerapi | numerapi/numerapi.py | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L728-L777 | def get_submission_filenames(self, tournament=None, round_num=None):
"""Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user... | [
"def",
"get_submission_filenames",
"(",
"self",
",",
"tournament",
"=",
"None",
",",
"round_num",
"=",
"None",
")",
":",
"query",
"=",
"'''\n query {\n user {\n submissions {\n filename\n selected\n round {... | Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames (`dict`)
Each filenames in the list as the following str... | [
"Get",
"filenames",
"of",
"the",
"submission",
"of",
"the",
"user",
"."
] | python | train |
MisterY/pydatum | pydatum/datum.py | https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L84-L89 | def from_iso_date_string(self, date_str: str) -> datetime:
""" Parse ISO date string (YYYY-MM-DD) """
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value | [
"def",
"from_iso_date_string",
"(",
"self",
",",
"date_str",
":",
"str",
")",
"->",
"datetime",
":",
"assert",
"isinstance",
"(",
"date_str",
",",
"str",
")",
"self",
".",
"value",
"=",
"datetime",
".",
"strptime",
"(",
"date_str",
",",
"ISO_DATE_FORMAT",
... | Parse ISO date string (YYYY-MM-DD) | [
"Parse",
"ISO",
"date",
"string",
"(",
"YYYY",
"-",
"MM",
"-",
"DD",
")"
] | python | train |
chaoss/grimoirelab-perceval | perceval/backends/core/nntp.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/nntp.py#L303-L315 | def _fetch_article(self, article_id):
"""Fetch article data
:param article_id: id of the article to fetch
"""
fetched_data = self.handler.article(article_id)
data = {
'number': fetched_data[1].number,
'message_id': fetched_data[1].message_id,
... | [
"def",
"_fetch_article",
"(",
"self",
",",
"article_id",
")",
":",
"fetched_data",
"=",
"self",
".",
"handler",
".",
"article",
"(",
"article_id",
")",
"data",
"=",
"{",
"'number'",
":",
"fetched_data",
"[",
"1",
"]",
".",
"number",
",",
"'message_id'",
... | Fetch article data
:param article_id: id of the article to fetch | [
"Fetch",
"article",
"data"
] | python | test |
readbeyond/aeneas | thirdparty/mfcc.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L162-L172 | def dctmat(N,K,freqstep,orthogonalize=True):
"""Return the orthogonal DCT-II/DCT-III matrix of size NxK.
For computing or inverting MFCCs, N is the number of
log-power-spectrum bins while K is the number of cepstra."""
cosmat = numpy.zeros((N, K), 'double')
for n in range(0,N):
for k in rang... | [
"def",
"dctmat",
"(",
"N",
",",
"K",
",",
"freqstep",
",",
"orthogonalize",
"=",
"True",
")",
":",
"cosmat",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"N",
",",
"K",
")",
",",
"'double'",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"N",
")",
"... | Return the orthogonal DCT-II/DCT-III matrix of size NxK.
For computing or inverting MFCCs, N is the number of
log-power-spectrum bins while K is the number of cepstra. | [
"Return",
"the",
"orthogonal",
"DCT",
"-",
"II",
"/",
"DCT",
"-",
"III",
"matrix",
"of",
"size",
"NxK",
".",
"For",
"computing",
"or",
"inverting",
"MFCCs",
"N",
"is",
"the",
"number",
"of",
"log",
"-",
"power",
"-",
"spectrum",
"bins",
"while",
"K",
... | python | train |
gbiggs/rtctree | rtctree/manager.py | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/manager.py#L215-L234 | def load_module(self, path, init_func):
'''Load a shared library.
Call this function to load a shared library (DLL file under Windows,
shared object under UNIX) into the manager.
@param path The path to the shared library.
@param init_func The name entry function in the library... | [
"def",
"load_module",
"(",
"self",
",",
"path",
",",
"init_func",
")",
":",
"try",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"_obj",
".",
"load_module",
"(",
"path",
",",
"init_func",
")",
"!=",
"RTC",
".",
"RTC_OK",
":",
"raise",
... | Load a shared library.
Call this function to load a shared library (DLL file under Windows,
shared object under UNIX) into the manager.
@param path The path to the shared library.
@param init_func The name entry function in the library.
@raises FailedToLoadModuleError | [
"Load",
"a",
"shared",
"library",
"."
] | python | train |
sosy-lab/benchexec | benchexec/container.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/container.py#L226-L244 | def get_mount_points():
"""Get all current mount points of the system.
Changes to the mount points during iteration may be reflected in the result.
@return a generator of (source, target, fstype, options),
where options is a list of bytes instances, and the others are bytes instances
(this avoids en... | [
"def",
"get_mount_points",
"(",
")",
":",
"def",
"decode_path",
"(",
"path",
")",
":",
"# Replace tab, space, newline, and backslash escapes with actual characters.",
"# According to man 5 fstab, only tab and space escaped, but Linux escapes more:",
"# https://git.kernel.org/pub/scm/linux/... | Get all current mount points of the system.
Changes to the mount points during iteration may be reflected in the result.
@return a generator of (source, target, fstype, options),
where options is a list of bytes instances, and the others are bytes instances
(this avoids encoding problems with mount poin... | [
"Get",
"all",
"current",
"mount",
"points",
"of",
"the",
"system",
".",
"Changes",
"to",
"the",
"mount",
"points",
"during",
"iteration",
"may",
"be",
"reflected",
"in",
"the",
"result",
"."
] | python | train |
chaosmail/python-fs | fs/fs.py | https://github.com/chaosmail/python-fs/blob/2567922ced9387e327e65f3244caff3b7af35684/fs/fs.py#L315-L320 | def addpath(path):
"""Add *path* to system path"""
import sys
if not exists(path):
raise ValueError('Path %s does not exist' % path)
sys.path.insert(1, path) | [
"def",
"addpath",
"(",
"path",
")",
":",
"import",
"sys",
"if",
"not",
"exists",
"(",
"path",
")",
":",
"raise",
"ValueError",
"(",
"'Path %s does not exist'",
"%",
"path",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"1",
",",
"path",
")"
] | Add *path* to system path | [
"Add",
"*",
"path",
"*",
"to",
"system",
"path"
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/ext/_bundled/decorator.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/decorator.py#L140-L167 | def make(self, src_templ, evaldict=None, addsource=False, **attrs):
"Make a new function from a given template and update the signature"
src = src_templ % vars(self) # expand name and signature
evaldict = evaldict or {}
mo = DEF.match(src)
if mo is None:
raise SyntaxE... | [
"def",
"make",
"(",
"self",
",",
"src_templ",
",",
"evaldict",
"=",
"None",
",",
"addsource",
"=",
"False",
",",
"*",
"*",
"attrs",
")",
":",
"src",
"=",
"src_templ",
"%",
"vars",
"(",
"self",
")",
"# expand name and signature",
"evaldict",
"=",
"evaldic... | Make a new function from a given template and update the signature | [
"Make",
"a",
"new",
"function",
"from",
"a",
"given",
"template",
"and",
"update",
"the",
"signature"
] | python | train |
JoeVirtual/KonFoo | konfoo/core.py | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L273-L303 | def to_dict(self, *attributes, **options):
""" Returns a **flatten** :class:`ordered dictionary <collections.OrderedDict>`
of ``{'field path': attribute}`` or ``{'field path': tuple(attributes)}``
pairs for each :class:`Field` *nested* in the `Container`.
:param str attributes: selected... | [
"def",
"to_dict",
"(",
"self",
",",
"*",
"attributes",
",",
"*",
"*",
"options",
")",
":",
"# Name of the Container",
"name",
"=",
"options",
".",
"pop",
"(",
"'name'",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"# Save to file",
"save",
"=",
"... | Returns a **flatten** :class:`ordered dictionary <collections.OrderedDict>`
of ``{'field path': attribute}`` or ``{'field path': tuple(attributes)}``
pairs for each :class:`Field` *nested* in the `Container`.
:param str attributes: selected :class:`Field` attributes.
Fallback is the... | [
"Returns",
"a",
"**",
"flatten",
"**",
":",
"class",
":",
"ordered",
"dictionary",
"<collections",
".",
"OrderedDict",
">",
"of",
"{",
"field",
"path",
":",
"attribute",
"}",
"or",
"{",
"field",
"path",
":",
"tuple",
"(",
"attributes",
")",
"}",
"pairs",... | python | train |
ciena/afkak | afkak/brokerclient.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/brokerclient.py#L322-L332 | def cancelRequest(self, requestId, reason=None, _=None):
"""Cancel a request: remove it from requests, & errback the deferred.
NOTE: Attempts to cancel a request which is no longer tracked
(expectResponse == False and already sent, or response already
received) will raise KeyError
... | [
"def",
"cancelRequest",
"(",
"self",
",",
"requestId",
",",
"reason",
"=",
"None",
",",
"_",
"=",
"None",
")",
":",
"if",
"reason",
"is",
"None",
":",
"reason",
"=",
"CancelledError",
"(",
")",
"tReq",
"=",
"self",
".",
"requests",
".",
"pop",
"(",
... | Cancel a request: remove it from requests, & errback the deferred.
NOTE: Attempts to cancel a request which is no longer tracked
(expectResponse == False and already sent, or response already
received) will raise KeyError | [
"Cancel",
"a",
"request",
":",
"remove",
"it",
"from",
"requests",
"&",
"errback",
"the",
"deferred",
"."
] | python | train |
saltstack/salt | salt/beacons/glxinfo.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/glxinfo.py#L49-L82 | def beacon(config):
'''
Emit the status of a connected display to the minion
Mainly this is used to detect when the display fails to connect
for whatever reason.
.. code-block:: yaml
beacons:
glxinfo:
- user: frank
- screen_event: True
'''
log.t... | [
"def",
"beacon",
"(",
"config",
")",
":",
"log",
".",
"trace",
"(",
"'glxinfo beacon starting'",
")",
"ret",
"=",
"[",
"]",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"retcode",
"=",
"__salt_... | Emit the status of a connected display to the minion
Mainly this is used to detect when the display fails to connect
for whatever reason.
.. code-block:: yaml
beacons:
glxinfo:
- user: frank
- screen_event: True | [
"Emit",
"the",
"status",
"of",
"a",
"connected",
"display",
"to",
"the",
"minion"
] | python | train |
okfn/ofs | ofs/local/storedjson.py | https://github.com/okfn/ofs/blob/c110cbecd7d0ae7e877963914a1a5af030cd6d45/ofs/local/storedjson.py#L33-L49 | def revert(self):
"""Revert the state to the version stored on disc."""
if self.filepath:
if path.isfile(self.filepath):
serialised_file = open(self.filepath, "r")
try:
self.state = json.load(serialised_file)
except ValueErr... | [
"def",
"revert",
"(",
"self",
")",
":",
"if",
"self",
".",
"filepath",
":",
"if",
"path",
".",
"isfile",
"(",
"self",
".",
"filepath",
")",
":",
"serialised_file",
"=",
"open",
"(",
"self",
".",
"filepath",
",",
"\"r\"",
")",
"try",
":",
"self",
".... | Revert the state to the version stored on disc. | [
"Revert",
"the",
"state",
"to",
"the",
"version",
"stored",
"on",
"disc",
"."
] | python | train |
fr33jc/bang | bang/providers/hpcloud/v12/__init__.py | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/v12/__init__.py#L50-L71 | def create_server(self, *args, **kwargs):
"""
Wraps :meth:`bang.providers.openstack.Nova.create_server` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values.
"""
# hpcloud's management console stuffs all of its tags i... | [
"def",
"create_server",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# hpcloud's management console stuffs all of its tags in a \"tags\" tag.",
"# populate it with the stack and role values here only at server",
"# creation time. what users do with it after serve... | Wraps :meth:`bang.providers.openstack.Nova.create_server` to apply
hpcloud specialization, namely pulling IP addresses from the hpcloud's
non-standard return values. | [
"Wraps",
":",
"meth",
":",
"bang",
".",
"providers",
".",
"openstack",
".",
"Nova",
".",
"create_server",
"to",
"apply",
"hpcloud",
"specialization",
"namely",
"pulling",
"IP",
"addresses",
"from",
"the",
"hpcloud",
"s",
"non",
"-",
"standard",
"return",
"va... | python | train |
bluedynamics/cone.ugm | src/cone/ugm/model/localmanager.py | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/model/localmanager.py#L118-L125 | def local_manager_rule(self):
"""Return rule for local manager.
"""
adm_gid = self.local_manager_gid
if not adm_gid:
return None
config = self.root['settings']['ugm_localmanager'].attrs
return config[adm_gid] | [
"def",
"local_manager_rule",
"(",
"self",
")",
":",
"adm_gid",
"=",
"self",
".",
"local_manager_gid",
"if",
"not",
"adm_gid",
":",
"return",
"None",
"config",
"=",
"self",
".",
"root",
"[",
"'settings'",
"]",
"[",
"'ugm_localmanager'",
"]",
".",
"attrs",
"... | Return rule for local manager. | [
"Return",
"rule",
"for",
"local",
"manager",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/transformer_memory.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/transformer_memory.py#L31-L45 | def pre_attention(self, segment, query_antecedent, memory_antecedent, bias):
"""Called prior to self-attention, to incorporate memory items.
Args:
segment: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. A... | [
"def",
"pre_attention",
"(",
"self",
",",
"segment",
",",
"query_antecedent",
",",
"memory_antecedent",
",",
"bias",
")",
":",
"del",
"segment",
"return",
"None",
",",
"query_antecedent",
",",
"memory_antecedent",
",",
"bias"
] | Called prior to self-attention, to incorporate memory items.
Args:
segment: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. Attention normally allows this to be a
Tensor with shape [batch, length_m, ch... | [
"Called",
"prior",
"to",
"self",
"-",
"attention",
"to",
"incorporate",
"memory",
"items",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L952-L976 | def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySeq... | [
"def",
"_context_menu_make",
"(",
"self",
",",
"pos",
")",
":",
"menu",
"=",
"QtGui",
".",
"QMenu",
"(",
"self",
")",
"self",
".",
"cut_action",
"=",
"menu",
".",
"addAction",
"(",
"'Cut'",
",",
"self",
".",
"cut",
")",
"self",
".",
"cut_action",
"."... | Creates a context menu for the given QPoint (in widget coordinates). | [
"Creates",
"a",
"context",
"menu",
"for",
"the",
"given",
"QPoint",
"(",
"in",
"widget",
"coordinates",
")",
"."
] | python | test |
TomasTomecek/sen | sen/docker_backend.py | https://github.com/TomasTomecek/sen/blob/239b4868125814e8bf5527708119fc08b35f6cc0/sen/docker_backend.py#L612-L624 | def net(self):
"""
get ACTIVE port mappings of a container
:return: dict:
{
"host_port": "container_port"
}
"""
try:
return NetData(self.inspect(cached=True).response)
except docker.errors.NotFound:
raise NotAvailableAn... | [
"def",
"net",
"(",
"self",
")",
":",
"try",
":",
"return",
"NetData",
"(",
"self",
".",
"inspect",
"(",
"cached",
"=",
"True",
")",
".",
"response",
")",
"except",
"docker",
".",
"errors",
".",
"NotFound",
":",
"raise",
"NotAvailableAnymore",
"(",
")"
... | get ACTIVE port mappings of a container
:return: dict:
{
"host_port": "container_port"
} | [
"get",
"ACTIVE",
"port",
"mappings",
"of",
"a",
"container"
] | python | train |
asweigart/pytweening | pytweening/__init__.py | https://github.com/asweigart/pytweening/blob/20d74368e53dc7d0f77c810b624b2c90994f099d/pytweening/__init__.py#L156-L170 | def easeInOutQuad(n):
"""A quadratic tween function that accelerates, reaches the midpoint, and then decelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine... | [
"def",
"easeInOutQuad",
"(",
"n",
")",
":",
"_checkRange",
"(",
"n",
")",
"if",
"n",
"<",
"0.5",
":",
"return",
"2",
"*",
"n",
"**",
"2",
"else",
":",
"n",
"=",
"n",
"*",
"2",
"-",
"1",
"return",
"-",
"0.5",
"*",
"(",
"n",
"*",
"(",
"n",
... | A quadratic tween function that accelerates, reaches the midpoint, and then decelerates.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). | [
"A",
"quadratic",
"tween",
"function",
"that",
"accelerates",
"reaches",
"the",
"midpoint",
"and",
"then",
"decelerates",
"."
] | python | train |
r-barnes/richdem | wrappers/pyrichdem/richdem/__init__.py | https://github.com/r-barnes/richdem/blob/abc04d81216d7cf5b57ad7a1e04b5699369b6f58/wrappers/pyrichdem/richdem/__init__.py#L289-L319 | def SaveGDAL(filename, rda):
"""Save a GDAL file.
Saves a RichDEM array to a data file in GeoTIFF format.
If you need to do something more complicated, look at the source of this
function.
Args:
filename (str): Name of the raster file to be created
rda (rdarray): Data... | [
"def",
"SaveGDAL",
"(",
"filename",
",",
"rda",
")",
":",
"if",
"type",
"(",
"rda",
")",
"is",
"not",
"rdarray",
":",
"raise",
"Exception",
"(",
"\"A richdem.rdarray or numpy.ndarray is required!\"",
")",
"if",
"not",
"GDAL_AVAILABLE",
":",
"raise",
"Exception",... | Save a GDAL file.
Saves a RichDEM array to a data file in GeoTIFF format.
If you need to do something more complicated, look at the source of this
function.
Args:
filename (str): Name of the raster file to be created
rda (rdarray): Data to save.
Returns:
... | [
"Save",
"a",
"GDAL",
"file",
"."
] | python | train |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2211-L2248 | def _prevent_default_initializer_splitting(self, item, indent_amt):
"""Prevent splitting between a default initializer.
When there is a default initializer, it's best to keep it all on
the same line. It's nicer and more readable, even if it goes
over the maximum allowable line length. T... | [
"def",
"_prevent_default_initializer_splitting",
"(",
"self",
",",
"item",
",",
"indent_amt",
")",
":",
"if",
"unicode",
"(",
"item",
")",
"==",
"'='",
":",
"# This is the assignment in the initializer. Just remove spaces for",
"# now.",
"self",
".",
"_delete_whitespace",... | Prevent splitting between a default initializer.
When there is a default initializer, it's best to keep it all on
the same line. It's nicer and more readable, even if it goes
over the maximum allowable line length. This goes back along the
current line to determine if we have a default ... | [
"Prevent",
"splitting",
"between",
"a",
"default",
"initializer",
"."
] | python | train |
edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/grada_cz.py | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/grada_cz.py#L54-L80 | def _parse_title_url(html_chunk):
"""
Parse title/name of the book and URL of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (title, url), both as strings.
"""
title = html_chunk.find("div", {"class": "comment"})
if... | [
"def",
"_parse_title_url",
"(",
"html_chunk",
")",
":",
"title",
"=",
"html_chunk",
".",
"find",
"(",
"\"div\"",
",",
"{",
"\"class\"",
":",
"\"comment\"",
"}",
")",
"if",
"not",
"title",
":",
"return",
"_parse_alt_title",
"(",
"html_chunk",
")",
",",
"Non... | Parse title/name of the book and URL of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (title, url), both as strings. | [
"Parse",
"title",
"/",
"name",
"of",
"the",
"book",
"and",
"URL",
"of",
"the",
"book",
"."
] | python | train |
GNS3/gns3-server | gns3server/controller/project.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/project.py#L922-L929 | def suspend_all(self):
"""
Suspend all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.suspend)
yield from pool.join() | [
"def",
"suspend_all",
"(",
"self",
")",
":",
"pool",
"=",
"Pool",
"(",
"concurrency",
"=",
"3",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
".",
"values",
"(",
")",
":",
"pool",
".",
"append",
"(",
"node",
".",
"suspend",
")",
"yield",
"from",
... | Suspend all nodes | [
"Suspend",
"all",
"nodes"
] | python | train |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L2336-L2385 | def _resolve_to_field_class(self, names, scope):
"""Resolve the names to a class in fields.py, resolving past
typedefs, etc
:names: TODO
:scope: TODO
:ctxt: TODO
:returns: TODO
"""
switch = {
"char" : "Char",
"int" : "Int",... | [
"def",
"_resolve_to_field_class",
"(",
"self",
",",
"names",
",",
"scope",
")",
":",
"switch",
"=",
"{",
"\"char\"",
":",
"\"Char\"",
",",
"\"int\"",
":",
"\"Int\"",
",",
"\"long\"",
":",
"\"Int\"",
",",
"\"int64\"",
":",
"\"Int64\"",
",",
"\"uint64\"",
":... | Resolve the names to a class in fields.py, resolving past
typedefs, etc
:names: TODO
:scope: TODO
:ctxt: TODO
:returns: TODO | [
"Resolve",
"the",
"names",
"to",
"a",
"class",
"in",
"fields",
".",
"py",
"resolving",
"past",
"typedefs",
"etc"
] | python | train |
xapple/plumbing | plumbing/common.py | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L286-L296 | def natural_sort(item):
"""
Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
dre... | [
"def",
"natural_sort",
"(",
"item",
")",
":",
"dre",
"=",
"re",
".",
"compile",
"(",
"r'(\\d+)'",
")",
"return",
"[",
"int",
"(",
"s",
")",
"if",
"s",
".",
"isdigit",
"(",
")",
"else",
"s",
".",
"lower",
"(",
")",
"for",
"s",
"in",
"re",
".",
... | Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" | [
"Sort",
"strings",
"that",
"contain",
"numbers",
"correctly",
".",
"Works",
"in",
"Python",
"2",
"and",
"3",
"."
] | python | train |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/commands/zip.py | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/commands/zip.py#L58-L86 | def paths(self):
"""All the entries of sys.path, possibly restricted by --path"""
if not self.select_paths:
return sys.path
result = []
match_any = set()
for path in sys.path:
path = os.path.normcase(os.path.abspath(path))
for match in self.sel... | [
"def",
"paths",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"select_paths",
":",
"return",
"sys",
".",
"path",
"result",
"=",
"[",
"]",
"match_any",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"sys",
".",
"path",
":",
"path",
"=",
"os",
".",
... | All the entries of sys.path, possibly restricted by --path | [
"All",
"the",
"entries",
"of",
"sys",
".",
"path",
"possibly",
"restricted",
"by",
"--",
"path"
] | python | train |
janpipek/physt | physt/special.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/special.py#L331-L345 | def _prepare_data(data, transformed, klass, *args, **kwargs):
"""Transform data for binning.
Returns
-------
np.ndarray
"""
# TODO: Maybe include in the class itself?
data = np.asarray(data)
if not transformed:
data = klass.transform(data)
dropna = kwargs.get("dropna", Fals... | [
"def",
"_prepare_data",
"(",
"data",
",",
"transformed",
",",
"klass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Maybe include in the class itself?",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"if",
"not",
"transformed",
":",
... | Transform data for binning.
Returns
-------
np.ndarray | [
"Transform",
"data",
"for",
"binning",
"."
] | python | train |
sdispater/pendulum | pendulum/time.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/time.py#L193-L221 | def diff(self, dt=None, abs=True):
"""
Returns the difference between two Time objects as an Duration.
:type dt: Time or None
:param abs: Whether to return an absolute interval or not
:type abs: bool
:rtype: Duration
"""
if dt is None:
dt = ... | [
"def",
"diff",
"(",
"self",
",",
"dt",
"=",
"None",
",",
"abs",
"=",
"True",
")",
":",
"if",
"dt",
"is",
"None",
":",
"dt",
"=",
"pendulum",
".",
"now",
"(",
")",
".",
"time",
"(",
")",
"else",
":",
"dt",
"=",
"self",
".",
"__class__",
"(",
... | Returns the difference between two Time objects as an Duration.
:type dt: Time or None
:param abs: Whether to return an absolute interval or not
:type abs: bool
:rtype: Duration | [
"Returns",
"the",
"difference",
"between",
"two",
"Time",
"objects",
"as",
"an",
"Duration",
"."
] | python | train |
cyface/django-termsandconditions | termsandconditions/signals.py | https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/signals.py#L23-L31 | def terms_updated(sender, **kwargs):
"""Called when terms and conditions is changed - to force cache clearing"""
LOGGER.debug("T&C Updated Signal Handler")
cache.delete('tandc.active_terms_ids')
cache.delete('tandc.active_terms_list')
if kwargs.get('instance').slug:
cache.delete('tandc.activ... | [
"def",
"terms_updated",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"T&C Updated Signal Handler\"",
")",
"cache",
".",
"delete",
"(",
"'tandc.active_terms_ids'",
")",
"cache",
".",
"delete",
"(",
"'tandc.active_terms_list'",
... | Called when terms and conditions is changed - to force cache clearing | [
"Called",
"when",
"terms",
"and",
"conditions",
"is",
"changed",
"-",
"to",
"force",
"cache",
"clearing"
] | python | train |
Jammy2211/PyAutoLens | autolens/model/galaxy/galaxy.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L293-L305 | def einstein_mass_in_units(self, unit_mass='angular', critical_surface_density=None):
"""The Einstein Mass of this galaxy, which is the sum of Einstein Radii of its mass profiles.
If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Mass \
may be i... | [
"def",
"einstein_mass_in_units",
"(",
"self",
",",
"unit_mass",
"=",
"'angular'",
",",
"critical_surface_density",
"=",
"None",
")",
":",
"if",
"self",
".",
"has_mass_profile",
":",
"return",
"sum",
"(",
"map",
"(",
"lambda",
"p",
":",
"p",
".",
"einstein_ma... | The Einstein Mass of this galaxy, which is the sum of Einstein Radii of its mass profiles.
If the galaxy is composed of multiple ellipitcal profiles with different axis-ratios, this Einstein Mass \
may be inaccurate. This is because the differently oriented ellipses of each mass profile | [
"The",
"Einstein",
"Mass",
"of",
"this",
"galaxy",
"which",
"is",
"the",
"sum",
"of",
"Einstein",
"Radii",
"of",
"its",
"mass",
"profiles",
"."
] | python | valid |
underworldcode/stripy | stripy-src/stripy/spherical.py | https://github.com/underworldcode/stripy/blob/d4c3480c3e58c88489ded695eadbe7cd5bf94b48/stripy-src/stripy/spherical.py#L128-L138 | def _generate_permutation(self, npoints):
"""
Create shuffle and deshuffle vectors
"""
i = np.arange(0, npoints)
# permutation
p = np.random.permutation(npoints)
ip = np.empty_like(p)
# inverse permutation
ip[p[i]] = i
return p, ip | [
"def",
"_generate_permutation",
"(",
"self",
",",
"npoints",
")",
":",
"i",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"npoints",
")",
"# permutation",
"p",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"npoints",
")",
"ip",
"=",
"np",
".",
"empty... | Create shuffle and deshuffle vectors | [
"Create",
"shuffle",
"and",
"deshuffle",
"vectors"
] | python | train |
aws/aws-dynamodb-encryption-python | src/dynamodb_encryption_sdk/internal/utils.py | https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/utils.py#L251-L268 | def encrypt_put_item(encrypt_method, crypto_config_method, write_method, **kwargs):
# type: (Callable, Callable, Callable, **Any) -> Dict
# TODO: narrow this down
"""Transparently encrypt an item before putting it to the table.
:param callable encrypt_method: Method to use to encrypt items
:param c... | [
"def",
"encrypt_put_item",
"(",
"encrypt_method",
",",
"crypto_config_method",
",",
"write_method",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Callable, Callable, Callable, **Any) -> Dict",
"# TODO: narrow this down",
"crypto_config",
",",
"ddb_kwargs",
"=",
"crypto_config_... | Transparently encrypt an item before putting it to the table.
:param callable encrypt_method: Method to use to encrypt items
:param callable crypto_config_method: Method that accepts ``kwargs`` and provides a :class:`CryptoConfig`
:param callable write_method: Method that writes to the table
:param **k... | [
"Transparently",
"encrypt",
"an",
"item",
"before",
"putting",
"it",
"to",
"the",
"table",
"."
] | python | train |
MacHu-GWU/uszipcode-project | uszipcode/pkg/sqlalchemy_mate/io.py | https://github.com/MacHu-GWU/uszipcode-project/blob/96282b779a3efb422802de83c48ca284598ba952/uszipcode/pkg/sqlalchemy_mate/io.py#L50-L65 | def table_to_csv(table, engine, filepath, chunksize=1000, overwrite=False):
"""
Export entire table to a csv file.
:param table: :class:`sqlalchemy.Table` instance.
:param engine: :class:`sqlalchemy.engine.base.Engine`.
:param filepath: file path.
:param chunksize: number of rows write to csv e... | [
"def",
"table_to_csv",
"(",
"table",
",",
"engine",
",",
"filepath",
",",
"chunksize",
"=",
"1000",
",",
"overwrite",
"=",
"False",
")",
":",
"sql",
"=",
"select",
"(",
"[",
"table",
"]",
")",
"sql_to_csv",
"(",
"sql",
",",
"engine",
",",
"filepath",
... | Export entire table to a csv file.
:param table: :class:`sqlalchemy.Table` instance.
:param engine: :class:`sqlalchemy.engine.base.Engine`.
:param filepath: file path.
:param chunksize: number of rows write to csv each time.
:param overwrite: bool, if True, avoid to overite existing file.
**中文... | [
"Export",
"entire",
"table",
"to",
"a",
"csv",
"file",
"."
] | python | train |
vpelletier/python-libusb1 | usb1/__init__.py | https://github.com/vpelletier/python-libusb1/blob/740c9778e28523e4ec3543415d95f5400ae0fa24/usb1/__init__.py#L2308-L2337 | def getDeviceIterator(self, skip_on_error=False):
"""
Return an iterator over all USB devices currently plugged in, as USBDevice
instances.
skip_on_error (bool)
If True, ignore devices which raise USBError.
"""
device_p_p = libusb1.libusb_device_p_p()
... | [
"def",
"getDeviceIterator",
"(",
"self",
",",
"skip_on_error",
"=",
"False",
")",
":",
"device_p_p",
"=",
"libusb1",
".",
"libusb_device_p_p",
"(",
")",
"libusb_device_p",
"=",
"libusb1",
".",
"libusb_device_p",
"device_list_len",
"=",
"libusb1",
".",
"libusb_get_... | Return an iterator over all USB devices currently plugged in, as USBDevice
instances.
skip_on_error (bool)
If True, ignore devices which raise USBError. | [
"Return",
"an",
"iterator",
"over",
"all",
"USB",
"devices",
"currently",
"plugged",
"in",
"as",
"USBDevice",
"instances",
"."
] | python | train |
facelessuser/backrefs | setup.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/setup.py#L60-L82 | def generate_unicode_table():
"""Generate the Unicode table for the given Python version."""
uver = get_unicodedata()
fail = False
path = os.path.join(os.path.dirname(__file__), 'tools')
fp, pathname, desc = imp.find_module('unipropgen', [path])
try:
unipropgen = imp.load_module('unipro... | [
"def",
"generate_unicode_table",
"(",
")",
":",
"uver",
"=",
"get_unicodedata",
"(",
")",
"fail",
"=",
"False",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'tools'",
")",
"fp",
",",... | Generate the Unicode table for the given Python version. | [
"Generate",
"the",
"Unicode",
"table",
"for",
"the",
"given",
"Python",
"version",
"."
] | python | train |
sparknetworks/pgpm | pgpm/utils/config.py | https://github.com/sparknetworks/pgpm/blob/1a060df46a886095181f692ea870a73a32510a2e/pgpm/utils/config.py#L63-L87 | def get_list_connections(self, environment, product, unique_name_list=None, is_except=False):
"""
Gets list of connections that satisfy the filter by environment, product and (optionally) unique DB names
:param environment: Environment name
:param product: Product name
:param uni... | [
"def",
"get_list_connections",
"(",
"self",
",",
"environment",
",",
"product",
",",
"unique_name_list",
"=",
"None",
",",
"is_except",
"=",
"False",
")",
":",
"return_list",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"connection_sets",
":",
"if",
"u... | Gets list of connections that satisfy the filter by environment, product and (optionally) unique DB names
:param environment: Environment name
:param product: Product name
:param unique_name_list: list of unique db aliases
:param is_except: take the connections with aliases provided or, ... | [
"Gets",
"list",
"of",
"connections",
"that",
"satisfy",
"the",
"filter",
"by",
"environment",
"product",
"and",
"(",
"optionally",
")",
"unique",
"DB",
"names",
":",
"param",
"environment",
":",
"Environment",
"name",
":",
"param",
"product",
":",
"Product",
... | python | train |
log2timeline/dftimewolf | dftimewolf/lib/state.py | https://github.com/log2timeline/dftimewolf/blob/45f898476a288d73c4256ae8e3836a2a4848c0d7/dftimewolf/lib/state.py#L121-L157 | def run_modules(self):
"""Performs the actual processing for each module in the module pool."""
def _run_module_thread(module_description):
"""Runs the module's process() function.
Waits for any blockers to have finished before running process(), then
sets an Event flag declaring the module ... | [
"def",
"run_modules",
"(",
"self",
")",
":",
"def",
"_run_module_thread",
"(",
"module_description",
")",
":",
"\"\"\"Runs the module's process() function.\n\n Waits for any blockers to have finished before running process(), then\n sets an Event flag declaring the module has compl... | Performs the actual processing for each module in the module pool. | [
"Performs",
"the",
"actual",
"processing",
"for",
"each",
"module",
"in",
"the",
"module",
"pool",
"."
] | python | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/views.py | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/views.py#L120-L129 | def component_suites(request, resource=None, component=None, extra_element="", **kwargs):
'Return part of a client-side component, served locally for some reason'
get_params = request.GET.urlencode()
if get_params and False:
redone_url = "/static/dash/component/%s/%s%s?%s" %(component, extra_elemen... | [
"def",
"component_suites",
"(",
"request",
",",
"resource",
"=",
"None",
",",
"component",
"=",
"None",
",",
"extra_element",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"get_params",
"=",
"request",
".",
"GET",
".",
"urlencode",
"(",
")",
"if",
"g... | Return part of a client-side component, served locally for some reason | [
"Return",
"part",
"of",
"a",
"client",
"-",
"side",
"component",
"served",
"locally",
"for",
"some",
"reason"
] | python | train |
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/logging.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/logging.py#L185-L209 | def gridLog(**kw):
"""Send GLRecord, Distributed Logging Utilities
If the scheme is passed as a keyword parameter
the value is expected to be a callable function
that takes 2 parameters: url, outputStr
GRIDLOG_ON -- turn grid logging on
GRIDLOG_DEST -- provide URL destination
"""
impo... | [
"def",
"gridLog",
"(",
"*",
"*",
"kw",
")",
":",
"import",
"os",
"if",
"not",
"bool",
"(",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'GRIDLOG_ON'",
",",
"0",
")",
")",
")",
":",
"return",
"url",
"=",
"os",
".",
"environ",
".",
"get",
... | Send GLRecord, Distributed Logging Utilities
If the scheme is passed as a keyword parameter
the value is expected to be a callable function
that takes 2 parameters: url, outputStr
GRIDLOG_ON -- turn grid logging on
GRIDLOG_DEST -- provide URL destination | [
"Send",
"GLRecord",
"Distributed",
"Logging",
"Utilities",
"If",
"the",
"scheme",
"is",
"passed",
"as",
"a",
"keyword",
"parameter",
"the",
"value",
"is",
"expected",
"to",
"be",
"a",
"callable",
"function",
"that",
"takes",
"2",
"parameters",
":",
"url",
"o... | python | train |
pysal/mapclassify | mapclassify/classifiers.py | https://github.com/pysal/mapclassify/blob/5b22ec33f5802becf40557614d90cd38efa1676e/mapclassify/classifiers.py#L476-L618 | def make(cls, *args, **kwargs):
"""
Configure and create a classifier that will consume data and produce
classifications, given the configuration options specified by this
function.
Note that this like a *partial application* of the relevant class
constructor. `make` cre... | [
"def",
"make",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# only flag overrides return flag",
"to_annotate",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"return_object",
"=",
"kwargs",
".",
"pop",
"(",
"'return_object'",
",",
"... | Configure and create a classifier that will consume data and produce
classifications, given the configuration options specified by this
function.
Note that this like a *partial application* of the relevant class
constructor. `make` creates a function that returns classifications; it
... | [
"Configure",
"and",
"create",
"a",
"classifier",
"that",
"will",
"consume",
"data",
"and",
"produce",
"classifications",
"given",
"the",
"configuration",
"options",
"specified",
"by",
"this",
"function",
"."
] | python | train |
llllllllll/codetransformer | codetransformer/utils/immutable.py | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L264-L287 | def _check_missing_slots(ob):
"""Check that all slots have been initialized when a custom __init__ method
is provided.
Parameters
----------
ob : immutable
The instance that was just initialized.
Raises
------
TypeError
Raised when the instance has not set values that a... | [
"def",
"_check_missing_slots",
"(",
"ob",
")",
":",
"missing_slots",
"=",
"tuple",
"(",
"filter",
"(",
"lambda",
"s",
":",
"not",
"hasattr",
"(",
"ob",
",",
"s",
")",
",",
"ob",
".",
"__slots__",
")",
",",
")",
"if",
"missing_slots",
":",
"raise",
"T... | Check that all slots have been initialized when a custom __init__ method
is provided.
Parameters
----------
ob : immutable
The instance that was just initialized.
Raises
------
TypeError
Raised when the instance has not set values that are named in the
__slots__. | [
"Check",
"that",
"all",
"slots",
"have",
"been",
"initialized",
"when",
"a",
"custom",
"__init__",
"method",
"is",
"provided",
"."
] | python | train |
psd-tools/psd-tools | src/psd_tools/utils.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/utils.py#L41-L51 | def write_fmt(fp, fmt, *args):
"""
Writes data to ``fp`` according to ``fmt``.
"""
fmt = str(">" + fmt)
fmt_size = struct.calcsize(fmt)
written = write_bytes(fp, struct.pack(fmt, *args))
assert written == fmt_size, 'written=%d, expected=%d' % (
written, fmt_size
)
return writ... | [
"def",
"write_fmt",
"(",
"fp",
",",
"fmt",
",",
"*",
"args",
")",
":",
"fmt",
"=",
"str",
"(",
"\">\"",
"+",
"fmt",
")",
"fmt_size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"written",
"=",
"write_bytes",
"(",
"fp",
",",
"struct",
".",
"p... | Writes data to ``fp`` according to ``fmt``. | [
"Writes",
"data",
"to",
"fp",
"according",
"to",
"fmt",
"."
] | python | train |
msoulier/tftpy | tftpy/TftpContexts.py | https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpContexts.py#L146-L150 | def sethost(self, host):
"""Setter method that also sets the address property as a result
of the host that is set."""
self.__host = host
self.address = socket.gethostbyname(host) | [
"def",
"sethost",
"(",
"self",
",",
"host",
")",
":",
"self",
".",
"__host",
"=",
"host",
"self",
".",
"address",
"=",
"socket",
".",
"gethostbyname",
"(",
"host",
")"
] | Setter method that also sets the address property as a result
of the host that is set. | [
"Setter",
"method",
"that",
"also",
"sets",
"the",
"address",
"property",
"as",
"a",
"result",
"of",
"the",
"host",
"that",
"is",
"set",
"."
] | python | train |
twisted/epsilon | epsilon/hotfixes/filepath_copyTo.py | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/hotfixes/filepath_copyTo.py#L96-L105 | def preauthChild(self, path):
"""
Use me if `path' might have slashes in it, but you know they're safe.
(NOT slashes at the beginning. It still needs to be a _child_).
"""
newpath = abspath(joinpath(self.path, normpath(path)))
if not newpath.startswith(self.path):
... | [
"def",
"preauthChild",
"(",
"self",
",",
"path",
")",
":",
"newpath",
"=",
"abspath",
"(",
"joinpath",
"(",
"self",
".",
"path",
",",
"normpath",
"(",
"path",
")",
")",
")",
"if",
"not",
"newpath",
".",
"startswith",
"(",
"self",
".",
"path",
")",
... | Use me if `path' might have slashes in it, but you know they're safe.
(NOT slashes at the beginning. It still needs to be a _child_). | [
"Use",
"me",
"if",
"path",
"might",
"have",
"slashes",
"in",
"it",
"but",
"you",
"know",
"they",
"re",
"safe",
"."
] | python | train |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L680-L740 | def memmap(filename, shape=None, dtype=None, page=None, series=0, mode='r+',
**kwargs):
"""Return memory-mapped numpy array stored in TIFF file.
Memory-mapping requires data stored in native byte order, without tiling,
compression, predictors, etc.
If 'shape' and 'dtype' are provided, existi... | [
"def",
"memmap",
"(",
"filename",
",",
"shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"page",
"=",
"None",
",",
"series",
"=",
"0",
",",
"mode",
"=",
"'r+'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"shape",
"is",
"not",
"None",
"and",
"... | Return memory-mapped numpy array stored in TIFF file.
Memory-mapping requires data stored in native byte order, without tiling,
compression, predictors, etc.
If 'shape' and 'dtype' are provided, existing files will be overwritten or
appended to depending on the 'append' parameter.
Otherwise the ima... | [
"Return",
"memory",
"-",
"mapped",
"numpy",
"array",
"stored",
"in",
"TIFF",
"file",
"."
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L1035-L1038 | def create(self, name, data=None):
"""Creates a new packet with the given definition and raw data.
"""
return createPacket(self[name], data) if name in self else None | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
")",
":",
"return",
"createPacket",
"(",
"self",
"[",
"name",
"]",
",",
"data",
")",
"if",
"name",
"in",
"self",
"else",
"None"
] | Creates a new packet with the given definition and raw data. | [
"Creates",
"a",
"new",
"packet",
"with",
"the",
"given",
"definition",
"and",
"raw",
"data",
"."
] | python | train |
pkgw/pwkit | pwkit/cli/latexdriver.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/cli/latexdriver.py#L319-L329 | def just_smart_bibtools(bib_style, aux, bib):
"""Tectonic has taken over most of the features that this tool used to provide,
but here's a hack to keep my smart .bib file generation working.
"""
extradir = Path('.bibtex')
extradir.ensure_dir(parents=True)
bib_export(bib_style, aux, extradir / ... | [
"def",
"just_smart_bibtools",
"(",
"bib_style",
",",
"aux",
",",
"bib",
")",
":",
"extradir",
"=",
"Path",
"(",
"'.bibtex'",
")",
"extradir",
".",
"ensure_dir",
"(",
"parents",
"=",
"True",
")",
"bib_export",
"(",
"bib_style",
",",
"aux",
",",
"extradir",
... | Tectonic has taken over most of the features that this tool used to provide,
but here's a hack to keep my smart .bib file generation working. | [
"Tectonic",
"has",
"taken",
"over",
"most",
"of",
"the",
"features",
"that",
"this",
"tool",
"used",
"to",
"provide",
"but",
"here",
"s",
"a",
"hack",
"to",
"keep",
"my",
"smart",
".",
"bib",
"file",
"generation",
"working",
"."
] | python | train |
jamescooke/flake8-aaa | src/flake8_aaa/helpers.py | https://github.com/jamescooke/flake8-aaa/blob/29938b96845fe32ced4358ba66af3b3be2a37794/src/flake8_aaa/helpers.py#L105-L109 | def node_is_noop(node: ast.AST) -> bool:
"""
Node does nothing.
"""
return isinstance(node.value, ast.Str) if isinstance(node, ast.Expr) else isinstance(node, ast.Pass) | [
"def",
"node_is_noop",
"(",
"node",
":",
"ast",
".",
"AST",
")",
"->",
"bool",
":",
"return",
"isinstance",
"(",
"node",
".",
"value",
",",
"ast",
".",
"Str",
")",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Expr",
")",
"else",
"isinstance",
... | Node does nothing. | [
"Node",
"does",
"nothing",
"."
] | python | train |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/data/StringValueMap.py | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/StringValueMap.py#L480-L505 | def from_tuples_array(tuples):
"""
Creates a new StringValueMap from a list of key-value pairs called tuples.
The method is similar to [[fromTuples]] but tuples are passed as array instead of parameters.
:param tuples: a list of values where odd elements are keys and the following even ... | [
"def",
"from_tuples_array",
"(",
"tuples",
")",
":",
"result",
"=",
"StringValueMap",
"(",
")",
"if",
"tuples",
"==",
"None",
"or",
"len",
"(",
"tuples",
")",
"==",
"0",
":",
"return",
"result",
"index",
"=",
"0",
"while",
"index",
"<",
"len",
"(",
"... | Creates a new StringValueMap from a list of key-value pairs called tuples.
The method is similar to [[fromTuples]] but tuples are passed as array instead of parameters.
:param tuples: a list of values where odd elements are keys and the following even elements are values
:return: a newly creat... | [
"Creates",
"a",
"new",
"StringValueMap",
"from",
"a",
"list",
"of",
"key",
"-",
"value",
"pairs",
"called",
"tuples",
".",
"The",
"method",
"is",
"similar",
"to",
"[[",
"fromTuples",
"]]",
"but",
"tuples",
"are",
"passed",
"as",
"array",
"instead",
"of",
... | python | train |
genepattern/nbtools | nbtools/jsobject/utils.py | https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/utils.py#L30-L33 | def _try_then(self):
"""Check to see if self has been resolved yet, if so invoke then."""
if self._cached is not None and self._callback is not None:
self._callback(*self._cached[0], **self._cached[1]) | [
"def",
"_try_then",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cached",
"is",
"not",
"None",
"and",
"self",
".",
"_callback",
"is",
"not",
"None",
":",
"self",
".",
"_callback",
"(",
"*",
"self",
".",
"_cached",
"[",
"0",
"]",
",",
"*",
"*",
"se... | Check to see if self has been resolved yet, if so invoke then. | [
"Check",
"to",
"see",
"if",
"self",
"has",
"been",
"resolved",
"yet",
"if",
"so",
"invoke",
"then",
"."
] | python | train |
lvjiyong/configreset | configreset/__init__.py | https://github.com/lvjiyong/configreset/blob/cde0a426e993a6aa483d6934358e61750c944de9/configreset/__init__.py#L53-L87 | def load_package(package_dir, package=None, exclude=None, default_section=_DEFAULT_SECTION):
"""
从目录中载入配置文件
:param package_dir:
:param package:
:param exclude:
:param default_section:
:return:
"""
init_py = '__init__.py'
py_ext = '.py'
files = os.listdir(package_dir)
if i... | [
"def",
"load_package",
"(",
"package_dir",
",",
"package",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"default_section",
"=",
"_DEFAULT_SECTION",
")",
":",
"init_py",
"=",
"'__init__.py'",
"py_ext",
"=",
"'.py'",
"files",
"=",
"os",
".",
"listdir",
"(",
... | 从目录中载入配置文件
:param package_dir:
:param package:
:param exclude:
:param default_section:
:return: | [
"从目录中载入配置文件",
":",
"param",
"package_dir",
":",
":",
"param",
"package",
":",
":",
"param",
"exclude",
":",
":",
"param",
"default_section",
":",
":",
"return",
":"
] | python | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L361-L381 | def _handle_stop_dag(self, request):
""" The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (Request): Reference to a req... | [
"def",
"_handle_stop_dag",
"(",
"self",
",",
"request",
")",
":",
"if",
"(",
"request",
".",
"payload",
"[",
"'name'",
"]",
"is",
"not",
"None",
")",
"and",
"(",
"request",
".",
"payload",
"[",
"'name'",
"]",
"not",
"in",
"self",
".",
"_stop_dags",
"... | The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (Request): Reference to a request object containing the
... | [
"The",
"handler",
"for",
"the",
"stop_dag",
"request",
"."
] | python | train |
cortical-io/retina-sdk.py | retinasdk/client/terms_api.py | https://github.com/cortical-io/retina-sdk.py/blob/474c13ad399fe1e974d2650335537608f4456b07/retinasdk/client/terms_api.py#L76-L104 | def getSimilarTerms(self, retina_name, term, context_id=None, pos_type=None, get_fingerprint=None, start_index=0, max_results=10):
"""Get the similar terms of a given term
Args:
retina_name, str: The retina name (required)
term, str: A term in the retina (required)
co... | [
"def",
"getSimilarTerms",
"(",
"self",
",",
"retina_name",
",",
"term",
",",
"context_id",
"=",
"None",
",",
"pos_type",
"=",
"None",
",",
"get_fingerprint",
"=",
"None",
",",
"start_index",
"=",
"0",
",",
"max_results",
"=",
"10",
")",
":",
"resourcePath"... | Get the similar terms of a given term
Args:
retina_name, str: The retina name (required)
term, str: A term in the retina (required)
context_id, int: The identifier of a context (optional) (optional)
pos_type, str: Part of speech (optional) (optional)
g... | [
"Get",
"the",
"similar",
"terms",
"of",
"a",
"given",
"term",
"Args",
":",
"retina_name",
"str",
":",
"The",
"retina",
"name",
"(",
"required",
")",
"term",
"str",
":",
"A",
"term",
"in",
"the",
"retina",
"(",
"required",
")",
"context_id",
"int",
":",... | python | train |
rs/domcheck | domcheck/strategies.py | https://github.com/rs/domcheck/blob/43e10c345320564a1236778e8577e2b8ef825925/domcheck/strategies.py#L65-L86 | def check_meta_tag(domain, prefix, code):
"""
Validates a domain by checking the existance of a <meta name="{prefix}" content="{code}">
tag in the <head> of the home page of the domain using either HTTP or HTTPs protocols.
Returns true if verification suceeded.
"""
url = '://{}'.format(domain)
... | [
"def",
"check_meta_tag",
"(",
"domain",
",",
"prefix",
",",
"code",
")",
":",
"url",
"=",
"'://{}'",
".",
"format",
"(",
"domain",
")",
"for",
"proto",
"in",
"(",
"'http'",
",",
"'https'",
")",
":",
"try",
":",
"req",
"=",
"Request",
"(",
"proto",
... | Validates a domain by checking the existance of a <meta name="{prefix}" content="{code}">
tag in the <head> of the home page of the domain using either HTTP or HTTPs protocols.
Returns true if verification suceeded. | [
"Validates",
"a",
"domain",
"by",
"checking",
"the",
"existance",
"of",
"a",
"<meta",
"name",
"=",
"{",
"prefix",
"}",
"content",
"=",
"{",
"code",
"}",
">",
"tag",
"in",
"the",
"<head",
">",
"of",
"the",
"home",
"page",
"of",
"the",
"domain",
"using... | python | train |
saltstack/salt | salt/client/ssh/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/__init__.py#L932-L943 | def __arg_comps(self):
'''
Return the function name and the arg list
'''
fun = self.argv[0] if self.argv else ''
parsed = salt.utils.args.parse_input(
self.argv[1:],
condition=False,
no_parse=self.opts.get('no_parse', []))
args = parsed... | [
"def",
"__arg_comps",
"(",
"self",
")",
":",
"fun",
"=",
"self",
".",
"argv",
"[",
"0",
"]",
"if",
"self",
".",
"argv",
"else",
"''",
"parsed",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"parse_input",
"(",
"self",
".",
"argv",
"[",
"1",
":",
... | Return the function name and the arg list | [
"Return",
"the",
"function",
"name",
"and",
"the",
"arg",
"list"
] | python | train |
dcos/shakedown | shakedown/dcos/security.py | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/security.py#L175-L196 | def add_group(id, description=None):
""" Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str
"""
if not description:
de... | [
"def",
"add_group",
"(",
"id",
",",
"description",
"=",
"None",
")",
":",
"if",
"not",
"description",
":",
"description",
"=",
"id",
"data",
"=",
"{",
"'description'",
":",
"description",
"}",
"acl_url",
"=",
"urljoin",
"(",
"_acl_url",
"(",
")",
",",
... | Adds group to the DCOS Enterprise. If not description
is provided the id will be used for the description.
:param id: group id
:type id: str
:param desc: description of user
:type desc: str | [
"Adds",
"group",
"to",
"the",
"DCOS",
"Enterprise",
".",
"If",
"not",
"description",
"is",
"provided",
"the",
"id",
"will",
"be",
"used",
"for",
"the",
"description",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/electronic_structure/cohp.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/electronic_structure/cohp.py#L362-L383 | def get_cohp_by_label(self, label):
"""
Get specific COHP object.
Args:
label: string (for newer Lobster versions: a number)
Returns:
Returns the COHP object to simplify plotting
"""
if label.lower() == "average":
return Cohp(efermi=s... | [
"def",
"get_cohp_by_label",
"(",
"self",
",",
"label",
")",
":",
"if",
"label",
".",
"lower",
"(",
")",
"==",
"\"average\"",
":",
"return",
"Cohp",
"(",
"efermi",
"=",
"self",
".",
"efermi",
",",
"energies",
"=",
"self",
".",
"energies",
",",
"cohp",
... | Get specific COHP object.
Args:
label: string (for newer Lobster versions: a number)
Returns:
Returns the COHP object to simplify plotting | [
"Get",
"specific",
"COHP",
"object",
"."
] | python | train |
marl/jams | jams/core.py | https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/core.py#L87-L152 | def _open(name_or_fdesc, mode='r', fmt='auto'):
'''An intelligent wrapper for ``open``.
Parameters
----------
name_or_fdesc : string-type or open file descriptor
If a string type, refers to the path to a file on disk.
If an open file descriptor, it is returned as-is.
mode : string... | [
"def",
"_open",
"(",
"name_or_fdesc",
",",
"mode",
"=",
"'r'",
",",
"fmt",
"=",
"'auto'",
")",
":",
"open_map",
"=",
"{",
"'jams'",
":",
"open",
",",
"'json'",
":",
"open",
",",
"'jamz'",
":",
"gzip",
".",
"open",
",",
"'gz'",
":",
"gzip",
".",
"... | An intelligent wrapper for ``open``.
Parameters
----------
name_or_fdesc : string-type or open file descriptor
If a string type, refers to the path to a file on disk.
If an open file descriptor, it is returned as-is.
mode : string
The mode with which to open the file.
... | [
"An",
"intelligent",
"wrapper",
"for",
"open",
"."
] | python | valid |
apple/turicreate | src/unity/python/turicreate/toolkits/topic_model/topic_model.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/topic_model/topic_model.py#L35-L271 | def create(dataset,
num_topics=10,
initial_topics=None,
alpha=None,
beta=.1,
num_iterations=10,
num_burnin=5,
associations=None,
verbose=False,
print_interval=10,
validation_set=None,
method='auto'):... | [
"def",
"create",
"(",
"dataset",
",",
"num_topics",
"=",
"10",
",",
"initial_topics",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"beta",
"=",
".1",
",",
"num_iterations",
"=",
"10",
",",
"num_burnin",
"=",
"5",
",",
"associations",
"=",
"None",
",",
... | Create a topic model from the given data set. A topic model assumes each
document is a mixture of a set of topics, where for each topic some words
are more likely than others. One statistical approach to do this is called a
"topic model". This method learns a topic model for the given document
collectio... | [
"Create",
"a",
"topic",
"model",
"from",
"the",
"given",
"data",
"set",
".",
"A",
"topic",
"model",
"assumes",
"each",
"document",
"is",
"a",
"mixture",
"of",
"a",
"set",
"of",
"topics",
"where",
"for",
"each",
"topic",
"some",
"words",
"are",
"more",
... | python | train |
Erotemic/utool | utool/util_hash.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_hash.py#L726-L763 | def convert_bytes_to_bigbase(bytes_, alphabet=ALPHABET_27):
r"""
Args:
bytes_ (bytes):
Returns:
str:
Ignore:
CommandLine:
python -m utool.util_hash convert_bytes_to_bigbase
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_hash import * # NOQA
... | [
"def",
"convert_bytes_to_bigbase",
"(",
"bytes_",
",",
"alphabet",
"=",
"ALPHABET_27",
")",
":",
"x",
"=",
"_bytes_to_int",
"(",
"bytes_",
")",
"if",
"x",
"==",
"0",
":",
"return",
"'0'",
"sign",
"=",
"1",
"if",
"x",
">",
"0",
"else",
"-",
"1",
"x",
... | r"""
Args:
bytes_ (bytes):
Returns:
str:
Ignore:
CommandLine:
python -m utool.util_hash convert_bytes_to_bigbase
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_hash import * # NOQA
>>> import utool as ut
>>> bytes_ = b('999999999999999... | [
"r",
"Args",
":",
"bytes_",
"(",
"bytes",
")",
":"
] | python | train |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L208-L244 | def get_name_cost( db, name ):
"""
Get the cost of a name, given the fully-qualified name.
Do so by finding the namespace it belongs to (even if the namespace is being imported).
Return {'amount': ..., 'units': ...} on success
Return None if the namespace has not been declared
"""
lastblock... | [
"def",
"get_name_cost",
"(",
"db",
",",
"name",
")",
":",
"lastblock",
"=",
"db",
".",
"lastblock",
"namespace_id",
"=",
"get_namespace_from_name",
"(",
"name",
")",
"if",
"namespace_id",
"is",
"None",
"or",
"len",
"(",
"namespace_id",
")",
"==",
"0",
":",... | Get the cost of a name, given the fully-qualified name.
Do so by finding the namespace it belongs to (even if the namespace is being imported).
Return {'amount': ..., 'units': ...} on success
Return None if the namespace has not been declared | [
"Get",
"the",
"cost",
"of",
"a",
"name",
"given",
"the",
"fully",
"-",
"qualified",
"name",
".",
"Do",
"so",
"by",
"finding",
"the",
"namespace",
"it",
"belongs",
"to",
"(",
"even",
"if",
"the",
"namespace",
"is",
"being",
"imported",
")",
"."
] | python | train |
openthread/openthread | tools/harness-thci/OpenThread_WpanCtl.py | https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread_WpanCtl.py#L439-L459 | def __setAddressfilterMode(self, mode):
"""set address filter mode
Returns:
True: successful to set address filter mode.
False: fail to set address filter mode.
"""
print 'call setAddressFilterMode() ' + mode
try:
if re.match('list', mode, re... | [
"def",
"__setAddressfilterMode",
"(",
"self",
",",
"mode",
")",
":",
"print",
"'call setAddressFilterMode() '",
"+",
"mode",
"try",
":",
"if",
"re",
".",
"match",
"(",
"'list'",
",",
"mode",
",",
"re",
".",
"M",
"|",
"re",
".",
"I",
")",
":",
"cmd",
... | set address filter mode
Returns:
True: successful to set address filter mode.
False: fail to set address filter mode. | [
"set",
"address",
"filter",
"mode"
] | python | train |
KnuVerse/knuverse-sdk-python | knuverse/knufactor.py | https://github.com/KnuVerse/knuverse-sdk-python/blob/00f1275a452a4dcf9bc92ef345f6985504226d8e/knuverse/knufactor.py#L728-L752 | def report_events(self, start_date, end_date, type="system"):
"""
Create a report for all client events or all system events.
Uses GET to /reports/events/{clients,system} interface
:Args:
* *start_date*: (datetime) Start time for report generation
* *end_date*: (date... | [
"def",
"report_events",
"(",
"self",
",",
"start_date",
",",
"end_date",
",",
"type",
"=",
"\"system\"",
")",
":",
"start_str",
",",
"end_str",
"=",
"self",
".",
"_format_input_dates",
"(",
"start_date",
",",
"end_date",
")",
"params",
"=",
"{",
"\"start_dat... | Create a report for all client events or all system events.
Uses GET to /reports/events/{clients,system} interface
:Args:
* *start_date*: (datetime) Start time for report generation
* *end_date*: (datetime) End time for report generation
:Kwargs:
* *type*: (str) Ty... | [
"Create",
"a",
"report",
"for",
"all",
"client",
"events",
"or",
"all",
"system",
"events",
".",
"Uses",
"GET",
"to",
"/",
"reports",
"/",
"events",
"/",
"{",
"clients",
"system",
"}",
"interface"
] | python | train |
saltstack/salt | salt/client/ssh/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/state.py#L92-L119 | def _master_tops(self):
'''
Evaluate master_tops locally
'''
if 'id' not in self.opts:
log.error('Received call for external nodes without an id')
return {}
if not salt.utils.verify.valid_id(self.opts, self.opts['id']):
return {}
# Eval... | [
"def",
"_master_tops",
"(",
"self",
")",
":",
"if",
"'id'",
"not",
"in",
"self",
".",
"opts",
":",
"log",
".",
"error",
"(",
"'Received call for external nodes without an id'",
")",
"return",
"{",
"}",
"if",
"not",
"salt",
".",
"utils",
".",
"verify",
".",... | Evaluate master_tops locally | [
"Evaluate",
"master_tops",
"locally"
] | python | train |
tchellomello/raincloudy | raincloudy/controller.py | https://github.com/tchellomello/raincloudy/blob/1847fa913e5ba79645d51bf23637860d68c67dbf/raincloudy/controller.py#L48-L55 | def _assign_faucets(self, faucets):
"""Assign RainCloudyFaucet objects to self.faucets."""
if not faucets:
raise TypeError("Controller does not have a faucet assigned.")
for faucet_id in faucets:
self.faucets.append(
RainCloudyFaucet(self._parent, self, f... | [
"def",
"_assign_faucets",
"(",
"self",
",",
"faucets",
")",
":",
"if",
"not",
"faucets",
":",
"raise",
"TypeError",
"(",
"\"Controller does not have a faucet assigned.\"",
")",
"for",
"faucet_id",
"in",
"faucets",
":",
"self",
".",
"faucets",
".",
"append",
"(",... | Assign RainCloudyFaucet objects to self.faucets. | [
"Assign",
"RainCloudyFaucet",
"objects",
"to",
"self",
".",
"faucets",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.