nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Qiskit/qiskit-terra | b66030e3b9192efdd3eb95cf25c6545fe0a13da4 | qiskit/transpiler/coupling.py | python | CouplingMap.distance | (self, physical_qubit1, physical_qubit2) | return int(self._dist_matrix[physical_qubit1, physical_qubit2]) | Returns the undirected distance between physical_qubit1 and physical_qubit2.
Args:
physical_qubit1 (int): A physical qubit
physical_qubit2 (int): Another physical qubit
Returns:
int: The undirected distance
Raises:
CouplingError: if the qubits do not exist in the CouplingMap | Returns the undirected distance between physical_qubit1 and physical_qubit2. | [
"Returns",
"the",
"undirected",
"distance",
"between",
"physical_qubit1",
"and",
"physical_qubit2",
"."
] | def distance(self, physical_qubit1, physical_qubit2):
"""Returns the undirected distance between physical_qubit1 and physical_qubit2.
Args:
physical_qubit1 (int): A physical qubit
physical_qubit2 (int): Another physical qubit
Returns:
int: The undirected distance
Raises:
CouplingError: if the qubits do not exist in the CouplingMap
"""
if physical_qubit1 >= self.size():
raise CouplingError("%s not in coupling graph" % physical_qubit1)
if physical_qubit2 >= self.size():
raise CouplingError("%s not in coupling graph" % physical_qubit2)
self.compute_distance_matrix()
return int(self._dist_matrix[physical_qubit1, physical_qubit2]) | [
"def",
"distance",
"(",
"self",
",",
"physical_qubit1",
",",
"physical_qubit2",
")",
":",
"if",
"physical_qubit1",
">=",
"self",
".",
"size",
"(",
")",
":",
"raise",
"CouplingError",
"(",
"\"%s not in coupling graph\"",
"%",
"physical_qubit1",
")",
"if",
"physic... | https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/transpiler/coupling.py#L181-L199 | |
Scalsol/mega.pytorch | a6aa6e0537b82d70da94228100a51e6a53d98f82 | mega_core/layers/dcn/deform_conv_module.py | python | ModulatedDeformConvPack.__init__ | (self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
deformable_groups=1,
bias=True) | [] | def __init__(self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
deformable_groups=1,
bias=True):
super(ModulatedDeformConvPack, self).__init__(
in_channels, out_channels, kernel_size, stride, padding, dilation,
groups, deformable_groups, bias)
self.conv_offset_mask = nn.Conv2d(
self.in_channels // self.groups,
self.deformable_groups * 3 * self.kernel_size[0] *
self.kernel_size[1],
kernel_size=self.kernel_size,
stride=_pair(self.stride),
padding=_pair(self.padding),
bias=True)
self.init_offset() | [
"def",
"__init__",
"(",
"self",
",",
"in_channels",
",",
"out_channels",
",",
"kernel_size",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"dilation",
"=",
"1",
",",
"groups",
"=",
"1",
",",
"deformable_groups",
"=",
"1",
",",
"bias",
"=",
... | https://github.com/Scalsol/mega.pytorch/blob/a6aa6e0537b82d70da94228100a51e6a53d98f82/mega_core/layers/dcn/deform_conv_module.py#L142-L164 | ||||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py | python | TableClause.delete | (self, dml, whereclause=None, **kwargs) | return dml.Delete(self, whereclause, **kwargs) | Generate a :func:`.delete` construct against this
:class:`.TableClause`.
E.g.::
table.delete().where(table.c.id==7)
See :func:`.delete` for argument and usage information. | Generate a :func:`.delete` construct against this
:class:`.TableClause`. | [
"Generate",
"a",
":",
"func",
":",
".",
"delete",
"construct",
"against",
"this",
":",
"class",
":",
".",
"TableClause",
"."
] | def delete(self, dml, whereclause=None, **kwargs):
"""Generate a :func:`.delete` construct against this
:class:`.TableClause`.
E.g.::
table.delete().where(table.c.id==7)
See :func:`.delete` for argument and usage information.
"""
return dml.Delete(self, whereclause, **kwargs) | [
"def",
"delete",
"(",
"self",
",",
"dml",
",",
"whereclause",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dml",
".",
"Delete",
"(",
"self",
",",
"whereclause",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py#L1775-L1787 | |
eirannejad/pyRevit | 49c0b7eb54eb343458ce1365425e6552d0c47d44 | site-packages/requests/adapters.py | python | HTTPAdapter.build_response | (self, req, resp) | return response | Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
:rtype: requests.Response | Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>` | [
"Builds",
"a",
":",
"class",
":",
"Response",
"<requests",
".",
"Response",
">",
"object",
"from",
"a",
"urllib3",
"response",
".",
"This",
"should",
"not",
"be",
"called",
"from",
"user",
"code",
"and",
"is",
"only",
"exposed",
"for",
"use",
"when",
"su... | def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
:rtype: requests.Response
"""
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response | [
"def",
"build_response",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"response",
"=",
"Response",
"(",
")",
"# Fallback to None if there's no status_code, for whatever reason.",
"response",
".",
"status_code",
"=",
"getattr",
"(",
"resp",
",",
"'status'",
",",
... | https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/requests/adapters.py#L240-L275 | |
jazzband/django-oauth-toolkit | ac201526843ff63ad3861bb37e4099521cff091a | oauth2_provider/views/mixins.py | python | OAuthLibMixin.create_token_response | (self, request) | return core.create_token_response(request) | A wrapper method that calls create_token_response on `server_class` instance.
:param request: The current django.http.HttpRequest object | A wrapper method that calls create_token_response on `server_class` instance. | [
"A",
"wrapper",
"method",
"that",
"calls",
"create_token_response",
"on",
"server_class",
"instance",
"."
] | def create_token_response(self, request):
"""
A wrapper method that calls create_token_response on `server_class` instance.
:param request: The current django.http.HttpRequest object
"""
core = self.get_oauthlib_core()
return core.create_token_response(request) | [
"def",
"create_token_response",
"(",
"self",
",",
"request",
")",
":",
"core",
"=",
"self",
".",
"get_oauthlib_core",
"(",
")",
"return",
"core",
".",
"create_token_response",
"(",
"request",
")"
] | https://github.com/jazzband/django-oauth-toolkit/blob/ac201526843ff63ad3861bb37e4099521cff091a/oauth2_provider/views/mixins.py#L117-L124 | |
python/cpython | e13cdca0f5224ec4e23bdd04bb3120506964bc8b | Lib/idlelib/colorizer.py | python | any | (name, alternates) | return "(?P<%s>" % name + "|".join(alternates) + ")" | Return a named group pattern matching list of alternates. | Return a named group pattern matching list of alternates. | [
"Return",
"a",
"named",
"group",
"pattern",
"matching",
"list",
"of",
"alternates",
"."
] | def any(name, alternates):
"Return a named group pattern matching list of alternates."
return "(?P<%s>" % name + "|".join(alternates) + ")" | [
"def",
"any",
"(",
"name",
",",
"alternates",
")",
":",
"return",
"\"(?P<%s>\"",
"%",
"name",
"+",
"\"|\"",
".",
"join",
"(",
"alternates",
")",
"+",
"\")\""
] | https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/idlelib/colorizer.py#L12-L14 | |
JetBrains/python-skeletons | 95ad24b666e475998e5d1cc02ed53a2188036167 | py/path/__init__.py | python | LocalPath.dump | (self, obj, bin=1) | pickle object into path location | pickle object into path location | [
"pickle",
"object",
"into",
"path",
"location"
] | def dump(self, obj, bin=1):
""" pickle object into path location""" | [
"def",
"dump",
"(",
"self",
",",
"obj",
",",
"bin",
"=",
"1",
")",
":"
] | https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/py/path/__init__.py#L247-L248 | ||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/queue.py | python | PriorityQueue._qsize | (self) | return len(self.queue) | [] | def _qsize(self):
return len(self.queue) | [
"def",
"_qsize",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"queue",
")"
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/queue.py#L226-L227 | |||
girder/girder | 0766ba8e7f9b25ce81e7c0d19bd343479bceea20 | girder/api/rest.py | python | Resource.getCurrentToken | (self) | return getCurrentToken() | Returns the current valid token object that was passed via the token
header or parameter, or None if no valid token was passed. | Returns the current valid token object that was passed via the token
header or parameter, or None if no valid token was passed. | [
"Returns",
"the",
"current",
"valid",
"token",
"object",
"that",
"was",
"passed",
"via",
"the",
"token",
"header",
"or",
"parameter",
"or",
"None",
"if",
"no",
"valid",
"token",
"was",
"passed",
"."
] | def getCurrentToken(self):
"""
Returns the current valid token object that was passed via the token
header or parameter, or None if no valid token was passed.
"""
return getCurrentToken() | [
"def",
"getCurrentToken",
"(",
"self",
")",
":",
"return",
"getCurrentToken",
"(",
")"
] | https://github.com/girder/girder/blob/0766ba8e7f9b25ce81e7c0d19bd343479bceea20/girder/api/rest.py#L1138-L1143 | |
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/Ubuntu_12/paramiko/sftp_client.py | python | SFTPClient.normalize | (self, path) | return _to_unicode(msg.get_string()) | Return the normalized path (on the server) of a given path. This
can be used to quickly resolve symbolic links or determine what the
server is considering to be the "current folder" (by passing C{'.'}
as C{path}).
@param path: path to be normalized
@type path: str
@return: normalized form of the given path
@rtype: str
@raise IOError: if the path can't be resolved on the server | Return the normalized path (on the server) of a given path. This
can be used to quickly resolve symbolic links or determine what the
server is considering to be the "current folder" (by passing C{'.'}
as C{path}). | [
"Return",
"the",
"normalized",
"path",
"(",
"on",
"the",
"server",
")",
"of",
"a",
"given",
"path",
".",
"This",
"can",
"be",
"used",
"to",
"quickly",
"resolve",
"symbolic",
"links",
"or",
"determine",
"what",
"the",
"server",
"is",
"considering",
"to",
... | def normalize(self, path):
"""
Return the normalized path (on the server) of a given path. This
can be used to quickly resolve symbolic links or determine what the
server is considering to be the "current folder" (by passing C{'.'}
as C{path}).
@param path: path to be normalized
@type path: str
@return: normalized form of the given path
@rtype: str
@raise IOError: if the path can't be resolved on the server
"""
path = self._adjust_cwd(path)
self._log(DEBUG, 'normalize(%r)' % path)
t, msg = self._request(CMD_REALPATH, path)
if t != CMD_NAME:
raise SFTPError('Expected name response')
count = msg.get_int()
if count != 1:
raise SFTPError('Realpath returned %d results' % count)
return _to_unicode(msg.get_string()) | [
"def",
"normalize",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"_adjust_cwd",
"(",
"path",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"'normalize(%r)'",
"%",
"path",
")",
"t",
",",
"msg",
"=",
"self",
".",
"_request",
"(",
"CMD... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/paramiko/sftp_client.py#L476-L498 | |
bookwyrm-social/bookwyrm | 0c2537e27a2cdbc0136880dfbbf170d5fec72986 | bookwyrm/models/book.py | python | BookDataModel.broadcast | (self, activity, sender, software="bookwyrm", **kwargs) | only send book data updates to other bookwyrm instances | only send book data updates to other bookwyrm instances | [
"only",
"send",
"book",
"data",
"updates",
"to",
"other",
"bookwyrm",
"instances"
] | def broadcast(self, activity, sender, software="bookwyrm", **kwargs):
"""only send book data updates to other bookwyrm instances"""
super().broadcast(activity, sender, software=software, **kwargs) | [
"def",
"broadcast",
"(",
"self",
",",
"activity",
",",
"sender",
",",
"software",
"=",
"\"bookwyrm\"",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"broadcast",
"(",
"activity",
",",
"sender",
",",
"software",
"=",
"software",
",",
"*",
... | https://github.com/bookwyrm-social/bookwyrm/blob/0c2537e27a2cdbc0136880dfbbf170d5fec72986/bookwyrm/models/book.py#L82-L84 | ||
mme/vergeml | 3dc30ba4e0f3d038743b6d468860cbcf3681acc6 | vergeml/option.py | python | Option.is_optional | (self) | return self.default is not None or self.has_optional_type() | [] | def is_optional(self):
return self.default is not None or self.has_optional_type() | [
"def",
"is_optional",
"(",
"self",
")",
":",
"return",
"self",
".",
"default",
"is",
"not",
"None",
"or",
"self",
".",
"has_optional_type",
"(",
")"
] | https://github.com/mme/vergeml/blob/3dc30ba4e0f3d038743b6d468860cbcf3681acc6/vergeml/option.py#L328-L329 | |||
dswah/pyGAM | b57b4cf8783a90976031e1857e748ca3e6ec650b | pygam/pygam.py | python | LinearGAM._validate_params | (self) | method to sanitize model parameters
Parameters
---------
None
Returns
-------
None | method to sanitize model parameters | [
"method",
"to",
"sanitize",
"model",
"parameters"
] | def _validate_params(self):
"""
method to sanitize model parameters
Parameters
---------
None
Returns
-------
None
"""
self.distribution = NormalDist(scale=self.scale)
super(LinearGAM, self)._validate_params() | [
"def",
"_validate_params",
"(",
"self",
")",
":",
"self",
".",
"distribution",
"=",
"NormalDist",
"(",
"scale",
"=",
"self",
".",
"scale",
")",
"super",
"(",
"LinearGAM",
",",
"self",
")",
".",
"_validate_params",
"(",
")"
] | https://github.com/dswah/pyGAM/blob/b57b4cf8783a90976031e1857e748ca3e6ec650b/pygam/pygam.py#L2296-L2309 | ||
ztwo/Auto_Analysis | 795db843dda0e677f20f1e1b16f38d945da83369 | lib/adbUtils.py | python | ADB.first_install_time | (self) | 查询当前屏幕应用安装时间 | 查询当前屏幕应用安装时间 | [
"查询当前屏幕应用安装时间"
] | def first_install_time(self):
"""
查询当前屏幕应用安装时间
"""
for package in self.shell(
'dumpsys package %s' %
self.get_current_package_name()).stdout.readlines():
if 'firstInstallTime' in package:
return package.split('=', 2)[1].strip() | [
"def",
"first_install_time",
"(",
"self",
")",
":",
"for",
"package",
"in",
"self",
".",
"shell",
"(",
"'dumpsys package %s'",
"%",
"self",
".",
"get_current_package_name",
"(",
")",
")",
".",
"stdout",
".",
"readlines",
"(",
")",
":",
"if",
"'firstInstallTi... | https://github.com/ztwo/Auto_Analysis/blob/795db843dda0e677f20f1e1b16f38d945da83369/lib/adbUtils.py#L710-L718 | ||
plastex/plastex | af1628719b50cf25fbe80f16a3e100d566e9bc32 | plasTeX/__init__.py | python | Macro.locals | (self) | return loc | Retrieve all macros local to this namespace | Retrieve all macros local to this namespace | [
"Retrieve",
"all",
"macros",
"local",
"to",
"this",
"namespace"
] | def locals(self):
""" Retrieve all macros local to this namespace """
tself = type(self)
localsname = '@locals'
# Check for cached versions first
try:
return vars(tself)[localsname]
except KeyError:
pass
mro = list(tself.__mro__)
mro.reverse()
loc = {}
for cls in mro:
for value in list(vars(cls).values()):
if ismacro(value):
loc[macroName(value)] = value
# Cache the locals in a unique name
setattr(tself, localsname, loc)
return loc | [
"def",
"locals",
"(",
"self",
")",
":",
"tself",
"=",
"type",
"(",
"self",
")",
"localsname",
"=",
"'@locals'",
"# Check for cached versions first",
"try",
":",
"return",
"vars",
"(",
"tself",
")",
"[",
"localsname",
"]",
"except",
"KeyError",
":",
"pass",
... | https://github.com/plastex/plastex/blob/af1628719b50cf25fbe80f16a3e100d566e9bc32/plasTeX/__init__.py#L308-L326 | |
youtube/spitfire | 1916e68d50ed30f395928585ef2f0d3ba1468ab0 | third_party/yapps2/yappsrt.py | python | Scanner.token | (self, i, restrict=0) | Get the i'th token, and if i is one past the end, then scan
for another token; restrict is a list of tokens that
are allowed, or 0 for any token. | Get the i'th token, and if i is one past the end, then scan
for another token; restrict is a list of tokens that
are allowed, or 0 for any token. | [
"Get",
"the",
"i",
"th",
"token",
"and",
"if",
"i",
"is",
"one",
"past",
"the",
"end",
"then",
"scan",
"for",
"another",
"token",
";",
"restrict",
"is",
"a",
"list",
"of",
"tokens",
"that",
"are",
"allowed",
"or",
"0",
"for",
"any",
"token",
"."
] | def token(self, i, restrict=0):
"""Get the i'th token, and if i is one past the end, then scan
for another token; restrict is a list of tokens that
are allowed, or 0 for any token."""
if i == len(self.tokens):
self.scan(restrict)
if i < len(self.tokens):
# Make sure the restriction is more restricted
if restrict and self.restrictions[i]:
for r in restrict:
if r not in self.restrictions[i]:
raise NotImplementedError(
"Unimplemented: restriction set changed", r, self.restrictions[i])
return self.tokens[i]
elif not restrict and not self.restrictions[i]:
return self.tokens[i]
raise NoMoreTokens(i, len(self.tokens), self.tokens[i], restrict, self.restrictions[i], self.tokens) | [
"def",
"token",
"(",
"self",
",",
"i",
",",
"restrict",
"=",
"0",
")",
":",
"if",
"i",
"==",
"len",
"(",
"self",
".",
"tokens",
")",
":",
"self",
".",
"scan",
"(",
"restrict",
")",
"if",
"i",
"<",
"len",
"(",
"self",
".",
"tokens",
")",
":",
... | https://github.com/youtube/spitfire/blob/1916e68d50ed30f395928585ef2f0d3ba1468ab0/third_party/yapps2/yappsrt.py#L64-L80 | ||
auvsi-suas/interop | ed3d9a7302712e9d4ccb465656bc5336f89906c7 | server/auvsi_suas/models/gps_position.py | python | GpsPositionMixin.distance_to | (self, other) | return distance.distance_to(self.latitude, self.longitude, 0,
other.latitude, other.longitude, 0) | Computes distance to another position.
Args:
other: The other position.
Returns:
Distance in feet. | Computes distance to another position. | [
"Computes",
"distance",
"to",
"another",
"position",
"."
] | def distance_to(self, other):
"""Computes distance to another position.
Args:
other: The other position.
Returns:
Distance in feet.
"""
return distance.distance_to(self.latitude, self.longitude, 0,
other.latitude, other.longitude, 0) | [
"def",
"distance_to",
"(",
"self",
",",
"other",
")",
":",
"return",
"distance",
".",
"distance_to",
"(",
"self",
".",
"latitude",
",",
"self",
".",
"longitude",
",",
"0",
",",
"other",
".",
"latitude",
",",
"other",
".",
"longitude",
",",
"0",
")"
] | https://github.com/auvsi-suas/interop/blob/ed3d9a7302712e9d4ccb465656bc5336f89906c7/server/auvsi_suas/models/gps_position.py#L29-L38 | |
stackimpact/stackimpact-python | 4d0a415b790c89e7bee1d70216f948b7fec11540 | stackimpact/runtime.py | python | read_vm_size | () | return None | [] | def read_vm_size():
pid = os.getpid()
output = None
try:
f = open('/proc/{0}/status'.format(os.getpid()))
output = f.read()
f.close()
except Exception:
return None
match = VM_SIZE_REGEXP.search(output)
if match:
return int(float(match.group(1)))
return None | [
"def",
"read_vm_size",
"(",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"output",
"=",
"None",
"try",
":",
"f",
"=",
"open",
"(",
"'/proc/{0}/status'",
".",
"format",
"(",
"os",
".",
"getpid",
"(",
")",
")",
")",
"output",
"=",
"f",
".",... | https://github.com/stackimpact/stackimpact-python/blob/4d0a415b790c89e7bee1d70216f948b7fec11540/stackimpact/runtime.py#L70-L85 | |||
jorgebastida/gordon | 4c1cd0c4dea2499d98115672095714592f80f7aa | gordon/resources/lambdas.py | python | Lambda._npm_install_extra | (self) | return ' '.join([e for e in extra if e]) | [] | def _npm_install_extra(self):
extra = (
self.project.settings.get('npm-install-extra'),
self.app and self.app.settings.get('npm-install-extra'),
self.settings.get('npm-install-extra'),
)
return ' '.join([e for e in extra if e]) | [
"def",
"_npm_install_extra",
"(",
"self",
")",
":",
"extra",
"=",
"(",
"self",
".",
"project",
".",
"settings",
".",
"get",
"(",
"'npm-install-extra'",
")",
",",
"self",
".",
"app",
"and",
"self",
".",
"app",
".",
"settings",
".",
"get",
"(",
"'npm-ins... | https://github.com/jorgebastida/gordon/blob/4c1cd0c4dea2499d98115672095714592f80f7aa/gordon/resources/lambdas.py#L589-L595 | |||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3db/br.py | python | br_case_root_org | (person_id) | return case_root_org | Get the root organisation managing a case
Args:
person_id: the person record ID
Returns:
root organisation record ID | Get the root organisation managing a case | [
"Get",
"the",
"root",
"organisation",
"managing",
"a",
"case"
] | def br_case_root_org(person_id):
"""
Get the root organisation managing a case
Args:
person_id: the person record ID
Returns:
root organisation record ID
"""
db = current.db
s3db = current.s3db
if person_id:
ctable = s3db.br_case
otable = s3db.org_organisation
left = otable.on(otable.id == ctable.organisation_id)
query = (ctable.person_id == person_id) & \
(ctable.invalid == False) & \
(ctable.deleted == False)
row = db(query).select(otable.root_organisation,
left = left,
limitby = (0, 1),
orderby = ~ctable.modified_on,
).first()
case_root_org = row.root_organisation if row else None
else:
case_root_org = None
return case_root_org | [
"def",
"br_case_root_org",
"(",
"person_id",
")",
":",
"db",
"=",
"current",
".",
"db",
"s3db",
"=",
"current",
".",
"s3db",
"if",
"person_id",
":",
"ctable",
"=",
"s3db",
".",
"br_case",
"otable",
"=",
"s3db",
".",
"org_organisation",
"left",
"=",
"otab... | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3db/br.py#L3670-L3700 | |
seopbo/nlp_classification | 21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf | A_Structured_Self-attentive_Sentence_Embedding_cls/train.py | python | get_tokenizer | (dataset_config, split_fn=split_morphs) | return tokenizer | [] | def get_tokenizer(dataset_config, split_fn=split_morphs):
with open(dataset_config.vocab, mode="rb") as io:
vocab = pickle.load(io)
tokenizer = Tokenizer(vocab=vocab, split_fn=split_fn)
return tokenizer | [
"def",
"get_tokenizer",
"(",
"dataset_config",
",",
"split_fn",
"=",
"split_morphs",
")",
":",
"with",
"open",
"(",
"dataset_config",
".",
"vocab",
",",
"mode",
"=",
"\"rb\"",
")",
"as",
"io",
":",
"vocab",
"=",
"pickle",
".",
"load",
"(",
"io",
")",
"... | https://github.com/seopbo/nlp_classification/blob/21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf/A_Structured_Self-attentive_Sentence_Embedding_cls/train.py#L19-L23 | |||
sqlfluff/sqlfluff | c2278f41f270a29ef5ffc6b179236abf32dc18e1 | src/sqlfluff/core/linter/linter.py | python | Linter.lint_string_wrapped | (
self,
string: str,
fname: str = "<string input>",
fix: bool = False,
) | return result | Lint strings directly. | Lint strings directly. | [
"Lint",
"strings",
"directly",
"."
] | def lint_string_wrapped(
self,
string: str,
fname: str = "<string input>",
fix: bool = False,
) -> LintingResult:
"""Lint strings directly."""
result = LintingResult()
linted_path = LintedDir(fname)
linted_path.add(self.lint_string(string, fname=fname, fix=fix))
result.add(linted_path)
result.stop_timer()
return result | [
"def",
"lint_string_wrapped",
"(",
"self",
",",
"string",
":",
"str",
",",
"fname",
":",
"str",
"=",
"\"<string input>\"",
",",
"fix",
":",
"bool",
"=",
"False",
",",
")",
"->",
"LintingResult",
":",
"result",
"=",
"LintingResult",
"(",
")",
"linted_path",... | https://github.com/sqlfluff/sqlfluff/blob/c2278f41f270a29ef5ffc6b179236abf32dc18e1/src/sqlfluff/core/linter/linter.py#L873-L885 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/ex-submodules/pillowtop/processors/interface.py | python | BulkPillowProcessor.process_changes_chunk | (self, changes_chunk) | Should process given changes_chunk.
Must return a tuple with first element as set of failed changes that
should be reprocessed serially by pillow and second element as a list
of (change, exception) tuples for failed changes that should not be
reprocessed but for which exceptions are to be handled by handle_pillow_error | Should process given changes_chunk. | [
"Should",
"process",
"given",
"changes_chunk",
"."
] | def process_changes_chunk(self, changes_chunk):
"""
Should process given changes_chunk.
Must return a tuple with first element as set of failed changes that
should be reprocessed serially by pillow and second element as a list
of (change, exception) tuples for failed changes that should not be
reprocessed but for which exceptions are to be handled by handle_pillow_error
"""
pass | [
"def",
"process_changes_chunk",
"(",
"self",
",",
"changes_chunk",
")",
":",
"pass"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/ex-submodules/pillowtop/processors/interface.py#L25-L34 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/threading.py | python | Thread._bootstrap | (self) | [] | def _bootstrap(self):
# Wrapper around the real bootstrap code that ignores
# exceptions during interpreter cleanup. Those typically
# happen when a daemon thread wakes up at an unfortunate
# moment, finds the world around it destroyed, and raises some
# random exception *** while trying to report the exception in
# _bootstrap_inner() below ***. Those random exceptions
# don't help anybody, and they confuse users, so we suppress
# them. We suppress them only when it appears that the world
# indeed has already been destroyed, so that exceptions in
# _bootstrap_inner() during normal business hours are properly
# reported. Also, we only suppress them for daemonic threads;
# if a non-daemonic encounters this, something else is wrong.
try:
self._bootstrap_inner()
except:
if self._daemonic and _sys is None:
return
raise | [
"def",
"_bootstrap",
"(",
"self",
")",
":",
"# Wrapper around the real bootstrap code that ignores",
"# exceptions during interpreter cleanup. Those typically",
"# happen when a daemon thread wakes up at an unfortunate",
"# moment, finds the world around it destroyed, and raises some",
"# rando... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/threading.py#L876-L894 | ||||
HymanLiuTS/flaskTs | 286648286976e85d9b9a5873632331efcafe0b21 | flasky/lib/python2.7/site-packages/werkzeug/serving.py | python | WSGIRequestHandler.handle | (self) | return rv | Handles a request ignoring dropped connections. | Handles a request ignoring dropped connections. | [
"Handles",
"a",
"request",
"ignoring",
"dropped",
"connections",
"."
] | def handle(self):
"""Handles a request ignoring dropped connections."""
rv = None
try:
rv = BaseHTTPRequestHandler.handle(self)
except (socket.error, socket.timeout) as e:
self.connection_dropped(e)
except Exception:
if self.server.ssl_context is None or not is_ssl_error():
raise
if self.server.shutdown_signal:
self.initiate_shutdown()
return rv | [
"def",
"handle",
"(",
"self",
")",
":",
"rv",
"=",
"None",
"try",
":",
"rv",
"=",
"BaseHTTPRequestHandler",
".",
"handle",
"(",
"self",
")",
"except",
"(",
"socket",
".",
"error",
",",
"socket",
".",
"timeout",
")",
"as",
"e",
":",
"self",
".",
"co... | https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/werkzeug/serving.py#L212-L224 | |
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/models/v1beta1_policy_rule.py | python | V1beta1PolicyRule.api_groups | (self, api_groups) | Sets the api_groups of this V1beta1PolicyRule.
APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed.
:param api_groups: The api_groups of this V1beta1PolicyRule.
:type: list[str] | Sets the api_groups of this V1beta1PolicyRule.
APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. | [
"Sets",
"the",
"api_groups",
"of",
"this",
"V1beta1PolicyRule",
".",
"APIGroups",
"is",
"the",
"name",
"of",
"the",
"APIGroup",
"that",
"contains",
"the",
"resources",
".",
"If",
"multiple",
"API",
"groups",
"are",
"specified",
"any",
"action",
"requested",
"a... | def api_groups(self, api_groups):
"""
Sets the api_groups of this V1beta1PolicyRule.
APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed.
:param api_groups: The api_groups of this V1beta1PolicyRule.
:type: list[str]
"""
self._api_groups = api_groups | [
"def",
"api_groups",
"(",
"self",
",",
"api_groups",
")",
":",
"self",
".",
"_api_groups",
"=",
"api_groups"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1beta1_policy_rule.py#L67-L76 | ||
aiidateam/aiida-core | c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2 | aiida/orm/implementation/nodes.py | python | BackendNode.clear_attributes | (self) | Delete all attributes. | Delete all attributes. | [
"Delete",
"all",
"attributes",
"."
] | def clear_attributes(self):
"""Delete all attributes.""" | [
"def",
"clear_attributes",
"(",
"self",
")",
":"
] | https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/implementation/nodes.py#L304-L305 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/dnspython-1.15.0/dns/zone.py | python | Zone.replace_rdataset | (self, name, replacement) | Replace an rdataset at name.
It is not an error if there is no rdataset matching I{replacement}.
Ownership of the I{replacement} object is transferred to the zone;
in other words, this method does not store a copy of I{replacement}
at the node, it stores I{replacement} itself.
If the I{name} node does not exist, it is created.
@param name: the owner name
@type name: DNS.name.Name object or string
@param replacement: the replacement rdataset
@type replacement: dns.rdataset.Rdataset | Replace an rdataset at name. | [
"Replace",
"an",
"rdataset",
"at",
"name",
"."
] | def replace_rdataset(self, name, replacement):
"""Replace an rdataset at name.
It is not an error if there is no rdataset matching I{replacement}.
Ownership of the I{replacement} object is transferred to the zone;
in other words, this method does not store a copy of I{replacement}
at the node, it stores I{replacement} itself.
If the I{name} node does not exist, it is created.
@param name: the owner name
@type name: DNS.name.Name object or string
@param replacement: the replacement rdataset
@type replacement: dns.rdataset.Rdataset
"""
if replacement.rdclass != self.rdclass:
raise ValueError('replacement.rdclass != zone.rdclass')
node = self.find_node(name, True)
node.replace_rdataset(replacement) | [
"def",
"replace_rdataset",
"(",
"self",
",",
"name",
",",
"replacement",
")",
":",
"if",
"replacement",
".",
"rdclass",
"!=",
"self",
".",
"rdclass",
":",
"raise",
"ValueError",
"(",
"'replacement.rdclass != zone.rdclass'",
")",
"node",
"=",
"self",
".",
"find... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/dnspython-1.15.0/dns/zone.py#L341-L361 | ||
openworm/owmeta | 4d546107c12ecb12f3d946db7a44b93b80877132 | owmeta/my_neuroml.py | python | NeuroML.generate | (cls, o, t=2) | Get a NeuroML object that represents the given object. The ``type``
determines what content is included in the NeuroML object:
:param o: The object to generate neuroml from
:param t: The what kind of content should be included in the document
- 0=full morphology+biophysics
- 1=cell body only+biophysics
- 2=full morphology only
:returns: A NeuroML object that represents the given object.
:rtype: NeuroMLDocument | Get a NeuroML object that represents the given object. The ``type``
determines what content is included in the NeuroML object: | [
"Get",
"a",
"NeuroML",
"object",
"that",
"represents",
"the",
"given",
"object",
".",
"The",
"type",
"determines",
"what",
"content",
"is",
"included",
"in",
"the",
"NeuroML",
"object",
":"
] | def generate(cls, o, t=2):
"""
Get a NeuroML object that represents the given object. The ``type``
determines what content is included in the NeuroML object:
:param o: The object to generate neuroml from
:param t: The what kind of content should be included in the document
- 0=full morphology+biophysics
- 1=cell body only+biophysics
- 2=full morphology only
:returns: A NeuroML object that represents the given object.
:rtype: NeuroMLDocument
"""
if isinstance(o, Neuron):
# read in the morphology data
d = N.NeuroMLDocument(id=o.name())
c = N.Cell(id=o.name())
c.morphology = o.morphology()
d.cells.append(c)
return d
else:
raise "Not a valid object for conversion to neuroml" | [
"def",
"generate",
"(",
"cls",
",",
"o",
",",
"t",
"=",
"2",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"Neuron",
")",
":",
"# read in the morphology data",
"d",
"=",
"N",
".",
"NeuroMLDocument",
"(",
"id",
"=",
"o",
".",
"name",
"(",
")",
")",
... | https://github.com/openworm/owmeta/blob/4d546107c12ecb12f3d946db7a44b93b80877132/owmeta/my_neuroml.py#L8-L29 | ||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/sql/elements.py | python | outparam | (key, type_=None) | return BindParameter(key, None, type_=type_, unique=False, isoutparam=True) | Create an 'OUT' parameter for usage in functions (stored procedures),
for databases which support them.
The ``outparam`` can be used like a regular function parameter.
The "output" value will be available from the
:class:`~sqlalchemy.engine.ResultProxy` object via its ``out_parameters``
attribute, which returns a dictionary containing the values. | Create an 'OUT' parameter for usage in functions (stored procedures),
for databases which support them. | [
"Create",
"an",
"OUT",
"parameter",
"for",
"usage",
"in",
"functions",
"(",
"stored",
"procedures",
")",
"for",
"databases",
"which",
"support",
"them",
"."
] | def outparam(key, type_=None):
"""Create an 'OUT' parameter for usage in functions (stored procedures),
for databases which support them.
The ``outparam`` can be used like a regular function parameter.
The "output" value will be available from the
:class:`~sqlalchemy.engine.ResultProxy` object via its ``out_parameters``
attribute, which returns a dictionary containing the values.
"""
return BindParameter(key, None, type_=type_, unique=False, isoutparam=True) | [
"def",
"outparam",
"(",
"key",
",",
"type_",
"=",
"None",
")",
":",
"return",
"BindParameter",
"(",
"key",
",",
"None",
",",
"type_",
"=",
"type_",
",",
"unique",
"=",
"False",
",",
"isoutparam",
"=",
"True",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/sql/elements.py#L157-L167 | |
KartikTalwar/Duolingo | 9e552ba4b03be8dff44e1de6e55d7c845d53c897 | duolingo.py | python | Duolingo.get_vocabulary | (self, language_abbr=None) | return overview | Get overview of user's vocabulary in a language. | Get overview of user's vocabulary in a language. | [
"Get",
"overview",
"of",
"user",
"s",
"vocabulary",
"in",
"a",
"language",
"."
] | def get_vocabulary(self, language_abbr=None):
"""Get overview of user's vocabulary in a language."""
if self.username != self._original_username:
raise OtherUserException("Vocab cannot be listed when the user has been switched.")
if language_abbr and not self._is_current_language(language_abbr):
self._switch_language(language_abbr)
overview_url = "https://www.duolingo.com/vocabulary/overview"
overview_request = self._make_req(overview_url)
overview = overview_request.json()
return overview | [
"def",
"get_vocabulary",
"(",
"self",
",",
"language_abbr",
"=",
"None",
")",
":",
"if",
"self",
".",
"username",
"!=",
"self",
".",
"_original_username",
":",
"raise",
"OtherUserException",
"(",
"\"Vocab cannot be listed when the user has been switched.\"",
")",
"if"... | https://github.com/KartikTalwar/Duolingo/blob/9e552ba4b03be8dff44e1de6e55d7c845d53c897/duolingo.py#L539-L551 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/win_dacl.py | python | daclConstants.getObjectTypeBit | (self, t) | returns the bit value of the string object type | returns the bit value of the string object type | [
"returns",
"the",
"bit",
"value",
"of",
"the",
"string",
"object",
"type"
] | def getObjectTypeBit(self, t):
"""
returns the bit value of the string object type
"""
if isinstance(t, str):
t = t.upper()
try:
return self.objectType[t]
except KeyError:
raise CommandExecutionError(
'Invalid object type "{}". It should be one of the following: {}'.format(
t, ", ".join(self.objectType)
)
)
else:
return t | [
"def",
"getObjectTypeBit",
"(",
"self",
",",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"str",
")",
":",
"t",
"=",
"t",
".",
"upper",
"(",
")",
"try",
":",
"return",
"self",
".",
"objectType",
"[",
"t",
"]",
"except",
"KeyError",
":",
"rai... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/win_dacl.py#L205-L220 | ||
simonw/djangopeople.net | ed04d3c79d03b9c74f3e7f82b2af944e021f8e15 | lib/yadis/etxrd.py | python | getCanonicalID | (iname, xrd_tree) | return canonicalID | Return the CanonicalID from this XRDS document.
@param iname: the XRI being resolved.
@type iname: unicode
@param xrd_tree: The XRDS output from the resolver.
@type xrd_tree: ElementTree
@returns: The XRI CanonicalID or None.
@returntype: unicode or None | Return the CanonicalID from this XRDS document. | [
"Return",
"the",
"CanonicalID",
"from",
"this",
"XRDS",
"document",
"."
] | def getCanonicalID(iname, xrd_tree):
"""Return the CanonicalID from this XRDS document.
@param iname: the XRI being resolved.
@type iname: unicode
@param xrd_tree: The XRDS output from the resolver.
@type xrd_tree: ElementTree
@returns: The XRI CanonicalID or None.
@returntype: unicode or None
"""
xrd_list = xrd_tree.findall(xrd_tag)
xrd_list.reverse()
try:
canonicalID = xri.XRI(xrd_list[0].findall(canonicalID_tag)[-1].text)
except IndexError:
return None
childID = canonicalID
for xrd in xrd_list[1:]:
# XXX: can't use rsplit until we require python >= 2.4.
parent_sought = childID[:childID.rindex('!')]
parent_list = [xri.XRI(c.text) for c in xrd.findall(canonicalID_tag)]
if parent_sought not in parent_list:
raise XRDSFraud("%r can not come from any of %s" % (parent_sought,
parent_list))
childID = parent_sought
root = xri.rootAuthority(iname)
if not xri.providerIsAuthoritative(root, childID):
raise XRDSFraud("%r can not come from root %r" % (childID, root))
return canonicalID | [
"def",
"getCanonicalID",
"(",
"iname",
",",
"xrd_tree",
")",
":",
"xrd_list",
"=",
"xrd_tree",
".",
"findall",
"(",
"xrd_tag",
")",
"xrd_list",
".",
"reverse",
"(",
")",
"try",
":",
"canonicalID",
"=",
"xri",
".",
"XRI",
"(",
"xrd_list",
"[",
"0",
"]",... | https://github.com/simonw/djangopeople.net/blob/ed04d3c79d03b9c74f3e7f82b2af944e021f8e15/lib/yadis/etxrd.py#L121-L157 | |
mfrister/pushproxy | 55f9386420986ba3cf61b61a9f5a78f73e5a82f2 | src/icl0ud/push/intercept.py | python | InterceptClientFactory.__init__ | (self, deviceProtocol) | [] | def __init__(self, deviceProtocol):
self.deviceProtocol = deviceProtocol | [
"def",
"__init__",
"(",
"self",
",",
"deviceProtocol",
")",
":",
"self",
".",
"deviceProtocol",
"=",
"deviceProtocol"
] | https://github.com/mfrister/pushproxy/blob/55f9386420986ba3cf61b61a9f5a78f73e5a82f2/src/icl0ud/push/intercept.py#L70-L71 | ||||
gpodder/mygpo | 7a028ad621d05d4ca0d58fd22fb92656c8835e43 | mygpo/api/simple.py | python | check_format | (fn) | return tmp | [] | def check_format(fn):
@wraps(fn)
def tmp(request, format, *args, **kwargs):
if format not in ALLOWED_FORMATS:
return HttpResponseBadRequest("Invalid format")
return fn(request, *args, format=format, **kwargs)
return tmp | [
"def",
"check_format",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"tmp",
"(",
"request",
",",
"format",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"format",
"not",
"in",
"ALLOWED_FORMATS",
":",
"return",
"HttpResponseBa... | https://github.com/gpodder/mygpo/blob/7a028ad621d05d4ca0d58fd22fb92656c8835e43/mygpo/api/simple.py#L35-L43 | |||
livid/v2ex-gae | 32be3a77d535e7c9df85a333e01ab8834d0e8581 | v2ex/babel/ext/cookies.py | python | Cookies.unset_cookie | (self, key) | Unset a cookie with the given name (remove it from the
response). If there are multiple cookies (e.g., two cookies
with the same name and different paths or domains), all such
cookies will be deleted. | Unset a cookie with the given name (remove it from the
response). If there are multiple cookies (e.g., two cookies
with the same name and different paths or domains), all such
cookies will be deleted. | [
"Unset",
"a",
"cookie",
"with",
"the",
"given",
"name",
"(",
"remove",
"it",
"from",
"the",
"response",
")",
".",
"If",
"there",
"are",
"multiple",
"cookies",
"(",
"e",
".",
"g",
".",
"two",
"cookies",
"with",
"the",
"same",
"name",
"and",
"different",... | def unset_cookie(self, key):
"""
Unset a cookie with the given name (remove it from the
response). If there are multiple cookies (e.g., two cookies
with the same name and different paths or domains), all such
cookies will be deleted.
"""
existing = self.response.headers.get_all('Set-Cookie')
if not existing:
raise KeyError(
"No cookies at all have been set")
del self.response.headers['Set-Cookie']
found = False
for header in existing:
cookies = BaseCookie()
cookies.load(header)
if key in cookies:
found = True
del cookies[key]
header = cookies.output(header='').lstrip()
if header:
self.response.headers.add('Set-Cookie', header)
if not found:
raise KeyError(
"No cookie has been set with the name %r" % key) | [
"def",
"unset_cookie",
"(",
"self",
",",
"key",
")",
":",
"existing",
"=",
"self",
".",
"response",
".",
"headers",
".",
"get_all",
"(",
"'Set-Cookie'",
")",
"if",
"not",
"existing",
":",
"raise",
"KeyError",
"(",
"\"No cookies at all have been set\"",
")",
... | https://github.com/livid/v2ex-gae/blob/32be3a77d535e7c9df85a333e01ab8834d0e8581/v2ex/babel/ext/cookies.py#L67-L91 | ||
indico/indico | 1579ea16235bbe5f22a308b79c5902c85374721f | indico/util/i18n.py | python | get_all_locales | () | List all available locales/names e.g. ``{'pt_PT': ('Portuguese', 'Portugal)}``. | List all available locales/names e.g. ``{'pt_PT': ('Portuguese', 'Portugal)}``. | [
"List",
"all",
"available",
"locales",
"/",
"names",
"e",
".",
"g",
".",
"{",
"pt_PT",
":",
"(",
"Portuguese",
"Portugal",
")",
"}",
"."
] | def get_all_locales():
"""
List all available locales/names e.g. ``{'pt_PT': ('Portuguese', 'Portugal)}``.
"""
if babel.app is None:
return {}
else:
missing = object()
languages = {str(t): config.CUSTOM_LANGUAGES.get(str(t), (t.language_name.title(), t.territory_name))
for t in babel.list_translations()
if config.CUSTOM_LANGUAGES.get(str(t), missing) is not None}
counts = Counter(x[0] for x in languages.values())
return {code: (name, territory, counts[name] > 1) for code, (name, territory) in languages.items()} | [
"def",
"get_all_locales",
"(",
")",
":",
"if",
"babel",
".",
"app",
"is",
"None",
":",
"return",
"{",
"}",
"else",
":",
"missing",
"=",
"object",
"(",
")",
"languages",
"=",
"{",
"str",
"(",
"t",
")",
":",
"config",
".",
"CUSTOM_LANGUAGES",
".",
"g... | https://github.com/indico/indico/blob/1579ea16235bbe5f22a308b79c5902c85374721f/indico/util/i18n.py#L263-L275 | ||
cloudera/impyla | 0c736af4cad2bade9b8e313badc08ec50e81c948 | impala/_thrift_gen/TCLIService/ttypes.py | python | TTypeQualifiers.__eq__ | (self, other) | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ | [] | def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
"and",
"self",
".",
"__dict__",
"==",
"other",
".",
"__dict__"
] | https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/TCLIService/ttypes.py#L516-L517 | |||
cobbler/cobbler | eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc | cobbler/modules/managers/import_signatures.py | python | _ImportSignatureManager.yum_repo_scanner | (self, distro: distro.Distro, dirname: str, fnames) | This is an import_walker routine that looks for potential yum repositories to be added to the configuration for
post-install usage.
:param distro: The distribution object to check for.
:param dirname: The folder with repositories to check.
:param fnames: Unkown what this does exactly. | This is an import_walker routine that looks for potential yum repositories to be added to the configuration for
post-install usage. | [
"This",
"is",
"an",
"import_walker",
"routine",
"that",
"looks",
"for",
"potential",
"yum",
"repositories",
"to",
"be",
"added",
"to",
"the",
"configuration",
"for",
"post",
"-",
"install",
"usage",
"."
] | def yum_repo_scanner(self, distro: distro.Distro, dirname: str, fnames):
"""
This is an import_walker routine that looks for potential yum repositories to be added to the configuration for
post-install usage.
:param distro: The distribution object to check for.
:param dirname: The folder with repositories to check.
:param fnames: Unkown what this does exactly.
"""
matches = {}
for x in fnames:
if x == "base" or x == "repodata":
self.logger.info("processing repo at : %s" % dirname)
# only run the repo scanner on directories that contain a comps.xml
gloob1 = glob.glob("%s/%s/*comps*.xml" % (dirname, x))
if len(gloob1) >= 1:
if dirname in matches:
self.logger.info("looks like we've already scanned here: %s" % dirname)
continue
self.logger.info("need to process repo/comps: %s" % dirname)
self.yum_process_comps_file(dirname, distro)
matches[dirname] = 1
else:
self.logger.info("directory %s is missing xml comps file, skipping" % dirname)
continue | [
"def",
"yum_repo_scanner",
"(",
"self",
",",
"distro",
":",
"distro",
".",
"Distro",
",",
"dirname",
":",
"str",
",",
"fnames",
")",
":",
"matches",
"=",
"{",
"}",
"for",
"x",
"in",
"fnames",
":",
"if",
"x",
"==",
"\"base\"",
"or",
"x",
"==",
"\"re... | https://github.com/cobbler/cobbler/blob/eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc/cobbler/modules/managers/import_signatures.py#L689-L714 | ||
conda/conda-build | 2a19925f2b2ca188f80ffa625cd783e7d403793f | conda_build/source.py | python | hg_source | (source_dict, src_dir, hg_cache, verbose) | return src_dir | Download a source from Mercurial repo. | Download a source from Mercurial repo. | [
"Download",
"a",
"source",
"from",
"Mercurial",
"repo",
"."
] | def hg_source(source_dict, src_dir, hg_cache, verbose):
''' Download a source from Mercurial repo. '''
if verbose:
stdout = None
stderr = None
else:
FNULL = open(os.devnull, 'wb')
stdout = FNULL
stderr = FNULL
hg_url = source_dict['hg_url']
if not isdir(hg_cache):
os.makedirs(hg_cache)
hg_dn = hg_url.split(':')[-1].replace('/', '_')
cache_repo = join(hg_cache, hg_dn)
if isdir(cache_repo):
check_call_env(['hg', 'pull'], cwd=cache_repo, stdout=stdout, stderr=stderr)
else:
check_call_env(['hg', 'clone', hg_url, cache_repo], stdout=stdout, stderr=stderr)
assert isdir(cache_repo)
# now clone in to work directory
update = source_dict.get('hg_tag') or 'tip'
if verbose:
print('checkout: %r' % update)
check_call_env(['hg', 'clone', cache_repo, src_dir], stdout=stdout,
stderr=stderr)
check_call_env(['hg', 'update', '-C', update], cwd=src_dir, stdout=stdout,
stderr=stderr)
if not verbose:
FNULL.close()
return src_dir | [
"def",
"hg_source",
"(",
"source_dict",
",",
"src_dir",
",",
"hg_cache",
",",
"verbose",
")",
":",
"if",
"verbose",
":",
"stdout",
"=",
"None",
"stderr",
"=",
"None",
"else",
":",
"FNULL",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'wb'",
")",
"st... | https://github.com/conda/conda-build/blob/2a19925f2b2ca188f80ffa625cd783e7d403793f/conda_build/source.py#L381-L415 | |
zbyte64/django-hyperadmin | 9ac2ae284b76efb3c50a1c2899f383a27154cb54 | hyperadmin/endpoints.py | python | VirtualEndpoint.get_extra_urls | (self) | return patterns('',) | [] | def get_extra_urls(self):
return patterns('',) | [
"def",
"get_extra_urls",
"(",
"self",
")",
":",
"return",
"patterns",
"(",
"''",
",",
")"
] | https://github.com/zbyte64/django-hyperadmin/blob/9ac2ae284b76efb3c50a1c2899f383a27154cb54/hyperadmin/endpoints.py#L487-L488 | |||
brython-dev/brython | 9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3 | www/src/Lib/_pydecimal.py | python | Decimal.logical_or | (self, other, context=None) | return _dec_from_triple(0, result.lstrip('0') or '0', 0) | Applies an 'or' operation between self and other's digits. | Applies an 'or' operation between self and other's digits. | [
"Applies",
"an",
"or",
"operation",
"between",
"self",
"and",
"other",
"s",
"digits",
"."
] | def logical_or(self, other, context=None):
"""Applies an 'or' operation between self and other's digits."""
if context is None:
context = getcontext()
other = _convert_other(other, raiseit=True)
if not self._islogical() or not other._islogical():
return context._raise_error(InvalidOperation)
# fill to context.prec
(opa, opb) = self._fill_logical(context, self._int, other._int)
# make the operation, and clean starting zeroes
result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
return _dec_from_triple(0, result.lstrip('0') or '0', 0) | [
"def",
"logical_or",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"other",
"=",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"True",
")",
"if",
"... | https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/_pydecimal.py#L3404-L3419 | |
out0fmemory/GoAgent-Always-Available | c4254984fea633ce3d1893fe5901debd9f22c2a9 | server/lib/google/appengine/datastore/datastore_rpc.py | python | BaseConnection._extract_entity_group | (self, value) | return (kind, elem_id or elem_name or ('new', id(elem))) | Internal helper: extracts the entity group from a key or entity.
Supports both v3 and v1 protobufs.
Args:
value: an entity_pb.{Reference, EntityProto} or
googledatastore.{Key, Entity}.
Returns:
A tuple consisting of:
- kind
- name, id, or ('new', unique id) | Internal helper: extracts the entity group from a key or entity. | [
"Internal",
"helper",
":",
"extracts",
"the",
"entity",
"group",
"from",
"a",
"key",
"or",
"entity",
"."
] | def _extract_entity_group(self, value):
"""Internal helper: extracts the entity group from a key or entity.
Supports both v3 and v1 protobufs.
Args:
value: an entity_pb.{Reference, EntityProto} or
googledatastore.{Key, Entity}.
Returns:
A tuple consisting of:
- kind
- name, id, or ('new', unique id)
"""
if _CLOUD_DATASTORE_ENABLED and isinstance(value, googledatastore.Entity):
value = value.key
if isinstance(value, entity_pb.EntityProto):
value = value.key()
if _CLOUD_DATASTORE_ENABLED and isinstance(value, googledatastore.Key):
elem = value.path[0]
elem_id = elem.id
elem_name = elem.name
kind = elem.kind
else:
elem = value.path().element(0)
kind = elem.type()
elem_id = elem.id()
elem_name = elem.name()
return (kind, elem_id or elem_name or ('new', id(elem))) | [
"def",
"_extract_entity_group",
"(",
"self",
",",
"value",
")",
":",
"if",
"_CLOUD_DATASTORE_ENABLED",
"and",
"isinstance",
"(",
"value",
",",
"googledatastore",
".",
"Entity",
")",
":",
"value",
"=",
"value",
".",
"key",
"if",
"isinstance",
"(",
"value",
",... | https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/datastore/datastore_rpc.py#L1396-L1426 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/messaging/whatsapputil.py | python | is_multimedia_message | (msg) | return 'caption_image' in msg.custom_metadata\
or 'caption_audio' in msg.custom_metadata\
or 'caption_video' in msg.custom_metadata | [] | def is_multimedia_message(msg):
return 'caption_image' in msg.custom_metadata\
or 'caption_audio' in msg.custom_metadata\
or 'caption_video' in msg.custom_metadata | [
"def",
"is_multimedia_message",
"(",
"msg",
")",
":",
"return",
"'caption_image'",
"in",
"msg",
".",
"custom_metadata",
"or",
"'caption_audio'",
"in",
"msg",
".",
"custom_metadata",
"or",
"'caption_video'",
"in",
"msg",
".",
"custom_metadata"
] | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/messaging/whatsapputil.py#L17-L20 | |||
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | squid/datadog_checks/squid/config_models/shared.py | python | SharedConfig._initial_validation | (cls, values) | return validation.core.initialize_config(getattr(validators, 'initialize_shared', identity)(values)) | [] | def _initial_validation(cls, values):
return validation.core.initialize_config(getattr(validators, 'initialize_shared', identity)(values)) | [
"def",
"_initial_validation",
"(",
"cls",
",",
"values",
")",
":",
"return",
"validation",
".",
"core",
".",
"initialize_config",
"(",
"getattr",
"(",
"validators",
",",
"'initialize_shared'",
",",
"identity",
")",
"(",
"values",
")",
")"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/squid/datadog_checks/squid/config_models/shared.py#L41-L42 | |||
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/httplib2/__init__.py | python | _wsse_username_token | (cnonce, iso_now, password) | return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip() | [] | def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip() | [
"def",
"_wsse_username_token",
"(",
"cnonce",
",",
"iso_now",
",",
"password",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"_sha",
"(",
"\"%s%s%s\"",
"%",
"(",
"cnonce",
",",
"iso_now",
",",
"password",
")",
")",
".",
"digest",
"(",
")",
")",
... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/httplib2/__init__.py#L407-L408 | |||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/iecp/v20210914/models.py | python | DescribeEdgeUnitCloudResponse.__init__ | (self) | r"""
:param Name: 边缘集群名称
:type Name: str
:param Description: 描述
注意:此字段可能返回 null,表示取不到有效值。
:type Description: str
:param CreateTime: 创建时间
注意:此字段可能返回 null,表示取不到有效值。
:type CreateTime: str
:param UpdateTime: 更新时间
注意:此字段可能返回 null,表示取不到有效值。
:type UpdateTime: str
:param LiveTime: 集群最后探活时间
注意:此字段可能返回 null,表示取不到有效值。
:type LiveTime: str
:param MasterStatus: 集群状态
注意:此字段可能返回 null,表示取不到有效值。
:type MasterStatus: str
:param K8sVersion: 版本号
注意:此字段可能返回 null,表示取不到有效值。
:type K8sVersion: str
:param PodCIDR: pod cidr
注意:此字段可能返回 null,表示取不到有效值。
:type PodCIDR: str
:param ServiceCIDR: service cidr
注意:此字段可能返回 null,表示取不到有效值。
:type ServiceCIDR: str
:param APIServerAddress: 集群内网访问地址
注意:此字段可能返回 null,表示取不到有效值。
:type APIServerAddress: str
:param APIServerExposeAddress: 集群外网访问地址
注意:此字段可能返回 null,表示取不到有效值。
:type APIServerExposeAddress: str
:param UID: 用户ID
注意:此字段可能返回 null,表示取不到有效值。
:type UID: str
:param UnitID: 集群ID
注意:此字段可能返回 null,表示取不到有效值。
:type UnitID: int
:param Cluster: 集群标识
注意:此字段可能返回 null,表示取不到有效值。
:type Cluster: str
:param Node: 节点统计
注意:此字段可能返回 null,表示取不到有效值。
:type Node: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param Workload: 工作负载统计
注意:此字段可能返回 null,表示取不到有效值。
:type Workload: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param Grid: Grid应用统计
注意:此字段可能返回 null,表示取不到有效值。
:type Grid: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param SubDevice: 设备统计
注意:此字段可能返回 null,表示取不到有效值。
:type SubDevice: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | r"""
:param Name: 边缘集群名称
:type Name: str
:param Description: 描述
注意:此字段可能返回 null,表示取不到有效值。
:type Description: str
:param CreateTime: 创建时间
注意:此字段可能返回 null,表示取不到有效值。
:type CreateTime: str
:param UpdateTime: 更新时间
注意:此字段可能返回 null,表示取不到有效值。
:type UpdateTime: str
:param LiveTime: 集群最后探活时间
注意:此字段可能返回 null,表示取不到有效值。
:type LiveTime: str
:param MasterStatus: 集群状态
注意:此字段可能返回 null,表示取不到有效值。
:type MasterStatus: str
:param K8sVersion: 版本号
注意:此字段可能返回 null,表示取不到有效值。
:type K8sVersion: str
:param PodCIDR: pod cidr
注意:此字段可能返回 null,表示取不到有效值。
:type PodCIDR: str
:param ServiceCIDR: service cidr
注意:此字段可能返回 null,表示取不到有效值。
:type ServiceCIDR: str
:param APIServerAddress: 集群内网访问地址
注意:此字段可能返回 null,表示取不到有效值。
:type APIServerAddress: str
:param APIServerExposeAddress: 集群外网访问地址
注意:此字段可能返回 null,表示取不到有效值。
:type APIServerExposeAddress: str
:param UID: 用户ID
注意:此字段可能返回 null,表示取不到有效值。
:type UID: str
:param UnitID: 集群ID
注意:此字段可能返回 null,表示取不到有效值。
:type UnitID: int
:param Cluster: 集群标识
注意:此字段可能返回 null,表示取不到有效值。
:type Cluster: str
:param Node: 节点统计
注意:此字段可能返回 null,表示取不到有效值。
:type Node: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param Workload: 工作负载统计
注意:此字段可能返回 null,表示取不到有效值。
:type Workload: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param Grid: Grid应用统计
注意:此字段可能返回 null,表示取不到有效值。
:type Grid: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param SubDevice: 设备统计
注意:此字段可能返回 null,表示取不到有效值。
:type SubDevice: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | [
"r",
":",
"param",
"Name",
":",
"边缘集群名称",
":",
"type",
"Name",
":",
"str",
":",
"param",
"Description",
":",
"描述",
"注意:此字段可能返回",
"null,表示取不到有效值。",
":",
"type",
"Description",
":",
"str",
":",
"param",
"CreateTime",
":",
"创建时间",
"注意:此字段可能返回",
"null,表示取不到有效值。"... | def __init__(self):
r"""
:param Name: 边缘集群名称
:type Name: str
:param Description: 描述
注意:此字段可能返回 null,表示取不到有效值。
:type Description: str
:param CreateTime: 创建时间
注意:此字段可能返回 null,表示取不到有效值。
:type CreateTime: str
:param UpdateTime: 更新时间
注意:此字段可能返回 null,表示取不到有效值。
:type UpdateTime: str
:param LiveTime: 集群最后探活时间
注意:此字段可能返回 null,表示取不到有效值。
:type LiveTime: str
:param MasterStatus: 集群状态
注意:此字段可能返回 null,表示取不到有效值。
:type MasterStatus: str
:param K8sVersion: 版本号
注意:此字段可能返回 null,表示取不到有效值。
:type K8sVersion: str
:param PodCIDR: pod cidr
注意:此字段可能返回 null,表示取不到有效值。
:type PodCIDR: str
:param ServiceCIDR: service cidr
注意:此字段可能返回 null,表示取不到有效值。
:type ServiceCIDR: str
:param APIServerAddress: 集群内网访问地址
注意:此字段可能返回 null,表示取不到有效值。
:type APIServerAddress: str
:param APIServerExposeAddress: 集群外网访问地址
注意:此字段可能返回 null,表示取不到有效值。
:type APIServerExposeAddress: str
:param UID: 用户ID
注意:此字段可能返回 null,表示取不到有效值。
:type UID: str
:param UnitID: 集群ID
注意:此字段可能返回 null,表示取不到有效值。
:type UnitID: int
:param Cluster: 集群标识
注意:此字段可能返回 null,表示取不到有效值。
:type Cluster: str
:param Node: 节点统计
注意:此字段可能返回 null,表示取不到有效值。
:type Node: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param Workload: 工作负载统计
注意:此字段可能返回 null,表示取不到有效值。
:type Workload: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param Grid: Grid应用统计
注意:此字段可能返回 null,表示取不到有效值。
:type Grid: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param SubDevice: 设备统计
注意:此字段可能返回 null,表示取不到有效值。
:type SubDevice: :class:`tencentcloud.iecp.v20210914.models.EdgeUnitStatisticItem`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Name = None
self.Description = None
self.CreateTime = None
self.UpdateTime = None
self.LiveTime = None
self.MasterStatus = None
self.K8sVersion = None
self.PodCIDR = None
self.ServiceCIDR = None
self.APIServerAddress = None
self.APIServerExposeAddress = None
self.UID = None
self.UnitID = None
self.Cluster = None
self.Node = None
self.Workload = None
self.Grid = None
self.SubDevice = None
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"Name",
"=",
"None",
"self",
".",
"Description",
"=",
"None",
"self",
".",
"CreateTime",
"=",
"None",
"self",
".",
"UpdateTime",
"=",
"None",
"self",
".",
"LiveTime",
"=",
"None",
"self",
".",
"M... | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iecp/v20210914/models.py#L3492-L3568 | ||
suragnair/alpha-zero-general | 018f65ee1ef56b87c8a9049353d4130946d03a9a | rts/src/Board.py | python | Board.time_killer | (self, player) | Additional function that can be used to stop players from looping in game. It is defined using _damage and _num_destroys functions, which define how much and how many actors should be damaged each round.
This prevents players playing games too long, as its starting to kill them. Better players should gather more gold and therefore create more advanced actors prolonging their lives.
:param player: which player is currently executing action
:return: / | Additional function that can be used to stop players from looping in game. It is defined using _damage and _num_destroys functions, which define how much and how many actors should be damaged each round.
This prevents players playing games too long, as its starting to kill them. Better players should gather more gold and therefore create more advanced actors prolonging their lives.
:param player: which player is currently executing action
:return: / | [
"Additional",
"function",
"that",
"can",
"be",
"used",
"to",
"stop",
"players",
"from",
"looping",
"in",
"game",
".",
"It",
"is",
"defined",
"using",
"_damage",
"and",
"_num_destroys",
"functions",
"which",
"define",
"how",
"much",
"and",
"how",
"many",
"act... | def time_killer(self, player):
"""
Additional function that can be used to stop players from looping in game. It is defined using _damage and _num_destroys functions, which define how much and how many actors should be damaged each round.
This prevents players playing games too long, as its starting to kill them. Better players should gather more gold and therefore create more advanced actors prolonging their lives.
:param player: which player is currently executing action
:return: /
"""
# I can pass player through, because this board is canonical board that this action gets executed upon
current_time = self[0][0][TIME_IDX]
destroys_per_round = self._num_destroys(current_time)
damage_amount = self._damage(current_time)
# Damage as many actors as "damage_amount" parameter provides
currently_damaged_actors = 0
for y in range(self.n):
for x in range(self.n):
if self[x][y][P_NAME_IDX] == player and self[x][y][A_TYPE_IDX] != 1: # for current player and not gold
if currently_damaged_actors >= destroys_per_round:
return
self[x][y][HEALTH_IDX] -= damage_amount
if self[x][y][HEALTH_IDX] <= 0:
time = self[x][y][TIME_IDX]
self[x][y] = [0] * NUM_ENCODERS
self[x][y][TIME_IDX] = time
currently_damaged_actors += 1 | [
"def",
"time_killer",
"(",
"self",
",",
"player",
")",
":",
"# I can pass player through, because this board is canonical board that this action gets executed upon",
"current_time",
"=",
"self",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"TIME_IDX",
"]",
"destroys_per_round",
"="... | https://github.com/suragnair/alpha-zero-general/blob/018f65ee1ef56b87c8a9049353d4130946d03a9a/rts/src/Board.py#L416-L443 | ||
mongodb/mongo-python-driver | c760f900f2e4109a247c2ffc8ad3549362007772 | pymongo/monitoring.py | python | ConnectionPoolListener.connection_checked_out | (self, event) | Abstract method to handle a :class:`ConnectionCheckedOutEvent`.
Emitted when the driver successfully checks out a Connection.
:Parameters:
- `event`: An instance of :class:`ConnectionCheckedOutEvent`. | Abstract method to handle a :class:`ConnectionCheckedOutEvent`. | [
"Abstract",
"method",
"to",
"handle",
"a",
":",
"class",
":",
"ConnectionCheckedOutEvent",
"."
] | def connection_checked_out(self, event):
"""Abstract method to handle a :class:`ConnectionCheckedOutEvent`.
Emitted when the driver successfully checks out a Connection.
:Parameters:
- `event`: An instance of :class:`ConnectionCheckedOutEvent`.
"""
raise NotImplementedError | [
"def",
"connection_checked_out",
"(",
"self",
",",
"event",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/mongodb/mongo-python-driver/blob/c760f900f2e4109a247c2ffc8ad3549362007772/pymongo/monitoring.py#L341-L349 | ||
tensorforce/tensorforce | 085a62bd37e0fdfd05691db29edeb2e1714ffbda | tensorforce/environments/environment.py | python | Environment.num_actors | (self) | return 1 | Returns the number of actors in this environment.
Returns:
int >= 1: The number of actors. | Returns the number of actors in this environment. | [
"Returns",
"the",
"number",
"of",
"actors",
"in",
"this",
"environment",
"."
] | def num_actors(self):
"""
Returns the number of actors in this environment.
Returns:
int >= 1: The number of actors.
"""
return 1 | [
"def",
"num_actors",
"(",
"self",
")",
":",
"return",
"1"
] | https://github.com/tensorforce/tensorforce/blob/085a62bd37e0fdfd05691db29edeb2e1714ffbda/tensorforce/environments/environment.py#L319-L326 | |
inferno-pytorch/inferno | 789c6d00b34cf9e9d119a8dfc6b6f9d2c334d7e8 | inferno/extensions/containers/graph.py | python | Graph.to_device | (self, names, target_device, device_ordinal=None, asynchronous=False) | return self | Transfer nodes in the network to a specified device. | Transfer nodes in the network to a specified device. | [
"Transfer",
"nodes",
"in",
"the",
"network",
"to",
"a",
"specified",
"device",
"."
] | def to_device(self, names, target_device, device_ordinal=None, asynchronous=False):
"""Transfer nodes in the network to a specified device."""
names = pyu.to_iterable(names)
for name in names:
assert self.is_node_in_graph(name), "Node '{}' is not in graph.".format(name)
module = getattr(self, name, None)
assert module is not None, "Node '{}' is in the graph but could not find a module " \
"corresponding to it.".format(name)
# Transfer
module_on_device = OnDevice(module, target_device,
device_ordinal=device_ordinal,
asynchronous=asynchronous)
setattr(self, name, module_on_device)
return self | [
"def",
"to_device",
"(",
"self",
",",
"names",
",",
"target_device",
",",
"device_ordinal",
"=",
"None",
",",
"asynchronous",
"=",
"False",
")",
":",
"names",
"=",
"pyu",
".",
"to_iterable",
"(",
"names",
")",
"for",
"name",
"in",
"names",
":",
"assert",... | https://github.com/inferno-pytorch/inferno/blob/789c6d00b34cf9e9d119a8dfc6b6f9d2c334d7e8/inferno/extensions/containers/graph.py#L358-L371 | |
ynhacler/RedKindle | 7c970920dc840f869e38cbda480d630cc2e7b200 | cssutils/script.py | python | csscombine | (path=None, url=None, cssText=None, href=None,
sourceencoding=None, targetencoding=None,
minify=True, resolveVariables=True) | return cssText | Combine sheets referred to by @import rules in given CSS proxy sheet
into a single new sheet.
:returns: combined cssText, normal or minified
:Parameters:
`path` or `url` or `cssText` + `href`
path or URL to a CSSStyleSheet or a cssText of a sheet which imports
other sheets which are then combined into one sheet.
`cssText` normally needs `href` to be able to resolve relative
imports.
`sourceencoding` = 'utf-8'
explicit encoding of the source proxysheet
`targetencoding`
encoding of the combined stylesheet
`minify` = True
defines if the combined sheet should be minified, in this case
comments are not parsed at all!
`resolveVariables` = True
defines if variables in combined sheet should be resolved | Combine sheets referred to by @import rules in given CSS proxy sheet
into a single new sheet. | [
"Combine",
"sheets",
"referred",
"to",
"by",
"@import",
"rules",
"in",
"given",
"CSS",
"proxy",
"sheet",
"into",
"a",
"single",
"new",
"sheet",
"."
] | def csscombine(path=None, url=None, cssText=None, href=None,
sourceencoding=None, targetencoding=None,
minify=True, resolveVariables=True):
"""Combine sheets referred to by @import rules in given CSS proxy sheet
into a single new sheet.
:returns: combined cssText, normal or minified
:Parameters:
`path` or `url` or `cssText` + `href`
path or URL to a CSSStyleSheet or a cssText of a sheet which imports
other sheets which are then combined into one sheet.
`cssText` normally needs `href` to be able to resolve relative
imports.
`sourceencoding` = 'utf-8'
explicit encoding of the source proxysheet
`targetencoding`
encoding of the combined stylesheet
`minify` = True
defines if the combined sheet should be minified, in this case
comments are not parsed at all!
`resolveVariables` = True
defines if variables in combined sheet should be resolved
"""
cssutils.log.info(u'Combining files from %r' % url,
neverraise=True)
if sourceencoding is not None:
cssutils.log.info(u'Using source encoding %r' % sourceencoding,
neverraise=True)
parser = cssutils.CSSParser(parseComments=not minify)
if path and not cssText:
src = parser.parseFile(path, encoding=sourceencoding)
elif url:
src = parser.parseUrl(url, encoding=sourceencoding)
elif cssText:
src = parser.parseString(cssText, href=href, encoding=sourceencoding)
else:
sys.exit('Path or URL must be given')
result = cssutils.resolveImports(src)
result.encoding = targetencoding
cssutils.log.info(u'Using target encoding: %r' % targetencoding, neverraise=True)
oldser = cssutils.ser
cssutils.setSerializer(cssutils.serialize.CSSSerializer())
if minify:
cssutils.ser.prefs.useMinified()
cssutils.ser.prefs.resolveVariables = resolveVariables
cssText = result.cssText
cssutils.setSerializer(oldser)
return cssText | [
"def",
"csscombine",
"(",
"path",
"=",
"None",
",",
"url",
"=",
"None",
",",
"cssText",
"=",
"None",
",",
"href",
"=",
"None",
",",
"sourceencoding",
"=",
"None",
",",
"targetencoding",
"=",
"None",
",",
"minify",
"=",
"True",
",",
"resolveVariables",
... | https://github.com/ynhacler/RedKindle/blob/7c970920dc840f869e38cbda480d630cc2e7b200/cssutils/script.py#L310-L362 | |
Pymol-Scripts/Pymol-script-repo | bcd7bb7812dc6db1595953dfa4471fa15fb68c77 | modules/pdb2pqr/main_cgi.py | python | WebOptions.getLoggingList | (self) | return results | Returns a list of options the user has turned on.
Used for logging jobs later in usage.txt | Returns a list of options the user has turned on.
Used for logging jobs later in usage.txt | [
"Returns",
"a",
"list",
"of",
"options",
"the",
"user",
"has",
"turned",
"on",
".",
"Used",
"for",
"logging",
"jobs",
"later",
"in",
"usage",
".",
"txt"
] | def getLoggingList(self):
'''Returns a list of options the user has turned on.
Used for logging jobs later in usage.txt'''
results = []
for key in self:
if self[key]:
results.append(key)
return results | [
"def",
"getLoggingList",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
":",
"if",
"self",
"[",
"key",
"]",
":",
"results",
".",
"append",
"(",
"key",
")",
"return",
"results"
] | https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/main_cgi.py#L219-L228 | |
NeuralEnsemble/python-neo | 34d4db8fb0dc950dbbc6defd7fb75e99ea877286 | neo/rawio/spikeglxrawio.py | python | scan_files | (dirname) | return info_list | Scan for pairs of `.bin` and `.meta` files and return information about it. | Scan for pairs of `.bin` and `.meta` files and return information about it. | [
"Scan",
"for",
"pairs",
"of",
".",
"bin",
"and",
".",
"meta",
"files",
"and",
"return",
"information",
"about",
"it",
"."
] | def scan_files(dirname):
"""
Scan for pairs of `.bin` and `.meta` files and return information about it.
"""
info_list = []
for root, dirs, files in os.walk(dirname):
for file in files:
if not file.endswith('.meta'):
continue
meta_filename = Path(root) / file
bin_filename = Path(root) / file.replace('.meta', '.bin')
if meta_filename.exists() and bin_filename.exists():
meta = read_meta_file(meta_filename)
else:
continue
num_chan = int(meta['nSavedChans'])
# Example file name structure:
# Consider the filenames: `Noise4Sam_g0_t0.nidq.bin` or `Noise4Sam_g0_t0.imec0.lf.bin`
# The filenames consist of 3 or 4 parts separated by `.`
# * "Noise4Sam_g0_t0" will be the `name` variable. This choosen by the user
# at recording time.
# * "_gt0_" will give the `seg_index` (here 0)
# * "nidq" or "imec0" will give the `device` variable
# * "lf" or "ap" will be the `signal_kind` variable
# `stream_name` variable is the concatenation of `device.signal_kind`
name = file.split('.')[0]
r = re.findall(r'_g(\d*)_t', name)
seg_index = int(r[0][0])
device = file.split('.')[1]
if 'imec' in device:
signal_kind = file.split('.')[2]
stream_name = device + '.' + signal_kind
units = 'uV'
# please note the 1e6 in gain for this uV
# metad['imroTbl'] contain two gain per channel AP and LF
# except for the last fake channel
per_channel_gain = np.ones(num_chan, dtype='float64')
if signal_kind == 'ap':
index_imroTbl = 3
elif signal_kind == 'lf':
index_imroTbl = 4
# the last channel doesn't have a gain value
for c in range(num_chan - 1):
per_channel_gain[c] = 1. / float(meta['imroTbl'][c].split(' ')[index_imroTbl])
gain_factor = float(meta['imAiRangeMax']) / 512
channel_gains = per_channel_gain * gain_factor * 1e6
else:
signal_kind = ''
stream_name = device
units = 'V'
channel_gains = np.ones(num_chan)
# there are differents kinds of channels with different gain values
mn, ma, xa, dw = [int(e) for e in meta['snsMnMaXaDw'].split(sep=',')]
per_channel_gain = np.ones(num_chan, dtype='float64')
per_channel_gain[0:mn] = float(meta['niMNGain'])
per_channel_gain[mn:mn + ma] = float(meta['niMAGain'])
# this scaling come from the code in this zip
# https://billkarsh.github.io/SpikeGLX/Support/SpikeGLX_Datafile_Tools.zip
# in file readSGLX.py line76
# this is equivalent of 2**15
gain_factor = float(meta['niAiRangeMax']) / 32768
channel_gains = per_channel_gain * gain_factor
info = {}
info['name'] = name
info['meta'] = meta
info['bin_file'] = str(bin_filename)
for k in ('niSampRate', 'imSampRate'):
if k in meta:
info['sampling_rate'] = float(meta[k])
info['num_chan'] = num_chan
info['sample_length'] = int(meta['fileSizeBytes']) // 2 // num_chan
info['seg_index'] = seg_index
info['device'] = device
info['signal_kind'] = signal_kind
info['stream_name'] = stream_name
info['units'] = units
info['channel_names'] = [txt.split(';')[0] for txt in meta['snsChanMap']]
info['channel_gains'] = channel_gains
info['channel_offsets'] = np.zeros(info['num_chan'])
if signal_kind == 'ap':
channel_location = []
for e in meta['snsShankMap']:
x_pos = int(e.split(':')[1])
y_pos = int(e.split(':')[2])
channel_location.append([x_pos, y_pos])
info['channel_location'] = np.array(channel_location)
info_list.append(info)
return info_list | [
"def",
"scan_files",
"(",
"dirname",
")",
":",
"info_list",
"=",
"[",
"]",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dirname",
")",
":",
"for",
"file",
"in",
"files",
":",
"if",
"not",
"file",
".",
"endswith",
"(",
... | https://github.com/NeuralEnsemble/python-neo/blob/34d4db8fb0dc950dbbc6defd7fb75e99ea877286/neo/rawio/spikeglxrawio.py#L190-L290 | |
graalvm/mx | 29c0debab406352df3af246be2f8973be5db69ae | mx_benchmark.py | python | AsyncProfiler.name | (self) | return "async" | [] | def name(self):
return "async" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"\"async\""
] | https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx_benchmark.py#L145-L146 | |||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/sympy/physics/quantum/identitysearch.py | python | rl_op | (left, right) | return None | Perform a RL operation.
A RL operation multiplies both left and right circuits
with the dagger of the right circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a RL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RL operation:
>>> from sympy.physics.quantum.identitysearch import rl_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rl_op((x,), (y, z))
((Y(0), X(0)), (Z(0),))
>>> rl_op((x, y), (z,))
((Z(0), X(0), Y(0)), ()) | Perform a RL operation. | [
"Perform",
"a",
"RL",
"operation",
"."
] | def rl_op(left, right):
"""Perform a RL operation.
A RL operation multiplies both left and right circuits
with the dagger of the right circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a RL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RL operation:
>>> from sympy.physics.quantum.identitysearch import rl_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rl_op((x,), (y, z))
((Y(0), X(0)), (Z(0),))
>>> rl_op((x, y), (z,))
((Z(0), X(0), Y(0)), ())
"""
if (len(right) > 0):
rl_gate = right[0]
rl_gate_is_unitary = is_scalar_matrix(
(Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
if (len(right) > 0 and rl_gate_is_unitary):
# Get the new right side w/o the leftmost gate
new_right = right[1:len(right)]
# Add the leftmost gate to the left position on the left side
new_left = (Dagger(rl_gate),) + left
# Return the new gate rule
return (new_left, new_right)
return None | [
"def",
"rl_op",
"(",
"left",
",",
"right",
")",
":",
"if",
"(",
"len",
"(",
"right",
")",
">",
"0",
")",
":",
"rl_gate",
"=",
"right",
"[",
"0",
"]",
"rl_gate_is_unitary",
"=",
"is_scalar_matrix",
"(",
"(",
"Dagger",
"(",
"rl_gate",
")",
",",
"rl_g... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/physics/quantum/identitysearch.py#L278-L326 | |
ilius/pyglossary | d599b3beda3ae17642af5debd83bb991148e6425 | pyglossary/plugins/appledict/jing/main.py | python | JingTestError.__init__ | (self, returncode, cmd, output) | [] | def __init__(self, returncode, cmd, output):
super(JingTestError, self).__init__(returncode, cmd, output) | [
"def",
"__init__",
"(",
"self",
",",
"returncode",
",",
"cmd",
",",
"output",
")",
":",
"super",
"(",
"JingTestError",
",",
"self",
")",
".",
"__init__",
"(",
"returncode",
",",
"cmd",
",",
"output",
")"
] | https://github.com/ilius/pyglossary/blob/d599b3beda3ae17642af5debd83bb991148e6425/pyglossary/plugins/appledict/jing/main.py#L20-L21 | ||||
FreeOpcUa/python-opcua | 67f15551884d7f11659d52483e7b932999ca3a75 | opcua/ua/uaerrors/_base.py | python | UaStatusCodeError.__new__ | (cls, *args) | return UaError.__new__(cls, *args) | Creates a new UaStatusCodeError but returns a more specific subclass
if possible, e.g.
UaStatusCodeError(0x80010000) => BadUnexpectedError() | Creates a new UaStatusCodeError but returns a more specific subclass
if possible, e.g. | [
"Creates",
"a",
"new",
"UaStatusCodeError",
"but",
"returns",
"a",
"more",
"specific",
"subclass",
"if",
"possible",
"e",
".",
"g",
"."
] | def __new__(cls, *args):
"""
Creates a new UaStatusCodeError but returns a more specific subclass
if possible, e.g.
UaStatusCodeError(0x80010000) => BadUnexpectedError()
"""
# switch class to a more appropriate subclass
if len(args) >= 1:
code = args[0]
try:
cls = cls._subclasses[code]
except (KeyError, AttributeError):
pass
else:
args = args[1:]
return UaError.__new__(cls, *args) | [
"def",
"__new__",
"(",
"cls",
",",
"*",
"args",
")",
":",
"# switch class to a more appropriate subclass",
"if",
"len",
"(",
"args",
")",
">=",
"1",
":",
"code",
"=",
"args",
"[",
"0",
"]",
"try",
":",
"cls",
"=",
"cls",
".",
"_subclasses",
"[",
"code"... | https://github.com/FreeOpcUa/python-opcua/blob/67f15551884d7f11659d52483e7b932999ca3a75/opcua/ua/uaerrors/_base.py#L41-L59 | |
Qirky/Troop | 529c5eb14e456f683e6d23fd4adcddc8446aa115 | src/OSC.py | python | OSCStreamingServer.broadcastToClients | (self, oscData) | return result | Send OSC message or bundle to all connected clients. | Send OSC message or bundle to all connected clients. | [
"Send",
"OSC",
"message",
"or",
"bundle",
"to",
"all",
"connected",
"clients",
"."
] | def broadcastToClients(self, oscData):
""" Send OSC message or bundle to all connected clients. """
result = True
for client in self._clientList:
result = result and client.sendOSC(oscData)
return result | [
"def",
"broadcastToClients",
"(",
"self",
",",
"oscData",
")",
":",
"result",
"=",
"True",
"for",
"client",
"in",
"self",
".",
"_clientList",
":",
"result",
"=",
"result",
"and",
"client",
".",
"sendOSC",
"(",
"oscData",
")",
"return",
"result"
] | https://github.com/Qirky/Troop/blob/529c5eb14e456f683e6d23fd4adcddc8446aa115/src/OSC.py#L2674-L2679 | |
clinton-hall/nzbToMedia | 27669389216902d1085660167e7bda0bd8527ecf | libs/common/musicbrainzngs/musicbrainz.py | python | set_hostname | (new_hostname) | Set the hostname for MusicBrainz webservice requests.
Defaults to 'musicbrainz.org'.
You can also include a port: 'localhost:8000'. | Set the hostname for MusicBrainz webservice requests.
Defaults to 'musicbrainz.org'.
You can also include a port: 'localhost:8000'. | [
"Set",
"the",
"hostname",
"for",
"MusicBrainz",
"webservice",
"requests",
".",
"Defaults",
"to",
"musicbrainz",
".",
"org",
".",
"You",
"can",
"also",
"include",
"a",
"port",
":",
"localhost",
":",
"8000",
"."
] | def set_hostname(new_hostname):
"""Set the hostname for MusicBrainz webservice requests.
Defaults to 'musicbrainz.org'.
You can also include a port: 'localhost:8000'."""
global hostname
hostname = new_hostname | [
"def",
"set_hostname",
"(",
"new_hostname",
")",
":",
"global",
"hostname",
"hostname",
"=",
"new_hostname"
] | https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/musicbrainzngs/musicbrainz.py#L320-L325 | ||
CentOS-PaaS-SIG/linchpin | a449385a4823a43e6f336de42b874ac7877d8b3e | linchpin/validator/__init__.py | python | Validator._gen_error_msg | (self, prefix, section, error) | Recursively generate a nicely-formatted validation error
:param prefix:
:param section: the section in which the error occured
:param error: the error message itself | Recursively generate a nicely-formatted validation error | [
"Recursively",
"generate",
"a",
"nicely",
"-",
"formatted",
"validation",
"error"
] | def _gen_error_msg(self, prefix, section, error):
"""
Recursively generate a nicely-formatted validation error
:param prefix:
:param section: the section in which the error occured
:param error: the error message itself
"""
# set the prefix for this subtree
if section != "":
if prefix != "":
prefix += '[' + str(section) + ']'
else:
prefix = str(section)
if isinstance(error, str):
if prefix == "":
return error
return prefix + ": " + error + os.linesep
elif isinstance(error, list):
msg = ""
for i, e in enumerate(error):
# we don't need to change the prefix here
msg += self._gen_error_msg(prefix, "", e)
return msg
else:
# in this case, error is a dict
msg = ""
for key, val in six.iteritems(error):
msg += self._gen_error_msg(prefix, key, val)
return msg | [
"def",
"_gen_error_msg",
"(",
"self",
",",
"prefix",
",",
"section",
",",
"error",
")",
":",
"# set the prefix for this subtree",
"if",
"section",
"!=",
"\"\"",
":",
"if",
"prefix",
"!=",
"\"\"",
":",
"prefix",
"+=",
"'['",
"+",
"str",
"(",
"section",
")",... | https://github.com/CentOS-PaaS-SIG/linchpin/blob/a449385a4823a43e6f336de42b874ac7877d8b3e/linchpin/validator/__init__.py#L287-L320 | ||
edisonlz/fastor | 342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3 | base/site-packages/django/contrib/gis/gdal/geometries.py | python | OGRGeometry.ewkt | (self) | Returns the EWKT representation of the Geometry. | Returns the EWKT representation of the Geometry. | [
"Returns",
"the",
"EWKT",
"representation",
"of",
"the",
"Geometry",
"."
] | def ewkt(self):
"Returns the EWKT representation of the Geometry."
srs = self.srs
if srs and srs.srid:
return 'SRID=%s;%s' % (srs.srid, self.wkt)
else:
return self.wkt | [
"def",
"ewkt",
"(",
"self",
")",
":",
"srs",
"=",
"self",
".",
"srs",
"if",
"srs",
"and",
"srs",
".",
"srid",
":",
"return",
"'SRID=%s;%s'",
"%",
"(",
"srs",
".",
"srid",
",",
"self",
".",
"wkt",
")",
"else",
":",
"return",
"self",
".",
"wkt"
] | https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/contrib/gis/gdal/geometries.py#L362-L368 | ||
nodesign/weio | 1d67d705a5c36a2e825ad13feab910b0aca9a2e8 | sandbox/downloadFromTornado/download.py | python | download | (url) | [] | def download(url):
http_client = httpclient.AsyncHTTPClient()
http_client.fetch(url, callback=doUpdate) | [
"def",
"download",
"(",
"url",
")",
":",
"http_client",
"=",
"httpclient",
".",
"AsyncHTTPClient",
"(",
")",
"http_client",
".",
"fetch",
"(",
"url",
",",
"callback",
"=",
"doUpdate",
")"
] | https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/sandbox/downloadFromTornado/download.py#L105-L107 | ||||
OCA/l10n-spain | 99050907670a70307fcd8cdfb6f3400d9e120df4 | l10n_es_aeat_mod347/models/mod347.py | python | L10nEsAeatMod347PartnerRecord._default_record_id | (self) | return self.env.context.get("report_id", False) | [] | def _default_record_id(self):
return self.env.context.get("report_id", False) | [
"def",
"_default_record_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"env",
".",
"context",
".",
"get",
"(",
"\"report_id\"",
",",
"False",
")"
] | https://github.com/OCA/l10n-spain/blob/99050907670a70307fcd8cdfb6f3400d9e120df4/l10n_es_aeat_mod347/models/mod347.py#L332-L333 | |||
HuguesTHOMAS/KPConv | 16bfbb96ac9af48a3c829d1f8123152d35b63862 | utils/config.py | python | Config.__init__ | (self) | Class Initialyser | Class Initialyser | [
"Class",
"Initialyser"
] | def __init__(self):
"""
Class Initialyser
"""
# Number of layers
self.num_layers = len([block for block in self.architecture if 'pool' in block or 'strided' in block]) + 1 | [
"def",
"__init__",
"(",
"self",
")",
":",
"# Number of layers",
"self",
".",
"num_layers",
"=",
"len",
"(",
"[",
"block",
"for",
"block",
"in",
"self",
".",
"architecture",
"if",
"'pool'",
"in",
"block",
"or",
"'strided'",
"in",
"block",
"]",
")",
"+",
... | https://github.com/HuguesTHOMAS/KPConv/blob/16bfbb96ac9af48a3c829d1f8123152d35b63862/utils/config.py#L166-L172 | ||
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/distutils/dist.py | python | Distribution._show_help | (self, parser, global_options=1, display_options=1,
commands=[]) | Show help for the setup script command-line in the form of
several lists of command-line options. 'parser' should be a
FancyGetopt instance; do not expect it to be returned in the
same state, as its option table will be reset to make it
generate the correct help text.
If 'global_options' is true, lists the global options:
--verbose, --dry-run, etc. If 'display_options' is true, lists
the "display-only" options: --name, --version, etc. Finally,
lists per-command help for every command name or command class
in 'commands'. | Show help for the setup script command-line in the form of
several lists of command-line options. 'parser' should be a
FancyGetopt instance; do not expect it to be returned in the
same state, as its option table will be reset to make it
generate the correct help text. | [
"Show",
"help",
"for",
"the",
"setup",
"script",
"command",
"-",
"line",
"in",
"the",
"form",
"of",
"several",
"lists",
"of",
"command",
"-",
"line",
"options",
".",
"parser",
"should",
"be",
"a",
"FancyGetopt",
"instance",
";",
"do",
"not",
"expect",
"i... | def _show_help(self, parser, global_options=1, display_options=1,
commands=[]):
"""Show help for the setup script command-line in the form of
several lists of command-line options. 'parser' should be a
FancyGetopt instance; do not expect it to be returned in the
same state, as its option table will be reset to make it
generate the correct help text.
If 'global_options' is true, lists the global options:
--verbose, --dry-run, etc. If 'display_options' is true, lists
the "display-only" options: --name, --version, etc. Finally,
lists per-command help for every command name or command class
in 'commands'.
"""
# late import because of mutual dependence between these modules
from distutils.core import gen_usage
from distutils.cmd import Command
if global_options:
if display_options:
options = self._get_toplevel_options()
else:
options = self.global_options
parser.set_option_table(options)
parser.print_help(self.common_usage + "\nGlobal options:")
print('')
if display_options:
parser.set_option_table(self.display_options)
parser.print_help(
"Information display options (just display " +
"information, ignore any commands)")
print('')
for command in self.commands:
if isinstance(command, type) and issubclass(command, Command):
klass = command
else:
klass = self.get_command_class(command)
if (hasattr(klass, 'help_options') and
isinstance(klass.help_options, list)):
parser.set_option_table(klass.user_options +
fix_help_options(klass.help_options))
else:
parser.set_option_table(klass.user_options)
parser.print_help("Options for '%s' command:" % klass.__name__)
print('')
print(gen_usage(self.script_name)) | [
"def",
"_show_help",
"(",
"self",
",",
"parser",
",",
"global_options",
"=",
"1",
",",
"display_options",
"=",
"1",
",",
"commands",
"=",
"[",
"]",
")",
":",
"# late import because of mutual dependence between these modules",
"from",
"distutils",
".",
"core",
"imp... | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/distutils/dist.py#L607-L655 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_openshift_3.2/library/oc_process.py | python | OpenShiftCLIConfig.to_option_list | (self) | return self.stringify() | return all options as a string | return all options as a string | [
"return",
"all",
"options",
"as",
"a",
"string"
] | def to_option_list(self):
'''return all options as a string'''
return self.stringify() | [
"def",
"to_option_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"stringify",
"(",
")"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/library/oc_process.py#L468-L470 | |
holland-backup/holland | 77dcfe9f23d4254e4c351cdc18f29a8d34945812 | plugins/holland.lib.mysql/holland/lib/mysql/client/base.py | python | MySQLClient.flush_tables_with_read_lock | (self) | Acquire MySQL server global read lock
Runs FLUSH TABLES WITH READ LOCK | Acquire MySQL server global read lock | [
"Acquire",
"MySQL",
"server",
"global",
"read",
"lock"
] | def flush_tables_with_read_lock(self):
"""Acquire MySQL server global read lock
Runs FLUSH TABLES WITH READ LOCK
"""
cursor = self.cursor()
cursor.execute("FLUSH TABLES WITH READ LOCK")
cursor.close() | [
"def",
"flush_tables_with_read_lock",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"FLUSH TABLES WITH READ LOCK\"",
")",
"cursor",
".",
"close",
"(",
")"
] | https://github.com/holland-backup/holland/blob/77dcfe9f23d4254e4c351cdc18f29a8d34945812/plugins/holland.lib.mysql/holland/lib/mysql/client/base.py#L115-L122 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Tools/scripts/fixcid.py | python | setreverse | () | [] | def setreverse():
global Reverse
Reverse = (not Reverse) | [
"def",
"setreverse",
"(",
")",
":",
"global",
"Reverse",
"Reverse",
"=",
"(",
"not",
"Reverse",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/scripts/fixcid.py#L270-L272 | ||||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/27/Lib/lib2to3/fixer_base.py | python | BaseFix.start_tree | (self, tree, filename) | Some fixers need to maintain tree-wide state.
This method is called once, at the start of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from. | Some fixers need to maintain tree-wide state.
This method is called once, at the start of tree fix-up. | [
"Some",
"fixers",
"need",
"to",
"maintain",
"tree",
"-",
"wide",
"state",
".",
"This",
"method",
"is",
"called",
"once",
"at",
"the",
"start",
"of",
"tree",
"fix",
"-",
"up",
"."
] | def start_tree(self, tree, filename):
"""Some fixers need to maintain tree-wide state.
This method is called once, at the start of tree fix-up.
tree - the root node of the tree to be processed.
filename - the name of the file the tree came from.
"""
self.used_names = tree.used_names
self.set_filename(filename)
self.numbers = itertools.count(1)
self.first_log = True | [
"def",
"start_tree",
"(",
"self",
",",
"tree",
",",
"filename",
")",
":",
"self",
".",
"used_names",
"=",
"tree",
".",
"used_names",
"self",
".",
"set_filename",
"(",
"filename",
")",
"self",
".",
"numbers",
"=",
"itertools",
".",
"count",
"(",
"1",
")... | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/lib2to3/fixer_base.py#L150-L160 | ||
inventree/InvenTree | 4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b | InvenTree/part/api.py | python | BomList.get_queryset | (self, *args, **kwargs) | return queryset | [] | def get_queryset(self, *args, **kwargs):
queryset = BomItem.objects.all()
queryset = self.get_serializer_class().setup_eager_loading(queryset)
return queryset | [
"def",
"get_queryset",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"BomItem",
".",
"objects",
".",
"all",
"(",
")",
"queryset",
"=",
"self",
".",
"get_serializer_class",
"(",
")",
".",
"setup_eager_loading",
"(",
... | https://github.com/inventree/InvenTree/blob/4a5e4a88ac3e91d64a21e8cab3708ecbc6e2bd8b/InvenTree/part/api.py#L1367-L1373 | |||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_oa_openshift/library/oc_label.py | python | Utils.filter_versions | (stdout) | return version_dict | filter the oc version output | filter the oc version output | [
"filter",
"the",
"oc",
"version",
"output"
] | def filter_versions(stdout):
''' filter the oc version output '''
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if not line:
continue
if line.startswith(term):
version_dict[term] = line.split()[-1]
# horrible hack to get openshift version in Openshift 3.2
# By default "oc version in 3.2 does not return an "openshift" version
if "openshift" not in version_dict:
version_dict["openshift"] = version_dict["oc"]
return version_dict | [
"def",
"filter_versions",
"(",
"stdout",
")",
":",
"version_dict",
"=",
"{",
"}",
"version_search",
"=",
"[",
"'oc'",
",",
"'openshift'",
",",
"'kubernetes'",
"]",
"for",
"line",
"in",
"stdout",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_label.py#L1296-L1314 | |
samoturk/mol2vec | 850d944d5f48a58e26ed0264332b5741f72555aa | mol2vec/helpers.py | python | depict_identifier | (mol, identifier, radius, useFeatures=False, **kwargs) | Depict an identifier in Morgan fingerprint.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule
identifier : int or str
Feature identifier from Morgan fingerprint
radius : int
Radius of Morgan FP
useFeatures : bool
Use feature-based Morgan FP
Returns
-------
IPython.display.SVG | Depict an identifier in Morgan fingerprint.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule
identifier : int or str
Feature identifier from Morgan fingerprint
radius : int
Radius of Morgan FP
useFeatures : bool
Use feature-based Morgan FP
Returns
-------
IPython.display.SVG | [
"Depict",
"an",
"identifier",
"in",
"Morgan",
"fingerprint",
".",
"Parameters",
"----------",
"mol",
":",
"rdkit",
".",
"Chem",
".",
"rdchem",
".",
"Mol",
"RDKit",
"molecule",
"identifier",
":",
"int",
"or",
"str",
"Feature",
"identifier",
"from",
"Morgan",
... | def depict_identifier(mol, identifier, radius, useFeatures=False, **kwargs):
"""Depict an identifier in Morgan fingerprint.
Parameters
----------
mol : rdkit.Chem.rdchem.Mol
RDKit molecule
identifier : int or str
Feature identifier from Morgan fingerprint
radius : int
Radius of Morgan FP
useFeatures : bool
Use feature-based Morgan FP
Returns
-------
IPython.display.SVG
"""
identifier = int(identifier)
info = {}
AllChem.GetMorganFingerprint(mol, radius, bitInfo=info, useFeatures=useFeatures)
if identifier in info.keys():
atoms, radii = zip(*info[identifier])
return depict_atoms(mol, atoms, radii, **kwargs)
else:
return mol_to_svg(mol, **kwargs) | [
"def",
"depict_identifier",
"(",
"mol",
",",
"identifier",
",",
"radius",
",",
"useFeatures",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"identifier",
"=",
"int",
"(",
"identifier",
")",
"info",
"=",
"{",
"}",
"AllChem",
".",
"GetMorganFingerprint",
... | https://github.com/samoturk/mol2vec/blob/850d944d5f48a58e26ed0264332b5741f72555aa/mol2vec/helpers.py#L108-L133 | ||
SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions | 014c4ca27a70b5907a183e942228004c989dcbe4 | selim_sef/zoo/unet.py | python | UnetDecoderBlock.__init__ | (self, in_channels, middle_channels, out_channels) | [] | def __init__(self, in_channels, middle_channels, out_channels):
super().__init__()
self.layer = nn.Sequential(
nn.Upsample(scale_factor=2),
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.ReLU(inplace=True)
) | [
"def",
"__init__",
"(",
"self",
",",
"in_channels",
",",
"middle_channels",
",",
"out_channels",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"layer",
"=",
"nn",
".",
"Sequential",
"(",
"nn",
".",
"Upsample",
"(",
"scale_factor",
... | https://github.com/SpaceNetChallenge/SpaceNet_Off_Nadir_Solutions/blob/014c4ca27a70b5907a183e942228004c989dcbe4/selim_sef/zoo/unet.py#L272-L278 | ||||
uber-research/PPLM | e236b8989322128360182d29a79944627957ad47 | paper_code/pytorch_pretrained_bert/tokenization.py | python | BertTokenizer.convert_ids_to_tokens | (self, ids) | return tokens | Converts a sequence of ids in wordpiece tokens using the vocab. | Converts a sequence of ids in wordpiece tokens using the vocab. | [
"Converts",
"a",
"sequence",
"of",
"ids",
"in",
"wordpiece",
"tokens",
"using",
"the",
"vocab",
"."
] | def convert_ids_to_tokens(self, ids):
"""Converts a sequence of ids in wordpiece tokens using the vocab."""
tokens = []
for i in ids:
tokens.append(self.ids_to_tokens[i])
return tokens | [
"def",
"convert_ids_to_tokens",
"(",
"self",
",",
"ids",
")",
":",
"tokens",
"=",
"[",
"]",
"for",
"i",
"in",
"ids",
":",
"tokens",
".",
"append",
"(",
"self",
".",
"ids_to_tokens",
"[",
"i",
"]",
")",
"return",
"tokens"
] | https://github.com/uber-research/PPLM/blob/e236b8989322128360182d29a79944627957ad47/paper_code/pytorch_pretrained_bert/tokenization.py#L130-L135 | |
paylogic/pip-accel | ccad1b784927a322d996db593403b1d2d2e22666 | pip_accel/config.py | python | Config.log_verbosity | (self) | return self.get(property_name='log_verbosity',
environment_variable='PIP_ACCEL_LOG_VERBOSITY',
configuration_option='log-verbosity',
default='INFO') | The verbosity of log messages written to the terminal.
- Environment variable: ``$PIP_ACCEL_LOG_VERBOSITY``
- Configuration option: ``log-verbosity``
- Default: 'INFO' (a string). | The verbosity of log messages written to the terminal. | [
"The",
"verbosity",
"of",
"log",
"messages",
"written",
"to",
"the",
"terminal",
"."
] | def log_verbosity(self):
"""
The verbosity of log messages written to the terminal.
- Environment variable: ``$PIP_ACCEL_LOG_VERBOSITY``
- Configuration option: ``log-verbosity``
- Default: 'INFO' (a string).
"""
return self.get(property_name='log_verbosity',
environment_variable='PIP_ACCEL_LOG_VERBOSITY',
configuration_option='log-verbosity',
default='INFO') | [
"def",
"log_verbosity",
"(",
"self",
")",
":",
"return",
"self",
".",
"get",
"(",
"property_name",
"=",
"'log_verbosity'",
",",
"environment_variable",
"=",
"'PIP_ACCEL_LOG_VERBOSITY'",
",",
"configuration_option",
"=",
"'log-verbosity'",
",",
"default",
"=",
"'INFO... | https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/config.py#L309-L320 | |
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_list.py | python | V1beta1CertificateSigningRequestList.to_str | (self) | return pprint.pformat(self.to_dict()) | Returns the string representation of the model | Returns the string representation of the model | [
"Returns",
"the",
"string",
"representation",
"of",
"the",
"model"
] | def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict()) | [
"def",
"to_str",
"(",
"self",
")",
":",
"return",
"pprint",
".",
"pformat",
"(",
"self",
".",
"to_dict",
"(",
")",
")"
] | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_certificate_signing_request_list.py#L183-L185 | |
fedora-infra/bodhi | 2b1df12d85eb2e575d8e481a3936c4f92d1fe29a | bodhi/server/models.py | python | BodhiBase.find_polymorphic_child | (cls, identity) | Find a child of a polymorphic base class.
For example, given the base Package class and the 'rpm' identity, this
class method should return the RpmPackage class.
This is accomplished by iterating over all classes in scope.
Limiting that to only those which are an extension of the given base
class. Among those, return the one whose polymorphic_identity matches
the value given. If none are found, then raise a NameError.
Args:
identity (EnumSymbol): An instance of EnumSymbol used to identify the child.
Returns:
BodhiBase: The type-specific child class.
Raises:
KeyError: If this class is not polymorphic.
NameError: If no child class is found for the given identity.
TypeError: If identity is not an EnumSymbol. | Find a child of a polymorphic base class. | [
"Find",
"a",
"child",
"of",
"a",
"polymorphic",
"base",
"class",
"."
] | def find_polymorphic_child(cls, identity):
"""
Find a child of a polymorphic base class.
For example, given the base Package class and the 'rpm' identity, this
class method should return the RpmPackage class.
This is accomplished by iterating over all classes in scope.
Limiting that to only those which are an extension of the given base
class. Among those, return the one whose polymorphic_identity matches
the value given. If none are found, then raise a NameError.
Args:
identity (EnumSymbol): An instance of EnumSymbol used to identify the child.
Returns:
BodhiBase: The type-specific child class.
Raises:
KeyError: If this class is not polymorphic.
NameError: If no child class is found for the given identity.
TypeError: If identity is not an EnumSymbol.
"""
if not isinstance(identity, EnumSymbol):
raise TypeError("%r is not an instance of EnumSymbol" % identity)
if 'polymorphic_on' not in getattr(cls, '__mapper_args__', {}):
raise KeyError("%r is not a polymorphic model." % cls)
classes = (c for c in globals().values() if isinstance(c, type))
children = (c for c in classes if issubclass(c, cls))
for child in children:
candidate = child.__mapper_args__.get('polymorphic_identity')
if candidate is identity:
return child
error = "Found no child of %r with identity %r"
raise NameError(error % (cls, identity)) | [
"def",
"find_polymorphic_child",
"(",
"cls",
",",
"identity",
")",
":",
"if",
"not",
"isinstance",
"(",
"identity",
",",
"EnumSymbol",
")",
":",
"raise",
"TypeError",
"(",
"\"%r is not an instance of EnumSymbol\"",
"%",
"identity",
")",
"if",
"'polymorphic_on'",
"... | https://github.com/fedora-infra/bodhi/blob/2b1df12d85eb2e575d8e481a3936c4f92d1fe29a/bodhi/server/models.py#L470-L505 | ||
flasgger/flasgger | beb9fa781fc6b063fe3f3081b9677dd70184a2da | examples/validation.py | python | validateannotation | () | return jsonify(data) | In this example you use validate(schema_id) annotation on the
method in which you want to validate received data | In this example you use validate(schema_id) annotation on the
method in which you want to validate received data | [
"In",
"this",
"example",
"you",
"use",
"validate",
"(",
"schema_id",
")",
"annotation",
"on",
"the",
"method",
"in",
"which",
"you",
"want",
"to",
"validate",
"received",
"data"
] | def validateannotation():
"""
In this example you use validate(schema_id) annotation on the
method in which you want to validate received data
"""
data = request.json
return jsonify(data) | [
"def",
"validateannotation",
"(",
")",
":",
"data",
"=",
"request",
".",
"json",
"return",
"jsonify",
"(",
"data",
")"
] | https://github.com/flasgger/flasgger/blob/beb9fa781fc6b063fe3f3081b9677dd70184a2da/examples/validation.py#L95-L101 | |
TesterlifeRaymond/doraemon | d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333 | venv/lib/python3.6/site-packages/click/core.py | python | Context.exit | (self, code=0) | Exits the application with a given exit code. | Exits the application with a given exit code. | [
"Exits",
"the",
"application",
"with",
"a",
"given",
"exit",
"code",
"."
] | def exit(self, code=0):
"""Exits the application with a given exit code."""
sys.exit(code) | [
"def",
"exit",
"(",
"self",
",",
"code",
"=",
"0",
")",
":",
"sys",
".",
"exit",
"(",
"code",
")"
] | https://github.com/TesterlifeRaymond/doraemon/blob/d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333/venv/lib/python3.6/site-packages/click/core.py#L482-L484 | ||
leo-editor/leo-editor | 383d6776d135ef17d73d935a2f0ecb3ac0e99494 | leo/commands/gotoCommands.py | python | GoToCommands.find_file_line | (self, n, p=None) | return self.find_script_line(n, p) | Place the cursor on the n'th line (one-based) of an external file.
Return (p, offset, found) for unit testing. | Place the cursor on the n'th line (one-based) of an external file.
Return (p, offset, found) for unit testing. | [
"Place",
"the",
"cursor",
"on",
"the",
"n",
"th",
"line",
"(",
"one",
"-",
"based",
")",
"of",
"an",
"external",
"file",
".",
"Return",
"(",
"p",
"offset",
"found",
")",
"for",
"unit",
"testing",
"."
] | def find_file_line(self, n, p=None):
"""
Place the cursor on the n'th line (one-based) of an external file.
Return (p, offset, found) for unit testing.
"""
c = self.c
if n < 0:
return None, -1, False
p = p or c.p
root, fileName = self.find_root(p)
if root:
# Step 1: Get the lines of external files *with* sentinels,
# even if the actual external file actually contains no sentinels.
sentinels = root.isAtFileNode()
s = self.get_external_file_with_sentinels(root)
lines = g.splitLines(s)
# Step 2: scan the lines for line n.
if sentinels:
# All sentinels count as real lines.
gnx, h, offset = self.scan_sentinel_lines(lines, n, root)
else:
# Not all sentinels cound as real lines.
gnx, h, offset = self.scan_nonsentinel_lines(lines, n, root)
p, found = self.find_gnx(root, gnx, h)
if gnx and found:
self.success(lines, n, offset, p)
return p, offset, True
self.fail(lines, n, root)
return None, -1, False
return self.find_script_line(n, p) | [
"def",
"find_file_line",
"(",
"self",
",",
"n",
",",
"p",
"=",
"None",
")",
":",
"c",
"=",
"self",
".",
"c",
"if",
"n",
"<",
"0",
":",
"return",
"None",
",",
"-",
"1",
",",
"False",
"p",
"=",
"p",
"or",
"c",
".",
"p",
"root",
",",
"fileName... | https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/commands/gotoCommands.py#L18-L47 | |
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/polys/rootisolation.py | python | ComplexInterval.by | (self) | Return ``y`` coordinate of north-eastern corner. | Return ``y`` coordinate of north-eastern corner. | [
"Return",
"y",
"coordinate",
"of",
"north",
"-",
"eastern",
"corner",
"."
] | def by(self):
"""Return ``y`` coordinate of north-eastern corner. """
if not self.conj:
return self.b[1]
else:
return -self.a[1] | [
"def",
"by",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"conj",
":",
"return",
"self",
".",
"b",
"[",
"1",
"]",
"else",
":",
"return",
"-",
"self",
".",
"a",
"[",
"1",
"]"
] | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/polys/rootisolation.py#L1993-L1998 | ||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/utils/dummy_pt_objects.py | python | apply_chunking_to_forward | (*args, **kwargs) | [] | def apply_chunking_to_forward(*args, **kwargs):
requires_backends(apply_chunking_to_forward, ["torch"]) | [
"def",
"apply_chunking_to_forward",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"requires_backends",
"(",
"apply_chunking_to_forward",
",",
"[",
"\"torch\"",
"]",
")"
] | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L237-L238 | ||||
CouchPotato/CouchPotatoV1 | 135b3331d1b88ef645e29b76f2d4cc4a732c9232 | library/sqlalchemy/orm/attributes.py | python | _install_lookup_strategy | (implementation) | Replace global class/object management functions
with either faster or more comprehensive implementations,
based on whether or not extended class instrumentation
has been detected.
This function is called only by InstrumentationRegistry()
and unit tests specific to this behavior. | Replace global class/object management functions
with either faster or more comprehensive implementations,
based on whether or not extended class instrumentation
has been detected.
This function is called only by InstrumentationRegistry()
and unit tests specific to this behavior. | [
"Replace",
"global",
"class",
"/",
"object",
"management",
"functions",
"with",
"either",
"faster",
"or",
"more",
"comprehensive",
"implementations",
"based",
"on",
"whether",
"or",
"not",
"extended",
"class",
"instrumentation",
"has",
"been",
"detected",
".",
"Th... | def _install_lookup_strategy(implementation):
"""Replace global class/object management functions
with either faster or more comprehensive implementations,
based on whether or not extended class instrumentation
has been detected.
This function is called only by InstrumentationRegistry()
and unit tests specific to this behavior.
"""
global instance_state, instance_dict, manager_of_class
if implementation is util.symbol('native'):
instance_state = attrgetter(ClassManager.STATE_ATTR)
instance_dict = attrgetter("__dict__")
def manager_of_class(cls):
return cls.__dict__.get(ClassManager.MANAGER_ATTR, None)
else:
instance_state = instrumentation_registry.state_of
instance_dict = instrumentation_registry.dict_of
manager_of_class = instrumentation_registry.manager_of_class | [
"def",
"_install_lookup_strategy",
"(",
"implementation",
")",
":",
"global",
"instance_state",
",",
"instance_dict",
",",
"manager_of_class",
"if",
"implementation",
"is",
"util",
".",
"symbol",
"(",
"'native'",
")",
":",
"instance_state",
"=",
"attrgetter",
"(",
... | https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/orm/attributes.py#L1751-L1770 | ||
bikalims/bika.lims | 35e4bbdb5a3912cae0b5eb13e51097c8b0486349 | bika/lims/browser/worksheet/views/printview.py | python | PrintView._analyst_data | (self, ws) | return {'username': username,
'fullname': to_utf8(self.user_fullname(username)),
'email': to_utf8(self.user_email(username))} | Returns a dict that represent the analyst assigned to the
worksheet.
Keys: username, fullname, email | Returns a dict that represent the analyst assigned to the
worksheet.
Keys: username, fullname, email | [
"Returns",
"a",
"dict",
"that",
"represent",
"the",
"analyst",
"assigned",
"to",
"the",
"worksheet",
".",
"Keys",
":",
"username",
"fullname",
"email"
] | def _analyst_data(self, ws):
""" Returns a dict that represent the analyst assigned to the
worksheet.
Keys: username, fullname, email
"""
username = ws.getAnalyst();
return {'username': username,
'fullname': to_utf8(self.user_fullname(username)),
'email': to_utf8(self.user_email(username))} | [
"def",
"_analyst_data",
"(",
"self",
",",
"ws",
")",
":",
"username",
"=",
"ws",
".",
"getAnalyst",
"(",
")",
"return",
"{",
"'username'",
":",
"username",
",",
"'fullname'",
":",
"to_utf8",
"(",
"self",
".",
"user_fullname",
"(",
"username",
")",
")",
... | https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/browser/worksheet/views/printview.py#L259-L267 | |
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/multiprocessing/dummy/connection.py | python | Connection.__enter__ | (self) | return self | [] | def __enter__(self):
return self | [
"def",
"__enter__",
"(",
"self",
")",
":",
"return",
"self"
] | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/multiprocessing/dummy/connection.py#L71-L72 | |||
thombashi/pytablewriter | 120392a8723a8ca13a6a519e7e3d11c447e9d9c7 | pytablewriter/writer/binary/_excel.py | python | ExcelTableWriter.last_header_row | (self) | return self._last_header_row | :return: Index of the last row of the header.
:rtype: int
.. note:: |excel_attr| | :return: Index of the last row of the header.
:rtype: int | [
":",
"return",
":",
"Index",
"of",
"the",
"last",
"row",
"of",
"the",
"header",
".",
":",
"rtype",
":",
"int"
] | def last_header_row(self) -> int:
"""
:return: Index of the last row of the header.
:rtype: int
.. note:: |excel_attr|
"""
return self._last_header_row | [
"def",
"last_header_row",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_last_header_row"
] | https://github.com/thombashi/pytablewriter/blob/120392a8723a8ca13a6a519e7e3d11c447e9d9c7/pytablewriter/writer/binary/_excel.py#L66-L74 | |
apple/ccs-calendarserver | 13c706b985fb728b9aab42dc0fef85aae21921c3 | txdav/common/datastore/sql_directory.py | python | GroupCacherAPIMixin.groupMembers | (self, groupID) | The members of the given group as recorded in the db | The members of the given group as recorded in the db | [
"The",
"members",
"of",
"the",
"given",
"group",
"as",
"recorded",
"in",
"the",
"db"
] | def groupMembers(self, groupID):
"""
The members of the given group as recorded in the db
"""
members = set()
memberUIDs = (yield self.groupMemberUIDs(groupID))
for uid in memberUIDs:
record = (yield self.directoryService().recordWithUID(uid))
if record is not None:
members.add(record)
returnValue(members) | [
"def",
"groupMembers",
"(",
"self",
",",
"groupID",
")",
":",
"members",
"=",
"set",
"(",
")",
"memberUIDs",
"=",
"(",
"yield",
"self",
".",
"groupMemberUIDs",
"(",
"groupID",
")",
")",
"for",
"uid",
"in",
"memberUIDs",
":",
"record",
"=",
"(",
"yield"... | https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/sql_directory.py#L417-L427 | ||
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/series/kauers.py | python | finite_diff | (expression, variable, increment=1) | return expression2 - expression | Takes as input a polynomial expression and the variable used to construct
it and returns the difference between function's value when the input is
incremented to 1 and the original function value. If you want an increment
other than one supply it as a third argument.
Examples
=========
>>> from sympy.abc import x, y, z, k, n
>>> from sympy.series.kauers import finite_diff
>>> from sympy import Sum
>>> finite_diff(x**2, x)
2*x + 1
>>> finite_diff(y**3 + 2*y**2 + 3*y + 4, y)
3*y**2 + 7*y + 6
>>> finite_diff(x**2 + 3*x + 8, x, 2)
4*x + 10
>>> finite_diff(z**3 + 8*z, z, 3)
9*z**2 + 27*z + 51 | Takes as input a polynomial expression and the variable used to construct
it and returns the difference between function's value when the input is
incremented to 1 and the original function value. If you want an increment
other than one supply it as a third argument. | [
"Takes",
"as",
"input",
"a",
"polynomial",
"expression",
"and",
"the",
"variable",
"used",
"to",
"construct",
"it",
"and",
"returns",
"the",
"difference",
"between",
"function",
"s",
"value",
"when",
"the",
"input",
"is",
"incremented",
"to",
"1",
"and",
"th... | def finite_diff(expression, variable, increment=1):
"""
Takes as input a polynomial expression and the variable used to construct
it and returns the difference between function's value when the input is
incremented to 1 and the original function value. If you want an increment
other than one supply it as a third argument.
Examples
=========
>>> from sympy.abc import x, y, z, k, n
>>> from sympy.series.kauers import finite_diff
>>> from sympy import Sum
>>> finite_diff(x**2, x)
2*x + 1
>>> finite_diff(y**3 + 2*y**2 + 3*y + 4, y)
3*y**2 + 7*y + 6
>>> finite_diff(x**2 + 3*x + 8, x, 2)
4*x + 10
>>> finite_diff(z**3 + 8*z, z, 3)
9*z**2 + 27*z + 51
"""
expression = expression.expand()
expression2 = expression.subs(variable, variable + increment)
expression2 = expression2.expand()
return expression2 - expression | [
"def",
"finite_diff",
"(",
"expression",
",",
"variable",
",",
"increment",
"=",
"1",
")",
":",
"expression",
"=",
"expression",
".",
"expand",
"(",
")",
"expression2",
"=",
"expression",
".",
"subs",
"(",
"variable",
",",
"variable",
"+",
"increment",
")"... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/series/kauers.py#L7-L31 | |
pjkundert/cpppo | 4c217b6c06b88bede3888cc5ea2731f271a95086 | remote/io.py | python | input.changed | ( self, last, chng ) | Called when the value is detected to have changed | Called when the value is detected to have changed | [
"Called",
"when",
"the",
"value",
"is",
"detected",
"to",
"have",
"changed"
] | def changed( self, last, chng ):
""" Called when the value is detected to have changed """
log.info( "%s ==> %-10s (was: %s)" % (
self._descr, misc.reprlib.repr( chng ), misc.reprlib.repr( last ))) | [
"def",
"changed",
"(",
"self",
",",
"last",
",",
"chng",
")",
":",
"log",
".",
"info",
"(",
"\"%s ==> %-10s (was: %s)\"",
"%",
"(",
"self",
".",
"_descr",
",",
"misc",
".",
"reprlib",
".",
"repr",
"(",
"chng",
")",
",",
"misc",
".",
"reprlib",
".",
... | https://github.com/pjkundert/cpppo/blob/4c217b6c06b88bede3888cc5ea2731f271a95086/remote/io.py#L72-L75 | ||
conjure-up/conjure-up | d2bf8ab8e71ff01321d0e691a8d3e3833a047678 | conjureup/controllers/juju/regions/gui.py | python | RegionsController.render | (self, going_back=False) | [] | def render(self, going_back=False):
if len(self.regions) < 2:
if going_back:
return self.back()
return self.finish(self.default_region)
view = RegionPickerView(self.regions,
app.provider.region or self.default_region,
self.finish,
self.back)
view.show() | [
"def",
"render",
"(",
"self",
",",
"going_back",
"=",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"regions",
")",
"<",
"2",
":",
"if",
"going_back",
":",
"return",
"self",
".",
"back",
"(",
")",
"return",
"self",
".",
"finish",
"(",
"self",
... | https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/controllers/juju/regions/gui.py#L9-L19 | ||||
CGCookie/retopoflow | 3d8b3a47d1d661f99ab0aeb21d31370bf15de35e | retopoflow/rf/rf_target.py | python | RetopoFlow_Target.get_target_geometry_counts | (self) | return self.rftarget.get_geometry_counts() | [] | def get_target_geometry_counts(self):
return self.rftarget.get_geometry_counts() | [
"def",
"get_target_geometry_counts",
"(",
"self",
")",
":",
"return",
"self",
".",
"rftarget",
".",
"get_geometry_counts",
"(",
")"
] | https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rf/rf_target.py#L642-L643 | |||
Zengyi-Qin/MonoGRNet | bd8c36c780345449b44db1b7d8de22e5eaa5fc7e | include/utils/annolist/AnnotationLib.py | python | AnnoRect.forceAspectRatio | (self, ratio, KeepHeight = False, KeepWidth = False) | force the Aspect ratio | force the Aspect ratio | [
"force",
"the",
"Aspect",
"ratio"
] | def forceAspectRatio(self, ratio, KeepHeight = False, KeepWidth = False):
"""force the Aspect ratio"""
if KeepWidth or ((not KeepHeight) and self.width() * 1.0 / self.height() > ratio):
# extend height
newHeight = self.width() * 1.0 / ratio
self.y1 = (self.centerY() - newHeight / 2.0)
self.y2 = (self.y1 + newHeight)
else:
# extend width
newWidth = self.height() * ratio
self.x1 = (self.centerX() - newWidth / 2.0)
self.x2 = (self.x1 + newWidth) | [
"def",
"forceAspectRatio",
"(",
"self",
",",
"ratio",
",",
"KeepHeight",
"=",
"False",
",",
"KeepWidth",
"=",
"False",
")",
":",
"if",
"KeepWidth",
"or",
"(",
"(",
"not",
"KeepHeight",
")",
"and",
"self",
".",
"width",
"(",
")",
"*",
"1.0",
"/",
"sel... | https://github.com/Zengyi-Qin/MonoGRNet/blob/bd8c36c780345449b44db1b7d8de22e5eaa5fc7e/include/utils/annolist/AnnotationLib.py#L252-L263 | ||
materialsproject/pymatgen | 8128f3062a334a2edd240e4062b5b9bdd1ae6f58 | pymatgen/io/cube.py | python | Cube.__init__ | (self, fname) | Initialize the cube object and store the data as self.data
Args:
fname (str): filename of the cube to read | Initialize the cube object and store the data as self.data | [
"Initialize",
"the",
"cube",
"object",
"and",
"store",
"the",
"data",
"as",
"self",
".",
"data"
] | def __init__(self, fname):
"""
Initialize the cube object and store the data as self.data
Args:
fname (str): filename of the cube to read
"""
f = zopen(fname, "rt")
# skip header lines
for i in range(2):
f.readline()
# number of atoms followed by the position of the origin of the volumetric data
line = f.readline().split()
self.natoms = int(line[0])
self.origin = np.array(list(map(float, line[1:])))
# The number of voxels along each axis (x, y, z) followed by the axis vector.
line = f.readline().split()
self.NX = int(line[0])
self.X = np.array([bohr_to_angstrom * float(l) for l in line[1:]])
self.dX = np.linalg.norm(self.X)
line = f.readline().split()
self.NY = int(line[0])
self.Y = np.array([bohr_to_angstrom * float(l) for l in line[1:]])
self.dY = np.linalg.norm(self.Y)
line = f.readline().split()
self.NZ = int(line[0])
self.Z = np.array([bohr_to_angstrom * float(l) for l in line[1:]])
self.dZ = np.linalg.norm(self.Z)
self.voxel_volume = abs(np.dot(np.cross(self.X, self.Y), self.Z))
self.volume = abs(np.dot(np.cross(self.X.dot(self.NZ), self.Y.dot(self.NY)), self.Z.dot(self.NZ)))
# The last section in the header is one line for each atom consisting of 5 numbers,
# the first is the atom number, second is charge,
# the last three are the x,y,z coordinates of the atom center.
self.sites = []
for i in range(self.natoms):
line = f.readline().split()
self.sites.append(Site(line[0], np.multiply(bohr_to_angstrom, list(map(float, line[2:])))))
self.structure = Structure(
lattice=[self.X * self.NX, self.Y * self.NY, self.Z * self.NZ],
species=[s.specie for s in self.sites],
coords=[s.coords for s in self.sites],
coords_are_cartesian=True,
)
# Volumetric data
self.data = np.reshape(np.array(f.read().split()).astype(float), (self.NX, self.NY, self.NZ)) | [
"def",
"__init__",
"(",
"self",
",",
"fname",
")",
":",
"f",
"=",
"zopen",
"(",
"fname",
",",
"\"rt\"",
")",
"# skip header lines",
"for",
"i",
"in",
"range",
"(",
"2",
")",
":",
"f",
".",
"readline",
"(",
")",
"# number of atoms followed by the position o... | https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/io/cube.py#L60-L113 | ||
automl/ConfigSpace | 4d69931de5540fc6be4230731ddebf6a25d2e1a8 | ConfigSpace/nx/classes/graph.py | python | Graph.adjacency_iter | (self) | return iter(self.adj.items()) | Return an iterator of (node, adjacency dict) tuples for all nodes.
This is the fastest way to look at every edge.
For directed graphs, only outgoing adjacencies are included.
Returns
-------
adj_iter : iterator
An iterator of (node, adjacency dictionary) for all nodes in
the graph.
See Also
--------
adjacency_list
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> [(n,nbrdict) for n,nbrdict in G.adjacency_iter()]
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})] | Return an iterator of (node, adjacency dict) tuples for all nodes. | [
"Return",
"an",
"iterator",
"of",
"(",
"node",
"adjacency",
"dict",
")",
"tuples",
"for",
"all",
"nodes",
"."
] | def adjacency_iter(self):
"""Return an iterator of (node, adjacency dict) tuples for all nodes.
This is the fastest way to look at every edge.
For directed graphs, only outgoing adjacencies are included.
Returns
-------
adj_iter : iterator
An iterator of (node, adjacency dictionary) for all nodes in
the graph.
See Also
--------
adjacency_list
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> [(n,nbrdict) for n,nbrdict in G.adjacency_iter()]
[(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
"""
return iter(self.adj.items()) | [
"def",
"adjacency_iter",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"adj",
".",
"items",
"(",
")",
")"
] | https://github.com/automl/ConfigSpace/blob/4d69931de5540fc6be4230731ddebf6a25d2e1a8/ConfigSpace/nx/classes/graph.py#L1179-L1203 | |
feincms/feincms | be35576fa86083a969ae56aaf848173d1a5a3c5d | feincms/module/page/models.py | python | BasePage.last_modified | (self, request) | return None | Generate a last modified date for this page.
Since a standard page has no way of knowing this, we always return
"no date" -- this is overridden by the changedate extension. | Generate a last modified date for this page.
Since a standard page has no way of knowing this, we always return
"no date" -- this is overridden by the changedate extension. | [
"Generate",
"a",
"last",
"modified",
"date",
"for",
"this",
"page",
".",
"Since",
"a",
"standard",
"page",
"has",
"no",
"way",
"of",
"knowing",
"this",
"we",
"always",
"return",
"no",
"date",
"--",
"this",
"is",
"overridden",
"by",
"the",
"changedate",
"... | def last_modified(self, request):
"""
Generate a last modified date for this page.
Since a standard page has no way of knowing this, we always return
"no date" -- this is overridden by the changedate extension.
"""
return None | [
"def",
"last_modified",
"(",
"self",
",",
"request",
")",
":",
"return",
"None"
] | https://github.com/feincms/feincms/blob/be35576fa86083a969ae56aaf848173d1a5a3c5d/feincms/module/page/models.py#L337-L343 | |
apache/libcloud | 90971e17bfd7b6bb97b2489986472c531cc8e140 | libcloud/compute/base.py | python | NodeDriver.start_node | (self, node) | Start a node.
:param node: The node to be started
:type node: :class:`.Node`
:return: True if the start was successful, otherwise False
:rtype: ``bool`` | Start a node. | [
"Start",
"a",
"node",
"."
] | def start_node(self, node):
# type: (Node) -> bool
"""
Start a node.
:param node: The node to be started
:type node: :class:`.Node`
:return: True if the start was successful, otherwise False
:rtype: ``bool``
"""
raise NotImplementedError("start_node not implemented for this driver") | [
"def",
"start_node",
"(",
"self",
",",
"node",
")",
":",
"# type: (Node) -> bool",
"raise",
"NotImplementedError",
"(",
"\"start_node not implemented for this driver\"",
")"
] | https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/base.py#L1309-L1320 | ||
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/models/v1beta1_policy_rules_with_subjects.py | python | V1beta1PolicyRulesWithSubjects.non_resource_rules | (self, non_resource_rules) | Sets the non_resource_rules of this V1beta1PolicyRulesWithSubjects.
`nonResourceRules` is a list of NonResourcePolicyRules that identify matching requests according to their verb and the target non-resource URL. # noqa: E501
:param non_resource_rules: The non_resource_rules of this V1beta1PolicyRulesWithSubjects. # noqa: E501
:type: list[V1beta1NonResourcePolicyRule] | Sets the non_resource_rules of this V1beta1PolicyRulesWithSubjects. | [
"Sets",
"the",
"non_resource_rules",
"of",
"this",
"V1beta1PolicyRulesWithSubjects",
"."
] | def non_resource_rules(self, non_resource_rules):
"""Sets the non_resource_rules of this V1beta1PolicyRulesWithSubjects.
`nonResourceRules` is a list of NonResourcePolicyRules that identify matching requests according to their verb and the target non-resource URL. # noqa: E501
:param non_resource_rules: The non_resource_rules of this V1beta1PolicyRulesWithSubjects. # noqa: E501
:type: list[V1beta1NonResourcePolicyRule]
"""
self._non_resource_rules = non_resource_rules | [
"def",
"non_resource_rules",
"(",
"self",
",",
"non_resource_rules",
")",
":",
"self",
".",
"_non_resource_rules",
"=",
"non_resource_rules"
] | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1beta1_policy_rules_with_subjects.py#L76-L85 | ||
Flask-Middleware/flask-security | 9ebc0342c47c0eed19246e143e580d06cb680580 | flask_security/utils.py | python | pwned | (password: str) | return entries.get(sha1[5:].upper(), 0) | Check password against pwnedpasswords API using k-Anonymity.
https://haveibeenpwned.com/API/v3
:return: Count of password in DB (0 means hasn't been compromised)
Can raise HTTPError
.. versionadded:: 3.4.0 | Check password against pwnedpasswords API using k-Anonymity.
https://haveibeenpwned.com/API/v3 | [
"Check",
"password",
"against",
"pwnedpasswords",
"API",
"using",
"k",
"-",
"Anonymity",
".",
"https",
":",
"//",
"haveibeenpwned",
".",
"com",
"/",
"API",
"/",
"v3"
] | def pwned(password: str) -> int:
"""
Check password against pwnedpasswords API using k-Anonymity.
https://haveibeenpwned.com/API/v3
:return: Count of password in DB (0 means hasn't been compromised)
Can raise HTTPError
.. versionadded:: 3.4.0
"""
def convert_password_tuple(value):
hash_suffix, count = value.split(":")
return hash_suffix, int(count)
sha1 = hashlib.sha1(password.encode("utf8")).hexdigest()
req = urllib.request.Request(
url=f"https://api.pwnedpasswords.com/range/{sha1[:5].upper()}",
headers={"User-Agent": "Flask-Security (Python)"},
)
# Might raise HTTPError
with urllib.request.urlopen(req) as f:
response = f.read()
raw = response.decode("utf-8-sig")
entries = dict(map(convert_password_tuple, raw.upper().split("\r\n")))
return entries.get(sha1[5:].upper(), 0) | [
"def",
"pwned",
"(",
"password",
":",
"str",
")",
"->",
"int",
":",
"def",
"convert_password_tuple",
"(",
"value",
")",
":",
"hash_suffix",
",",
"count",
"=",
"value",
".",
"split",
"(",
"\":\"",
")",
"return",
"hash_suffix",
",",
"int",
"(",
"count",
... | https://github.com/Flask-Middleware/flask-security/blob/9ebc0342c47c0eed19246e143e580d06cb680580/flask_security/utils.py#L1212-L1241 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/inspect.py | python | getargs | (co) | return Arguments(args + kwonlyargs, varargs, varkw) | Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None. | Get information about the arguments accepted by a code object. | [
"Get",
"information",
"about",
"the",
"arguments",
"accepted",
"by",
"a",
"code",
"object",
"."
] | def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None."""
if not iscode(co):
raise TypeError('{!r} is not a code object'.format(co))
names = co.co_varnames
nargs = co.co_argcount
nkwargs = co.co_kwonlyargcount
args = list(names[:nargs])
kwonlyargs = list(names[nargs:nargs+nkwargs])
step = 0
nargs += nkwargs
varargs = None
if co.co_flags & CO_VARARGS:
varargs = co.co_varnames[nargs]
nargs = nargs + 1
varkw = None
if co.co_flags & CO_VARKEYWORDS:
varkw = co.co_varnames[nargs]
return Arguments(args + kwonlyargs, varargs, varkw) | [
"def",
"getargs",
"(",
"co",
")",
":",
"if",
"not",
"iscode",
"(",
"co",
")",
":",
"raise",
"TypeError",
"(",
"'{!r} is not a code object'",
".",
"format",
"(",
"co",
")",
")",
"names",
"=",
"co",
".",
"co_varnames",
"nargs",
"=",
"co",
".",
"co_argcou... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/inspect.py#L1190-L1215 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.