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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sqlalchemy/sqlalchemy | eb716884a4abcabae84a6aaba105568e925b7d27 | lib/sqlalchemy/dialects/mssql/base.py | python | MSSQLCompiler.get_select_precolumns | (self, select, **kw) | return s | MS-SQL puts TOP, it's version of LIMIT here | MS-SQL puts TOP, it's version of LIMIT here | [
"MS",
"-",
"SQL",
"puts",
"TOP",
"it",
"s",
"version",
"of",
"LIMIT",
"here"
] | def get_select_precolumns(self, select, **kw):
"""MS-SQL puts TOP, it's version of LIMIT here"""
s = super(MSSQLCompiler, self).get_select_precolumns(select, **kw)
if select._has_row_limiting_clause and self._use_top(select):
# ODBC drivers and possibly others
# don't support bind params in the SELECT clause on SQL Server.
# so have to use literal here.
kw["literal_execute"] = True
s += "TOP %s " % self.process(
self._get_limit_or_fetch(select), **kw
)
if select._fetch_clause is not None:
if select._fetch_clause_options["percent"]:
s += "PERCENT "
if select._fetch_clause_options["with_ties"]:
s += "WITH TIES "
return s | [
"def",
"get_select_precolumns",
"(",
"self",
",",
"select",
",",
"*",
"*",
"kw",
")",
":",
"s",
"=",
"super",
"(",
"MSSQLCompiler",
",",
"self",
")",
".",
"get_select_precolumns",
"(",
"select",
",",
"*",
"*",
"kw",
")",
"if",
"select",
".",
"_has_row_... | https://github.com/sqlalchemy/sqlalchemy/blob/eb716884a4abcabae84a6aaba105568e925b7d27/lib/sqlalchemy/dialects/mssql/base.py#L1812-L1831 | |
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/cherrypy/lib/auth_digest.py | python | digest_auth | (realm, get_ha1, key, debug=False) | A CherryPy tool which hooks at before_handler to perform
HTTP Digest Access Authentication, as specified in :rfc:`2617`.
If the request has an 'authorization' header with a 'Digest' scheme,
this tool authenticates the credentials supplied in that header.
If the request has no 'authorization' header, or if it does but the
scheme is not "Digest", or if authentication fails, the tool sends
a 401 response with a 'WWW-Authenticate' Digest header.
realm
A string containing the authentication realm.
get_ha1
A callable which looks up a username in a credentials store
and returns the HA1 string, which is defined in the RFC to be
MD5(username : realm : password). The function's signature is:
``get_ha1(realm, username)``
where username is obtained from the request's 'authorization' header.
If username is not found in the credentials store, get_ha1() returns
None.
key
A secret string known only to the server, used in the synthesis
of nonces. | A CherryPy tool which hooks at before_handler to perform
HTTP Digest Access Authentication, as specified in :rfc:`2617`. | [
"A",
"CherryPy",
"tool",
"which",
"hooks",
"at",
"before_handler",
"to",
"perform",
"HTTP",
"Digest",
"Access",
"Authentication",
"as",
"specified",
"in",
":",
"rfc",
":",
"2617",
"."
] | def digest_auth(realm, get_ha1, key, debug=False):
"""A CherryPy tool which hooks at before_handler to perform
HTTP Digest Access Authentication, as specified in :rfc:`2617`.
If the request has an 'authorization' header with a 'Digest' scheme,
this tool authenticates the credentials supplied in that header.
If the request has no 'authorization' header, or if it does but the
scheme is not "Digest", or if authentication fails, the tool sends
a 401 response with a 'WWW-Authenticate' Digest header.
realm
A string containing the authentication realm.
get_ha1
A callable which looks up a username in a credentials store
and returns the HA1 string, which is defined in the RFC to be
MD5(username : realm : password). The function's signature is:
``get_ha1(realm, username)``
where username is obtained from the request's 'authorization' header.
If username is not found in the credentials store, get_ha1() returns
None.
key
A secret string known only to the server, used in the synthesis
of nonces.
"""
request = cherrypy.serving.request
auth_header = request.headers.get('authorization')
nonce_is_stale = False
if auth_header is not None:
try:
auth = HttpDigestAuthorization(
auth_header, request.method, debug=debug)
except ValueError:
raise cherrypy.HTTPError(
400, "The Authorization header could not be parsed.")
if debug:
TRACE(str(auth))
if auth.validate_nonce(realm, key):
ha1 = get_ha1(realm, auth.username)
if ha1 is not None:
# note that for request.body to be available we need to
# hook in at before_handler, not on_start_resource like
# 3.1.x digest_auth does.
digest = auth.request_digest(ha1, entity_body=request.body)
if digest == auth.response: # authenticated
if debug:
TRACE("digest matches auth.response")
# Now check if nonce is stale.
# The choice of ten minutes' lifetime for nonce is somewhat
# arbitrary
nonce_is_stale = auth.is_nonce_stale(max_age_seconds=600)
if not nonce_is_stale:
request.login = auth.username
if debug:
TRACE("authentication of %s successful" %
auth.username)
return
# Respond with 401 status and a WWW-Authenticate header
header = www_authenticate(realm, key, stale=nonce_is_stale)
if debug:
TRACE(header)
cherrypy.serving.response.headers['WWW-Authenticate'] = header
raise cherrypy.HTTPError(
401, "You are not authorized to access that resource") | [
"def",
"digest_auth",
"(",
"realm",
",",
"get_ha1",
",",
"key",
",",
"debug",
"=",
"False",
")",
":",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"auth_header",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'authorization'",
")",
"non... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/lib/auth_digest.py#L321-L390 | ||
wistbean/learn_python3_spider | 73c873f4845f4385f097e5057407d03dd37a117b | stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/endpoints.py | python | _WrappingFactory.clientConnectionFailed | (self, connector, reason) | Errback the C{self._onConnection} L{Deferred} when the
client connection fails. | Errback the C{self._onConnection} L{Deferred} when the
client connection fails. | [
"Errback",
"the",
"C",
"{",
"self",
".",
"_onConnection",
"}",
"L",
"{",
"Deferred",
"}",
"when",
"the",
"client",
"connection",
"fails",
"."
] | def clientConnectionFailed(self, connector, reason):
"""
Errback the C{self._onConnection} L{Deferred} when the
client connection fails.
"""
if not self._onConnection.called:
self._onConnection.errback(reason) | [
"def",
"clientConnectionFailed",
"(",
"self",
",",
"connector",
",",
"reason",
")",
":",
"if",
"not",
"self",
".",
"_onConnection",
".",
"called",
":",
"self",
".",
"_onConnection",
".",
"errback",
"(",
"reason",
")"
] | https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/endpoints.py#L264-L270 | ||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/roformer/modeling_flax_roformer.py | python | FlaxRoFormerEmbeddings.__call__ | (self, input_ids, token_type_ids, attention_mask, deterministic: bool = True) | return hidden_states | [] | def __call__(self, input_ids, token_type_ids, attention_mask, deterministic: bool = True):
# Embed
inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
# Sum all embeddings
hidden_states = inputs_embeds + token_type_embeddings
# Layer Norm
hidden_states = self.LayerNorm(hidden_states)
hidden_states = self.dropout(hidden_states, deterministic=deterministic)
return hidden_states | [
"def",
"__call__",
"(",
"self",
",",
"input_ids",
",",
"token_type_ids",
",",
"attention_mask",
",",
"deterministic",
":",
"bool",
"=",
"True",
")",
":",
"# Embed",
"inputs_embeds",
"=",
"self",
".",
"word_embeddings",
"(",
"input_ids",
".",
"astype",
"(",
"... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/roformer/modeling_flax_roformer.py#L162-L173 | |||
pydata/pandas-datareader | 3f1d590e6e67cf30aa516d3b1f1921b5c45ccc4b | pandas_datareader/tiingo.py | python | TiingoMetaDataReader.__init__ | (
self,
symbols,
start=None,
end=None,
retry_count=3,
pause=0.1,
timeout=30,
session=None,
freq=None,
api_key=None,
) | [] | def __init__(
self,
symbols,
start=None,
end=None,
retry_count=3,
pause=0.1,
timeout=30,
session=None,
freq=None,
api_key=None,
):
super(TiingoMetaDataReader, self).__init__(
symbols, start, end, retry_count, pause, timeout, session, freq, api_key
)
self._concat_axis = 1 | [
"def",
"__init__",
"(",
"self",
",",
"symbols",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"retry_count",
"=",
"3",
",",
"pause",
"=",
"0.1",
",",
"timeout",
"=",
"30",
",",
"session",
"=",
"None",
",",
"freq",
"=",
"None",
",",
"ap... | https://github.com/pydata/pandas-datareader/blob/3f1d590e6e67cf30aa516d3b1f1921b5c45ccc4b/pandas_datareader/tiingo.py#L262-L277 | ||||
spack/spack | 675210bd8bd1c5d32ad1cc83d898fb43b569ed74 | lib/spack/spack/cmd/__init__.py | python | matching_spec_from_env | (spec) | Returns a concrete spec, matching what is available in the environment.
If no matching spec is found in the environment (or if no environment is
active), this will return the given spec but concretized. | Returns a concrete spec, matching what is available in the environment.
If no matching spec is found in the environment (or if no environment is
active), this will return the given spec but concretized. | [
"Returns",
"a",
"concrete",
"spec",
"matching",
"what",
"is",
"available",
"in",
"the",
"environment",
".",
"If",
"no",
"matching",
"spec",
"is",
"found",
"in",
"the",
"environment",
"(",
"or",
"if",
"no",
"environment",
"is",
"active",
")",
"this",
"will"... | def matching_spec_from_env(spec):
"""
Returns a concrete spec, matching what is available in the environment.
If no matching spec is found in the environment (or if no environment is
active), this will return the given spec but concretized.
"""
env = ev.active_environment()
if env:
return env.matching_spec(spec) or spec.concretized()
else:
return spec.concretized() | [
"def",
"matching_spec_from_env",
"(",
"spec",
")",
":",
"env",
"=",
"ev",
".",
"active_environment",
"(",
")",
"if",
"env",
":",
"return",
"env",
".",
"matching_spec",
"(",
"spec",
")",
"or",
"spec",
".",
"concretized",
"(",
")",
"else",
":",
"return",
... | https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/cmd/__init__.py#L186-L196 | ||
hottbox/hottbox | 26580018ec6d38a1b08266c04ce4408c9e276130 | hottbox/core/structures.py | python | Tensor.order | (self) | return self.data.ndim | Order of a tensor
Returns
-------
int | Order of a tensor | [
"Order",
"of",
"a",
"tensor"
] | def order(self):
""" Order of a tensor
Returns
-------
int
"""
return self.data.ndim | [
"def",
"order",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"ndim"
] | https://github.com/hottbox/hottbox/blob/26580018ec6d38a1b08266c04ce4408c9e276130/hottbox/core/structures.py#L384-L391 | |
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/twitter/api.py | python | Api.GetRetweeters | (self,
status_id,
cursor=None,
count=100,
stringify_ids=False) | return result | Returns a collection of up to 100 user IDs belonging to users who have
retweeted the tweet specified by the status_id parameter.
Args:
status_id:
the tweet's numerical ID
cursor:
breaks the ids into pages of no more than 100.
stringify_ids:
returns the IDs as unicode strings. [Optional]
Returns:
A list of user IDs | Returns a collection of up to 100 user IDs belonging to users who have
retweeted the tweet specified by the status_id parameter. | [
"Returns",
"a",
"collection",
"of",
"up",
"to",
"100",
"user",
"IDs",
"belonging",
"to",
"users",
"who",
"have",
"retweeted",
"the",
"tweet",
"specified",
"by",
"the",
"status_id",
"parameter",
"."
] | def GetRetweeters(self,
status_id,
cursor=None,
count=100,
stringify_ids=False):
"""Returns a collection of up to 100 user IDs belonging to users who have
retweeted the tweet specified by the status_id parameter.
Args:
status_id:
the tweet's numerical ID
cursor:
breaks the ids into pages of no more than 100.
stringify_ids:
returns the IDs as unicode strings. [Optional]
Returns:
A list of user IDs
"""
url = '%s/statuses/retweeters/ids.json' % (self.base_url)
parameters = {
'id': enf_type('id', int, status_id),
'stringify_ids': enf_type('stringify_ids', bool, stringify_ids),
'count': count,
}
result = []
total_count = 0
while True:
if cursor:
try:
parameters['cursor'] = int(cursor)
except ValueError:
raise TwitterError({'message': "cursor must be an integer"})
resp = self._RequestUrl(url, 'GET', data=parameters)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
result += [x for x in data['ids']]
if 'next_cursor' in data:
if data['next_cursor'] == 0 or data['next_cursor'] == data['previous_cursor']:
break
else:
cursor = data['next_cursor']
total_count -= len(data['ids'])
if total_count < 1:
break
else:
break
return result | [
"def",
"GetRetweeters",
"(",
"self",
",",
"status_id",
",",
"cursor",
"=",
"None",
",",
"count",
"=",
"100",
",",
"stringify_ids",
"=",
"False",
")",
":",
"url",
"=",
"'%s/statuses/retweeters/ids.json'",
"%",
"(",
"self",
".",
"base_url",
")",
"parameters",
... | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/twitter/api.py#L1646-L1695 | |
playframework/play1 | 0ecac3bc2421ae2dbec27a368bf671eda1c9cba5 | python/Lib/_abcoll.py | python | Set._from_iterable | (cls, it) | return cls(it) | Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input. | Construct an instance of the class from any iterable input. | [
"Construct",
"an",
"instance",
"of",
"the",
"class",
"from",
"any",
"iterable",
"input",
"."
] | def _from_iterable(cls, it):
'''Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.
'''
return cls(it) | [
"def",
"_from_iterable",
"(",
"cls",
",",
"it",
")",
":",
"return",
"cls",
"(",
"it",
")"
] | https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/_abcoll.py#L189-L195 | |
coursera-dl/coursera-dl | 10ba6b8d8c30798a45d45db2dc147edf3b455350 | coursera/credentials.py | python | get_config_paths | (config_name) | return res | Return a list of config files paths to try in order, given config file
name and possibly a user-specified path.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way" of doing
things.
A brief recap of the situation (all file paths are written in Unix
convention):
1. By default, Windows does not define a $HOME path. However, some
people might define one manually, and many command-line tools imported
from Unix will search the $HOME environment variable first. This
includes MSYSGit tools (bash, ssh, ...) and Emacs.
2. Windows defines two 'user paths': $USERPROFILE, and the
concatenation of the two variables $HOMEDRIVE and $HOMEPATH. Both of
these paths point by default to the same location, e.g.
C:\\Users\\Username
3. $USERPROFILE cannot be changed, however $HOMEDRIVE and $HOMEPATH
can be changed. They are originally intended to be the equivalent of
the $HOME path, but there are many known issues with them
4. As for the name of the file itself, most of the tools ported from
Unix will use the standard '.dotfile' scheme, but some of these will
instead use "_dotfile". Of the latter, the two notable exceptions are
vim, which will first try '_vimrc' before '.vimrc' (but it will try
both) and git, which will require the user to name its netrc file
'_netrc'.
Relevant links :
http://markmail.org/message/i33ldu4xl5aterrr
http://markmail.org/message/wbzs4gmtvkbewgxi
http://stackoverflow.com/questions/6031214/
Because the whole thing is a mess, I suggest we tried various sensible
defaults until we succeed or have depleted all possibilities. | Return a list of config files paths to try in order, given config file
name and possibly a user-specified path. | [
"Return",
"a",
"list",
"of",
"config",
"files",
"paths",
"to",
"try",
"in",
"order",
"given",
"config",
"file",
"name",
"and",
"possibly",
"a",
"user",
"-",
"specified",
"path",
"."
] | def get_config_paths(config_name): # pragma: no test
"""
Return a list of config files paths to try in order, given config file
name and possibly a user-specified path.
For Windows platforms, there are several paths that can be tried to
retrieve the netrc file. There is, however, no "standard way" of doing
things.
A brief recap of the situation (all file paths are written in Unix
convention):
1. By default, Windows does not define a $HOME path. However, some
people might define one manually, and many command-line tools imported
from Unix will search the $HOME environment variable first. This
includes MSYSGit tools (bash, ssh, ...) and Emacs.
2. Windows defines two 'user paths': $USERPROFILE, and the
concatenation of the two variables $HOMEDRIVE and $HOMEPATH. Both of
these paths point by default to the same location, e.g.
C:\\Users\\Username
3. $USERPROFILE cannot be changed, however $HOMEDRIVE and $HOMEPATH
can be changed. They are originally intended to be the equivalent of
the $HOME path, but there are many known issues with them
4. As for the name of the file itself, most of the tools ported from
Unix will use the standard '.dotfile' scheme, but some of these will
instead use "_dotfile". Of the latter, the two notable exceptions are
vim, which will first try '_vimrc' before '.vimrc' (but it will try
both) and git, which will require the user to name its netrc file
'_netrc'.
Relevant links :
http://markmail.org/message/i33ldu4xl5aterrr
http://markmail.org/message/wbzs4gmtvkbewgxi
http://stackoverflow.com/questions/6031214/
Because the whole thing is a mess, I suggest we tried various sensible
defaults until we succeed or have depleted all possibilities.
"""
if platform.system() != 'Windows':
return [None]
# Now, we only treat the case of Windows
env_vars = [["HOME"],
["HOMEDRIVE", "HOMEPATH"],
["USERPROFILE"],
["SYSTEMDRIVE"]]
env_dirs = []
for var_list in env_vars:
var_values = [_getenv_or_empty(var) for var in var_list]
directory = ''.join(var_values)
if not directory:
logging.debug('Environment var(s) %s not defined, skipping',
var_list)
else:
env_dirs.append(directory)
additional_dirs = ["C:", ""]
all_dirs = env_dirs + additional_dirs
leading_chars = [".", "_"]
res = [''.join([directory, os.sep, lc, config_name])
for directory in all_dirs
for lc in leading_chars]
return res | [
"def",
"get_config_paths",
"(",
"config_name",
")",
":",
"# pragma: no test",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Windows'",
":",
"return",
"[",
"None",
"]",
"# Now, we only treat the case of Windows",
"env_vars",
"=",
"[",
"[",
"\"HOME\"",
"]",
"... | https://github.com/coursera-dl/coursera-dl/blob/10ba6b8d8c30798a45d45db2dc147edf3b455350/coursera/credentials.py#L37-L110 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/freedompro/binary_sensor.py | python | Device._handle_coordinator_update | (self) | Handle updated data from the coordinator. | Handle updated data from the coordinator. | [
"Handle",
"updated",
"data",
"from",
"the",
"coordinator",
"."
] | def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
device = next(
(
device
for device in self.coordinator.data
if device["uid"] == self.unique_id
),
None,
)
if device is not None and "state" in device:
state = device["state"]
self._attr_is_on = state[DEVICE_KEY_MAP[self._type]]
super()._handle_coordinator_update() | [
"def",
"_handle_coordinator_update",
"(",
"self",
")",
"->",
"None",
":",
"device",
"=",
"next",
"(",
"(",
"device",
"for",
"device",
"in",
"self",
".",
"coordinator",
".",
"data",
"if",
"device",
"[",
"\"uid\"",
"]",
"==",
"self",
".",
"unique_id",
")",... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/freedompro/binary_sensor.py#L63-L76 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/algebras/steenrod/steenrod_algebra_bases.py | python | steenrod_basis_error_check | (dim, p, **kwds) | This performs crude error checking.
INPUT:
- ``dim`` - non-negative integer
- ``p`` - positive prime number
OUTPUT: None
This checks to see if the different bases have the same length, and
if the change-of-basis matrices are invertible. If something goes
wrong, an error message is printed.
This function checks at the prime ``p`` as the dimension goes up
from 0 to ``dim``.
If you set the Sage verbosity level to a positive integer (using
``set_verbose(n)``), then some extra messages will be printed.
EXAMPLES::
sage: from sage.algebras.steenrod.steenrod_algebra_bases import steenrod_basis_error_check
sage: steenrod_basis_error_check(15,2) # long time
sage: steenrod_basis_error_check(15,2,generic=True) # long time
sage: steenrod_basis_error_check(40,3) # long time
sage: steenrod_basis_error_check(80,5) # long time | This performs crude error checking. | [
"This",
"performs",
"crude",
"error",
"checking",
"."
] | def steenrod_basis_error_check(dim, p, **kwds):
"""
This performs crude error checking.
INPUT:
- ``dim`` - non-negative integer
- ``p`` - positive prime number
OUTPUT: None
This checks to see if the different bases have the same length, and
if the change-of-basis matrices are invertible. If something goes
wrong, an error message is printed.
This function checks at the prime ``p`` as the dimension goes up
from 0 to ``dim``.
If you set the Sage verbosity level to a positive integer (using
``set_verbose(n)``), then some extra messages will be printed.
EXAMPLES::
sage: from sage.algebras.steenrod.steenrod_algebra_bases import steenrod_basis_error_check
sage: steenrod_basis_error_check(15,2) # long time
sage: steenrod_basis_error_check(15,2,generic=True) # long time
sage: steenrod_basis_error_check(40,3) # long time
sage: steenrod_basis_error_check(80,5) # long time
"""
from sage.misc.verbose import verbose
generic = kwds.get('generic', False if p==2 else True )
if not generic:
bases = ('adem','woody', 'woodz', 'wall', 'arnona', 'arnonc',
'pst_rlex', 'pst_llex', 'pst_deg', 'pst_revz',
'comm_rlex', 'comm_llex', 'comm_deg', 'comm_revz')
else:
bases = ('adem',
'pst_rlex', 'pst_llex', 'pst_deg', 'pst_revz',
'comm_rlex', 'comm_llex', 'comm_deg', 'comm_revz')
for i in range(dim):
if i % 5 == 0:
verbose("up to dimension %s"%i)
milnor_dim = len(steenrod_algebra_basis.f(i,'milnor',p=p,generic=generic))
for B in bases:
if milnor_dim != len(steenrod_algebra_basis.f(i,B,p,generic=generic)):
print("problem with milnor/{} in dimension {}".format(B, i))
mat = convert_to_milnor_matrix.f(i,B,p,generic=generic)
if mat.nrows() != 0 and not mat.is_invertible():
print("%s invertibility problem in dim %s at p=%s" % (B, i, p))
verbose("done checking, no profiles")
bases = ('pst_rlex', 'pst_llex', 'pst_deg', 'pst_revz')
if not generic:
profiles = [(4,3,2,1), (2,2,3,1,1), (0,0,0,2)]
else:
profiles = [((3,2,1), ()), ((), (2,1,2)), ((3,2,1), (2,2,2,2))]
for i in range(dim):
if i % 5 == 0:
verbose("up to dimension %s"%i)
for pro in profiles:
milnor_dim = len(steenrod_algebra_basis.f(i,'milnor',p=p,profile=pro,generic=generic))
for B in bases:
if milnor_dim != len(steenrod_algebra_basis.f(i,B,p,profile=pro,generic=generic)):
print("problem with milnor/%s in dimension %s with profile %s" % (B, i, pro))
verbose("done checking with profiles") | [
"def",
"steenrod_basis_error_check",
"(",
"dim",
",",
"p",
",",
"*",
"*",
"kwds",
")",
":",
"from",
"sage",
".",
"misc",
".",
"verbose",
"import",
"verbose",
"generic",
"=",
"kwds",
".",
"get",
"(",
"'generic'",
",",
"False",
"if",
"p",
"==",
"2",
"e... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/algebras/steenrod/steenrod_algebra_bases.py#L1090-L1159 | ||
lephong/mulrel-nel | db14942450f72c87a4d46349860e96ef2edf353d | nel/vocabulary.py | python | Vocabulary.normalize | (token, lower=LOWER, digit_0=DIGIT_0) | [] | def normalize(token, lower=LOWER, digit_0=DIGIT_0):
if token in [Vocabulary.unk_token, "<s>", "</s>"]:
return token
elif token in BRACKETS:
token = BRACKETS[token]
else:
if digit_0:
token = re.sub("[0-9]", "0", token)
if lower:
return token.lower()
else:
return token | [
"def",
"normalize",
"(",
"token",
",",
"lower",
"=",
"LOWER",
",",
"digit_0",
"=",
"DIGIT_0",
")",
":",
"if",
"token",
"in",
"[",
"Vocabulary",
".",
"unk_token",
",",
"\"<s>\"",
",",
"\"</s>\"",
"]",
":",
"return",
"token",
"elif",
"token",
"in",
"BRAC... | https://github.com/lephong/mulrel-nel/blob/db14942450f72c87a4d46349860e96ef2edf353d/nel/vocabulary.py#L21-L33 | ||||
kozistr/Awesome-GANs | b4b9a3b8c3fd1d32c864dc5655d80c0650aebee1 | awesome_gans/srgan/srgan_model.py | python | SRGAN.discriminator | (self, x, reuse=None) | # Following a network architecture referred in the paper
:param x: Input images (-1, 384, 384, 3)
:param reuse: re-usability
:return: HR (High Resolution) or SR (Super Resolution) images | # Following a network architecture referred in the paper
:param x: Input images (-1, 384, 384, 3)
:param reuse: re-usability
:return: HR (High Resolution) or SR (Super Resolution) images | [
"#",
"Following",
"a",
"network",
"architecture",
"referred",
"in",
"the",
"paper",
":",
"param",
"x",
":",
"Input",
"images",
"(",
"-",
"1",
"384",
"384",
"3",
")",
":",
"param",
"reuse",
":",
"re",
"-",
"usability",
":",
"return",
":",
"HR",
"(",
... | def discriminator(self, x, reuse=None):
"""
# Following a network architecture referred in the paper
:param x: Input images (-1, 384, 384, 3)
:param reuse: re-usability
:return: HR (High Resolution) or SR (Super Resolution) images
"""
with tf.variable_scope("discriminator", reuse=reuse):
x = t.conv2d(x, self.df_dim, 3, 1, name='n64s1-1')
x = tf.nn.leaky_relu(x)
strides = [2, 1]
filters = [1, 2, 2, 4, 4, 8, 8]
for i, f in enumerate(filters):
x = t.conv2d(x, f=f, k=3, s=strides[i % 2], name='n%ds%d-%d' % (f, strides[i % 2], i + 1))
x = t.batch_norm(x, name='n%d-bn-%d' % (f, i + 1))
x = tf.nn.leaky_relu(x)
x = tf.layers.flatten(x) # (-1, 96 * 96 * 64)
x = t.dense(x, 1024, name='disc-fc-1')
x = tf.nn.leaky_relu(x)
x = t.dense(x, 1, name='disc-fc-2')
# x = tf.nn.sigmoid(x)
return x | [
"def",
"discriminator",
"(",
"self",
",",
"x",
",",
"reuse",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"discriminator\"",
",",
"reuse",
"=",
"reuse",
")",
":",
"x",
"=",
"t",
".",
"conv2d",
"(",
"x",
",",
"self",
".",
"df_d... | https://github.com/kozistr/Awesome-GANs/blob/b4b9a3b8c3fd1d32c864dc5655d80c0650aebee1/awesome_gans/srgan/srgan_model.py#L108-L134 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/polys/orthopolys.py | python | dup_chebyshevt | (n, K) | return seq[n] | Low-level implementation of Chebyshev polynomials of the 1st kind. | Low-level implementation of Chebyshev polynomials of the 1st kind. | [
"Low",
"-",
"level",
"implementation",
"of",
"Chebyshev",
"polynomials",
"of",
"the",
"1st",
"kind",
"."
] | def dup_chebyshevt(n, K):
"""Low-level implementation of Chebyshev polynomials of the 1st kind. """
seq = [[K.one], [K.one, K.zero]]
for i in xrange(2, n + 1):
a = dup_mul_ground(dup_lshift(seq[-1], 1, K), K(2), K)
seq.append(dup_sub(a, seq[-2], K))
return seq[n] | [
"def",
"dup_chebyshevt",
"(",
"n",
",",
"K",
")",
":",
"seq",
"=",
"[",
"[",
"K",
".",
"one",
"]",
",",
"[",
"K",
".",
"one",
",",
"K",
".",
"zero",
"]",
"]",
"for",
"i",
"in",
"xrange",
"(",
"2",
",",
"n",
"+",
"1",
")",
":",
"a",
"=",... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/polys/orthopolys.py#L93-L101 | |
tendenci/tendenci | 0f2c348cc0e7d41bc56f50b00ce05544b083bf1d | tendenci/apps/social_services/models.py | python | ReliefAssessment.get_address | (self) | return "%s %s %s, %s %s %s" % (
self.address,
self.address2,
self.city,
self.state,
self.zipcode,
self.country
) | [] | def get_address(self):
return "%s %s %s, %s %s %s" % (
self.address,
self.address2,
self.city,
self.state,
self.zipcode,
self.country
) | [
"def",
"get_address",
"(",
"self",
")",
":",
"return",
"\"%s %s %s, %s %s %s\"",
"%",
"(",
"self",
".",
"address",
",",
"self",
".",
"address2",
",",
"self",
".",
"city",
",",
"self",
".",
"state",
",",
"self",
".",
"zipcode",
",",
"self",
".",
"countr... | https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/social_services/models.py#L162-L170 | |||
brightmart/multi-label_classification | b5febe17eaf9d937d71cabab56c5da48ee68f7b5 | run_classifier.py | python | file_based_input_fn_builder | (input_file, seq_length, is_training,
drop_remainder) | return input_fn | Creates an `input_fn` closure to be passed to TPUEstimator. | Creates an `input_fn` closure to be passed to TPUEstimator. | [
"Creates",
"an",
"input_fn",
"closure",
"to",
"be",
"passed",
"to",
"TPUEstimator",
"."
] | def file_based_input_fn_builder(input_file, seq_length, is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"label_ids": tf.FixedLenFeature([], tf.int64),
"is_real_example": tf.FixedLenFeature([], tf.int64),
}
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn | [
"def",
"file_based_input_fn_builder",
"(",
"input_file",
",",
"seq_length",
",",
"is_training",
",",
"drop_remainder",
")",
":",
"name_to_features",
"=",
"{",
"\"input_ids\"",
":",
"tf",
".",
"FixedLenFeature",
"(",
"[",
"seq_length",
"]",
",",
"tf",
".",
"int64... | https://github.com/brightmart/multi-label_classification/blob/b5febe17eaf9d937d71cabab56c5da48ee68f7b5/run_classifier.py#L507-L552 | |
SheffieldML/GPy | bb1bc5088671f9316bc92a46d356734e34c2d5c0 | GPy/plotting/gpy_plot/plot_util.py | python | get_x_y_var | (model) | return X, X_variance, Y | Either the the data from a model as
X the inputs,
X_variance the variance of the inputs ([default: None])
and Y the outputs
If (X, X_variance, Y) is given, this just returns.
:returns: (X, X_variance, Y) | Either the the data from a model as
X the inputs,
X_variance the variance of the inputs ([default: None])
and Y the outputs | [
"Either",
"the",
"the",
"data",
"from",
"a",
"model",
"as",
"X",
"the",
"inputs",
"X_variance",
"the",
"variance",
"of",
"the",
"inputs",
"(",
"[",
"default",
":",
"None",
"]",
")",
"and",
"Y",
"the",
"outputs"
] | def get_x_y_var(model):
"""
Either the the data from a model as
X the inputs,
X_variance the variance of the inputs ([default: None])
and Y the outputs
If (X, X_variance, Y) is given, this just returns.
:returns: (X, X_variance, Y)
"""
# model given
if hasattr(model, 'has_uncertain_inputs') and model.has_uncertain_inputs():
X = model.X.mean.values
X_variance = model.X.variance.values
else:
try:
X = model.X.values
except AttributeError:
X = model.X
X_variance = None
try:
Y = model.Y.values
except AttributeError:
Y = model.Y
if isinstance(model, WarpedGP) and not model.predict_in_warped_space:
Y = model.Y_normalized
if sparse.issparse(Y): Y = Y.todense().view(np.ndarray)
return X, X_variance, Y | [
"def",
"get_x_y_var",
"(",
"model",
")",
":",
"# model given",
"if",
"hasattr",
"(",
"model",
",",
"'has_uncertain_inputs'",
")",
"and",
"model",
".",
"has_uncertain_inputs",
"(",
")",
":",
"X",
"=",
"model",
".",
"X",
".",
"mean",
".",
"values",
"X_varian... | https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/plotting/gpy_plot/plot_util.py#L271-L301 | |
google-research/uda | 960684e363251772a5938451d4d2bc0f1da9e24b | text/augmentation/word_level_augment.py | python | TfIdfWordRep.replace_tokens | (self, word_list, replace_prob) | return word_list | Replace tokens in a sentence. | Replace tokens in a sentence. | [
"Replace",
"tokens",
"in",
"a",
"sentence",
"."
] | def replace_tokens(self, word_list, replace_prob):
"""Replace tokens in a sentence."""
for i in range(len(word_list)):
if self.get_random_prob() < replace_prob[i]:
word_list[i] = self.get_random_token()
return word_list | [
"def",
"replace_tokens",
"(",
"self",
",",
"word_list",
",",
"replace_prob",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"word_list",
")",
")",
":",
"if",
"self",
".",
"get_random_prob",
"(",
")",
"<",
"replace_prob",
"[",
"i",
"]",
":",
"w... | https://github.com/google-research/uda/blob/960684e363251772a5938451d4d2bc0f1da9e24b/text/augmentation/word_level_augment.py#L213-L218 | |
mit-han-lab/once-for-all | 4f6fce3652ee4553ea811d38f32f90ac8b1bc378 | ofa/imagenet_classification/elastic_nn/modules/dynamic_layers.py | python | DynamicResNetBottleneckBlock.get_active_subnet | (self, in_channel, preserve_weight=True) | return sub_layer | [] | def get_active_subnet(self, in_channel, preserve_weight=True):
# build the new layer
sub_layer = set_layer_from_config(self.get_active_subnet_config(in_channel))
sub_layer = sub_layer.to(get_net_device(self))
if not preserve_weight:
return sub_layer
# copy weight from current layer
sub_layer.conv1.conv.weight.data.copy_(
self.conv1.conv.get_active_filter(self.active_middle_channels, in_channel).data)
copy_bn(sub_layer.conv1.bn, self.conv1.bn.bn)
sub_layer.conv2.conv.weight.data.copy_(
self.conv2.conv.get_active_filter(self.active_middle_channels, self.active_middle_channels).data)
copy_bn(sub_layer.conv2.bn, self.conv2.bn.bn)
sub_layer.conv3.conv.weight.data.copy_(
self.conv3.conv.get_active_filter(self.active_out_channel, self.active_middle_channels).data)
copy_bn(sub_layer.conv3.bn, self.conv3.bn.bn)
if not isinstance(self.downsample, IdentityLayer):
sub_layer.downsample.conv.weight.data.copy_(
self.downsample.conv.get_active_filter(self.active_out_channel, in_channel).data)
copy_bn(sub_layer.downsample.bn, self.downsample.bn.bn)
return sub_layer | [
"def",
"get_active_subnet",
"(",
"self",
",",
"in_channel",
",",
"preserve_weight",
"=",
"True",
")",
":",
"# build the new layer",
"sub_layer",
"=",
"set_layer_from_config",
"(",
"self",
".",
"get_active_subnet_config",
"(",
"in_channel",
")",
")",
"sub_layer",
"="... | https://github.com/mit-han-lab/once-for-all/blob/4f6fce3652ee4553ea811d38f32f90ac8b1bc378/ofa/imagenet_classification/elastic_nn/modules/dynamic_layers.py#L534-L559 | |||
i-pan/kaggle-rsna18 | 2db498fe99615d935aa676f04847d0c562fd8e46 | models/DeformableConvNets/lib/bbox/bbox_transform.py | python | filter_boxes | (boxes, min_size) | return keep | filter small boxes.
:param boxes: [N, 4* num_classes]
:param min_size:
:return: keep: | filter small boxes.
:param boxes: [N, 4* num_classes]
:param min_size:
:return: keep: | [
"filter",
"small",
"boxes",
".",
":",
"param",
"boxes",
":",
"[",
"N",
"4",
"*",
"num_classes",
"]",
":",
"param",
"min_size",
":",
":",
"return",
":",
"keep",
":"
] | def filter_boxes(boxes, min_size):
"""
filter small boxes.
:param boxes: [N, 4* num_classes]
:param min_size:
:return: keep:
"""
ws = boxes[:, 2] - boxes[:, 0] + 1
hs = boxes[:, 3] - boxes[:, 1] + 1
keep = np.where((ws >= min_size) & (hs >= min_size))[0]
return keep | [
"def",
"filter_boxes",
"(",
"boxes",
",",
"min_size",
")",
":",
"ws",
"=",
"boxes",
"[",
":",
",",
"2",
"]",
"-",
"boxes",
"[",
":",
",",
"0",
"]",
"+",
"1",
"hs",
"=",
"boxes",
"[",
":",
",",
"3",
"]",
"-",
"boxes",
"[",
":",
",",
"1",
"... | https://github.com/i-pan/kaggle-rsna18/blob/2db498fe99615d935aa676f04847d0c562fd8e46/models/DeformableConvNets/lib/bbox/bbox_transform.py#L62-L72 | |
apache/libcloud | 90971e17bfd7b6bb97b2489986472c531cc8e140 | libcloud/container/drivers/rancher.py | python | RancherContainerDriver.ex_deploy_stack | (
self,
name,
description=None,
docker_compose=None,
environment=None,
external_id=None,
rancher_compose=None,
start=True,
) | return result | Deploy a new stack.
http://docs.rancher.com/rancher/v1.2/en/api/api-resources/environment/#create
:param name: The desired name of the stack. (required)
:type name: ``str``
:param description: A desired description for the stack.
:type description: ``str``
:param docker_compose: The Docker Compose configuration to use.
:type docker_compose: ``str``
:param environment: Environment K/V specific to this stack.
:type environment: ``dict``
:param external_id: The externalId of the stack.
:type external_id: ``str``
:param rancher_compose: The Rancher Compose configuration for this env.
:type rancher_compose: ``str``
:param start: Whether to start this stack on creation.
:type start: ``bool``
:return: The newly created stack.
:rtype: ``dict`` | Deploy a new stack. | [
"Deploy",
"a",
"new",
"stack",
"."
] | def ex_deploy_stack(
self,
name,
description=None,
docker_compose=None,
environment=None,
external_id=None,
rancher_compose=None,
start=True,
):
"""
Deploy a new stack.
http://docs.rancher.com/rancher/v1.2/en/api/api-resources/environment/#create
:param name: The desired name of the stack. (required)
:type name: ``str``
:param description: A desired description for the stack.
:type description: ``str``
:param docker_compose: The Docker Compose configuration to use.
:type docker_compose: ``str``
:param environment: Environment K/V specific to this stack.
:type environment: ``dict``
:param external_id: The externalId of the stack.
:type external_id: ``str``
:param rancher_compose: The Rancher Compose configuration for this env.
:type rancher_compose: ``str``
:param start: Whether to start this stack on creation.
:type start: ``bool``
:return: The newly created stack.
:rtype: ``dict``
"""
payload = {
"description": description,
"dockerCompose": docker_compose,
"environment": environment,
"externalId": external_id,
"name": name,
"rancherCompose": rancher_compose,
"startOnCreate": start,
}
data = json.dumps(dict((k, v) for (k, v) in payload.items() if v is not None))
result = self.connection.request(
"%s/environments" % self.baseuri, data=data, method="POST"
).object
return result | [
"def",
"ex_deploy_stack",
"(",
"self",
",",
"name",
",",
"description",
"=",
"None",
",",
"docker_compose",
"=",
"None",
",",
"environment",
"=",
"None",
",",
"external_id",
"=",
"None",
",",
"rancher_compose",
"=",
"None",
",",
"start",
"=",
"True",
",",
... | https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/container/drivers/rancher.py#L175-L229 | |
tobspr/RenderPipeline | d8c38c0406a63298f4801782a8e44e9c1e467acf | rpcore/stage_manager.py | python | StageManager.write_autoconfig | (self) | Writes the shader auto config, based on the defines specified by the
different stages | Writes the shader auto config, based on the defines specified by the
different stages | [
"Writes",
"the",
"shader",
"auto",
"config",
"based",
"on",
"the",
"defines",
"specified",
"by",
"the",
"different",
"stages"
] | def write_autoconfig(self):
""" Writes the shader auto config, based on the defines specified by the
different stages """
self.debug("Writing shader config")
# Generate autoconfig as string
output = "#pragma once\n\n"
output += "// Autogenerated by the render pipeline\n"
output += "// Do not edit! Your changes will be lost.\n\n"
for key, value in sorted(iteritems(self.defines)):
if isinstance(value, bool):
value = 1 if value else 0
output += "#define " + key + " " + str(value) + "\n"
try:
with open("/$$rptemp/$$pipeline_shader_config.inc.glsl", "w") as handle:
handle.write(output)
except IOError as msg:
self.error("Error writing shader autoconfig:", msg) | [
"def",
"write_autoconfig",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"Writing shader config\"",
")",
"# Generate autoconfig as string",
"output",
"=",
"\"#pragma once\\n\\n\"",
"output",
"+=",
"\"// Autogenerated by the render pipeline\\n\"",
"output",
"+=",
"\"//... | https://github.com/tobspr/RenderPipeline/blob/d8c38c0406a63298f4801782a8e44e9c1e467acf/rpcore/stage_manager.py#L267-L286 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_policy_group.py | python | Yedit.load | (self, content_type='yaml') | return self.yaml_dict | return yaml file | return yaml file | [
"return",
"yaml",
"file"
] | def load(self, content_type='yaml'):
''' return yaml file '''
contents = self.read()
if not contents and not self.content:
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
# check if it is yaml
try:
if content_type == 'yaml' and contents:
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
# Try to use RoundTripLoader if supported.
try:
self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
except AttributeError:
self.yaml_dict = yaml.safe_load(contents)
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
elif content_type == 'json' and contents:
self.yaml_dict = json.loads(contents)
except yaml.YAMLError as err:
# Error loading yaml or json
raise YeditException('Problem with loading yaml file. {}'.format(err))
return self.yaml_dict | [
"def",
"load",
"(",
"self",
",",
"content_type",
"=",
"'yaml'",
")",
":",
"contents",
"=",
"self",
".",
"read",
"(",
")",
"if",
"not",
"contents",
"and",
"not",
"self",
".",
"content",
":",
"return",
"None",
"if",
"self",
".",
"content",
":",
"if",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_policy_group.py#L393-L434 | |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | 5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e | deep-learning/UBER-pyro/examples/baseball.py | python | get_site_stats | (array, player_names) | return df.apply(pd.Series.describe, axis=1)[["mean", "std", "25%", "50%", "75%"]] | Return the summarized statistics for a given array corresponding
to the values sampled for a latent or response site. | Return the summarized statistics for a given array corresponding
to the values sampled for a latent or response site. | [
"Return",
"the",
"summarized",
"statistics",
"for",
"a",
"given",
"array",
"corresponding",
"to",
"the",
"values",
"sampled",
"for",
"a",
"latent",
"or",
"response",
"site",
"."
] | def get_site_stats(array, player_names):
"""
Return the summarized statistics for a given array corresponding
to the values sampled for a latent or response site.
"""
if len(array.shape) == 1:
df = pd.DataFrame(array).transpose()
else:
df = pd.DataFrame(array, columns=player_names).transpose()
return df.apply(pd.Series.describe, axis=1)[["mean", "std", "25%", "50%", "75%"]] | [
"def",
"get_site_stats",
"(",
"array",
",",
"player_names",
")",
":",
"if",
"len",
"(",
"array",
".",
"shape",
")",
"==",
"1",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"array",
")",
".",
"transpose",
"(",
")",
"else",
":",
"df",
"=",
"pd",
".... | https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/deep-learning/UBER-pyro/examples/baseball.py#L126-L135 | |
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | pypy/module/cpyext/pystate.py | python | PyThreadState_Clear | (space, tstate) | Reset all information in a thread state object. The global
interpreter lock must be held. | Reset all information in a thread state object. The global
interpreter lock must be held. | [
"Reset",
"all",
"information",
"in",
"a",
"thread",
"state",
"object",
".",
"The",
"global",
"interpreter",
"lock",
"must",
"be",
"held",
"."
] | def PyThreadState_Clear(space, tstate):
"""Reset all information in a thread state object. The global
interpreter lock must be held."""
if not space.config.translation.thread:
raise NoThreads
decref(space, tstate.c_dict)
tstate.c_dict = lltype.nullptr(PyObject.TO)
space.threadlocals.leave_thread(space)
space.getexecutioncontext().cleanup_cpyext_state()
rthread.gc_thread_die() | [
"def",
"PyThreadState_Clear",
"(",
"space",
",",
"tstate",
")",
":",
"if",
"not",
"space",
".",
"config",
".",
"translation",
".",
"thread",
":",
"raise",
"NoThreads",
"decref",
"(",
"space",
",",
"tstate",
".",
"c_dict",
")",
"tstate",
".",
"c_dict",
"=... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/cpyext/pystate.py#L322-L331 | ||
collinsctk/PyQYT | 7af3673955f94ff1b2df2f94220cd2dab2e252af | ExtentionPackages/Crypto/Signature/PKCS1_v1_5.py | python | PKCS115_SigScheme.verify | (self, mhash, S) | return em1==em2 | Verify that a certain PKCS#1 v1.5 signature is authentic.
This function checks if the party holding the private half of the key
really signed the message.
This function is named ``RSASSA-PKCS1-V1_5-VERIFY``, and is specified in
section 8.2.2 of RFC3447.
:Parameters:
mhash : hash object
The hash that was carried out over the message. This is an object
belonging to the `Crypto.Hash` module.
S : string
The signature that needs to be validated.
:Return: True if verification is correct. False otherwise. | Verify that a certain PKCS#1 v1.5 signature is authentic.
This function checks if the party holding the private half of the key
really signed the message.
This function is named ``RSASSA-PKCS1-V1_5-VERIFY``, and is specified in
section 8.2.2 of RFC3447.
:Parameters:
mhash : hash object
The hash that was carried out over the message. This is an object
belonging to the `Crypto.Hash` module.
S : string
The signature that needs to be validated.
:Return: True if verification is correct. False otherwise. | [
"Verify",
"that",
"a",
"certain",
"PKCS#1",
"v1",
".",
"5",
"signature",
"is",
"authentic",
".",
"This",
"function",
"checks",
"if",
"the",
"party",
"holding",
"the",
"private",
"half",
"of",
"the",
"key",
"really",
"signed",
"the",
"message",
".",
"This",... | def verify(self, mhash, S):
"""Verify that a certain PKCS#1 v1.5 signature is authentic.
This function checks if the party holding the private half of the key
really signed the message.
This function is named ``RSASSA-PKCS1-V1_5-VERIFY``, and is specified in
section 8.2.2 of RFC3447.
:Parameters:
mhash : hash object
The hash that was carried out over the message. This is an object
belonging to the `Crypto.Hash` module.
S : string
The signature that needs to be validated.
:Return: True if verification is correct. False otherwise.
"""
# TODO: Verify the key is RSA
# See 8.2.2 in RFC3447
modBits = Crypto.Util.number.size(self._key.n)
k = ceil_div(modBits,8) # Convert from bits to bytes
# Step 1
if len(S) != k:
return 0
# Step 2a (O2SIP) and 2b (RSAVP1)
# Note that signature must be smaller than the module
# but RSA.py won't complain about it.
# TODO: Fix RSA object; don't do it here.
m = self._key.encrypt(S, 0)[0]
# Step 2c (I2OSP)
em1 = bchr(0x00)*(k-len(m)) + m
# Step 3
try:
em2 = EMSA_PKCS1_V1_5_ENCODE(mhash, k)
except ValueError:
return 0
# Step 4
# By comparing the full encodings (as opposed to checking each
# of its components one at a time) we avoid attacks to the padding
# scheme like Bleichenbacher's (see http://www.mail-archive.com/cryptography@metzdowd.com/msg06537).
#
return em1==em2 | [
"def",
"verify",
"(",
"self",
",",
"mhash",
",",
"S",
")",
":",
"# TODO: Verify the key is RSA",
"# See 8.2.2 in RFC3447",
"modBits",
"=",
"Crypto",
".",
"Util",
".",
"number",
".",
"size",
"(",
"self",
".",
"_key",
".",
"n",
")",
"k",
"=",
"ceil_div",
"... | https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/Crypto/Signature/PKCS1_v1_5.py#L117-L161 | |
Pymol-Scripts/Pymol-script-repo | bcd7bb7812dc6db1595953dfa4471fa15fb68c77 | modules/pdb2pqr/contrib/numpy-1.1.0/numpy/core/defmatrix.py | python | bmat | (obj, ldict=None, gdict=None) | Build a matrix object from string, nested sequence, or array.
Examples
--------
>>> F = bmat('A, B; C, D')
>>> F = bmat([[A,B],[C,D]])
>>> F = bmat(r_[c_[A,B],c_[C,D]])
All of these produce the same matrix::
[ A B ]
[ C D ]
if A, B, C, and D are appropriately shaped 2-d arrays. | Build a matrix object from string, nested sequence, or array. | [
"Build",
"a",
"matrix",
"object",
"from",
"string",
"nested",
"sequence",
"or",
"array",
"."
] | def bmat(obj, ldict=None, gdict=None):
"""
Build a matrix object from string, nested sequence, or array.
Examples
--------
>>> F = bmat('A, B; C, D')
>>> F = bmat([[A,B],[C,D]])
>>> F = bmat(r_[c_[A,B],c_[C,D]])
All of these produce the same matrix::
[ A B ]
[ C D ]
if A, B, C, and D are appropriately shaped 2-d arrays.
"""
if isinstance(obj, str):
if gdict is None:
# get previous frame
frame = sys._getframe().f_back
glob_dict = frame.f_globals
loc_dict = frame.f_locals
else:
glob_dict = gdict
loc_dict = ldict
return matrix(_from_string(obj, glob_dict, loc_dict))
if isinstance(obj, (tuple, list)):
# [[A,B],[C,D]]
arr_rows = []
for row in obj:
if isinstance(row, N.ndarray): # not 2-d
return matrix(concatenate(obj,axis=-1))
else:
arr_rows.append(concatenate(row,axis=-1))
return matrix(concatenate(arr_rows,axis=0))
if isinstance(obj, N.ndarray):
return matrix(obj) | [
"def",
"bmat",
"(",
"obj",
",",
"ldict",
"=",
"None",
",",
"gdict",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"if",
"gdict",
"is",
"None",
":",
"# get previous frame",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
"... | https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/numpy-1.1.0/numpy/core/defmatrix.py#L536-L576 | ||
matrix-org/synapse | 8e57584a5859a9002759963eb546d523d2498a01 | synapse/api/auth.py | python | Auth.get_access_token_from_request | (request: Request) | Extracts the access_token from the request.
Args:
request: The http request.
Returns:
The access_token
Raises:
MissingClientTokenError: If there isn't a single access_token in the
request | Extracts the access_token from the request. | [
"Extracts",
"the",
"access_token",
"from",
"the",
"request",
"."
] | def get_access_token_from_request(request: Request) -> str:
"""Extracts the access_token from the request.
Args:
request: The http request.
Returns:
The access_token
Raises:
MissingClientTokenError: If there isn't a single access_token in the
request
"""
# This will always be set by the time Twisted calls us.
assert request.args is not None
auth_headers = request.requestHeaders.getRawHeaders(b"Authorization")
query_params = request.args.get(b"access_token")
if auth_headers:
# Try the get the access_token from a "Authorization: Bearer"
# header
if query_params is not None:
raise MissingClientTokenError(
"Mixing Authorization headers and access_token query parameters."
)
if len(auth_headers) > 1:
raise MissingClientTokenError("Too many Authorization headers.")
parts = auth_headers[0].split(b" ")
if parts[0] == b"Bearer" and len(parts) == 2:
return parts[1].decode("ascii")
else:
raise MissingClientTokenError("Invalid Authorization header.")
else:
# Try to get the access_token from the query params.
if not query_params:
raise MissingClientTokenError()
return query_params[0].decode("ascii") | [
"def",
"get_access_token_from_request",
"(",
"request",
":",
"Request",
")",
"->",
"str",
":",
"# This will always be set by the time Twisted calls us.",
"assert",
"request",
".",
"args",
"is",
"not",
"None",
"auth_headers",
"=",
"request",
".",
"requestHeaders",
".",
... | https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/api/auth.py#L619-L654 | ||
CvvT/dumpDex | 92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1 | python/idaapi.py | python | get_next_module | (*args) | return _idaapi.get_next_module(*args) | get_next_module(modinfo) -> bool | get_next_module(modinfo) -> bool | [
"get_next_module",
"(",
"modinfo",
")",
"-",
">",
"bool"
] | def get_next_module(*args):
"""
get_next_module(modinfo) -> bool
"""
return _idaapi.get_next_module(*args) | [
"def",
"get_next_module",
"(",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"get_next_module",
"(",
"*",
"args",
")"
] | https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L24926-L24930 | |
quip/quip-api | 19f3b32a05ed092a70dc2c616e214aaff8a06de2 | samples/webhooks/quip.py | python | QuipClient.remove_folder_members | (self, folder_id, member_ids) | return self._fetch_json("folders/remove-members", post_data={
"folder_id": folder_id,
"member_ids": ",".join(member_ids),
}) | Removes the given users from the given folder. | Removes the given users from the given folder. | [
"Removes",
"the",
"given",
"users",
"from",
"the",
"given",
"folder",
"."
] | def remove_folder_members(self, folder_id, member_ids):
"""Removes the given users from the given folder."""
return self._fetch_json("folders/remove-members", post_data={
"folder_id": folder_id,
"member_ids": ",".join(member_ids),
}) | [
"def",
"remove_folder_members",
"(",
"self",
",",
"folder_id",
",",
"member_ids",
")",
":",
"return",
"self",
".",
"_fetch_json",
"(",
"\"folders/remove-members\"",
",",
"post_data",
"=",
"{",
"\"folder_id\"",
":",
"folder_id",
",",
"\"member_ids\"",
":",
"\",\"",... | https://github.com/quip/quip-api/blob/19f3b32a05ed092a70dc2c616e214aaff8a06de2/samples/webhooks/quip.py#L212-L217 | |
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | dist/lib/python2.7/os2emxpath.py | python | ismount | (path) | return len(p) == 1 and p[0] in '/\\' | Test whether a path is a mount point (defined as root of drive) | Test whether a path is a mount point (defined as root of drive) | [
"Test",
"whether",
"a",
"path",
"is",
"a",
"mount",
"point",
"(",
"defined",
"as",
"root",
"of",
"drive",
")"
] | def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
if unc:
return rest in ("", "/", "\\")
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in '/\\' | [
"def",
"ismount",
"(",
"path",
")",
":",
"unc",
",",
"rest",
"=",
"splitunc",
"(",
"path",
")",
"if",
"unc",
":",
"return",
"rest",
"in",
"(",
"\"\"",
",",
"\"/\"",
",",
"\"\\\\\"",
")",
"p",
"=",
"splitdrive",
"(",
"path",
")",
"[",
"1",
"]",
... | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/os2emxpath.py#L109-L115 | |
CvvT/dumpDex | 92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1 | python/idaapi.py | python | exit_process | (*args) | return _idaapi.exit_process(*args) | exit_process() -> bool | exit_process() -> bool | [
"exit_process",
"()",
"-",
">",
"bool"
] | def exit_process(*args):
"""
exit_process() -> bool
"""
return _idaapi.exit_process(*args) | [
"def",
"exit_process",
"(",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"exit_process",
"(",
"*",
"args",
")"
] | https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L24308-L24312 | |
intercom/python-intercom | a1b12bace6d24b4ce70e8ce234f3a4f3bca9acf2 | intercom/api_operations/save.py | python | Save.id_present | (self, obj) | return getattr(obj, 'id', None) and obj.id != "" | Return whether the obj has an `id` attribute with a value. | Return whether the obj has an `id` attribute with a value. | [
"Return",
"whether",
"the",
"obj",
"has",
"an",
"id",
"attribute",
"with",
"a",
"value",
"."
] | def id_present(self, obj):
"""Return whether the obj has an `id` attribute with a value."""
return getattr(obj, 'id', None) and obj.id != "" | [
"def",
"id_present",
"(",
"self",
",",
"obj",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"'id'",
",",
"None",
")",
"and",
"obj",
".",
"id",
"!=",
"\"\""
] | https://github.com/intercom/python-intercom/blob/a1b12bace6d24b4ce70e8ce234f3a4f3bca9acf2/intercom/api_operations/save.py#L33-L35 | |
AstroPrint/AstroBox | e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75 | src/ext/makerbot_pyserial/serialutil.py | python | SerialBase.getXonXoff | (self) | return self._xonxoff | Get the current XON/XOFF setting. | Get the current XON/XOFF setting. | [
"Get",
"the",
"current",
"XON",
"/",
"XOFF",
"setting",
"."
] | def getXonXoff(self):
"""Get the current XON/XOFF setting."""
return self._xonxoff | [
"def",
"getXonXoff",
"(",
"self",
")",
":",
"return",
"self",
".",
"_xonxoff"
] | https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/ext/makerbot_pyserial/serialutil.py#L411-L413 | |
mediacloud/backend | d36b489e4fbe6e44950916a04d9543a1d6cd5df0 | apps/crawler-fetcher/src/python/crawler_fetcher/handlers/feed_podcast.py | python | _get_feed_url_from_google_podcasts_url | (url: str) | return feed_url | Given a Google Podcasts URL, try to determine a RSS feed URL from it.
:param url: Google Podcasts URL, e.g. https://podcasts.google.com/?feed=aHR0cHM6Ly93d3cucmVzaWRlbnRhZHZpc29yLm5ldC94
bWwvcG9kY2FzdC54bWw&ved=0CAAQ4aUDahcKEwiot6W5hrnnAhUAAAAAHQAAAAAQAQ&hl=lt
:return: RSS feed URL that Google Podcasts uses, or original URL if it's not a Google Podcasts URL / feed URL can't
be determined. | Given a Google Podcasts URL, try to determine a RSS feed URL from it. | [
"Given",
"a",
"Google",
"Podcasts",
"URL",
"try",
"to",
"determine",
"a",
"RSS",
"feed",
"URL",
"from",
"it",
"."
] | def _get_feed_url_from_google_podcasts_url(url: str) -> str:
"""
Given a Google Podcasts URL, try to determine a RSS feed URL from it.
:param url: Google Podcasts URL, e.g. https://podcasts.google.com/?feed=aHR0cHM6Ly93d3cucmVzaWRlbnRhZHZpc29yLm5ldC94
bWwvcG9kY2FzdC54bWw&ved=0CAAQ4aUDahcKEwiot6W5hrnnAhUAAAAAHQAAAAAQAQ&hl=lt
:return: RSS feed URL that Google Podcasts uses, or original URL if it's not a Google Podcasts URL / feed URL can't
be determined.
"""
uri = furl(url)
if uri.host != 'podcasts.google.com':
log.debug(f"URL '{url}' is not Google Podcasts URL.")
return url
if 'feed' not in uri.args:
log.error(f"URL '{url}' doesn't have 'feed' parameter.")
# Remove the rest of the arguments because they might lead to an episode page which doesn't have "data-feed"
args = list(uri.args.keys())
for arg in args:
if arg != 'feed':
del uri.args[arg]
url = str(uri.url)
ua = UserAgent()
res = ua.get(url)
if not res.is_success():
log.error(f"Unable to fetch Google Podcasts feed URL: {res.status_line()}")
return url
html = res.decoded_content()
# check whether this is an individual episode URL rather than the show's Google Podcasts homepage; the feed URL
# doesn't appear on individual episode pages, so we need to spider to the show's Google Podcasts homepage to get it
if '/episode/' in url:
show_homepage = url.split('/episode/')[0]
res = ua.get(show_homepage)
if not res.is_success():
log.error(f"Unable to fetch Google Podcasts feed URL: {res.status_line()}")
return show_homepage
else:
html = res.decoded_content()
# get show's feed URL from its Google Podcasts homepage
match = re.search(r'c-data id="i3" jsdata=".*(https?://.+?);2', html, flags=re.IGNORECASE)
if not match:
log.error(f"Feed URL was not found in Google Podcasts feed page.")
return url
feed_url = match.group(1)
log.info(f"Resolved Google Podcasts URL '{url}' as '{feed_url}'")
return feed_url | [
"def",
"_get_feed_url_from_google_podcasts_url",
"(",
"url",
":",
"str",
")",
"->",
"str",
":",
"uri",
"=",
"furl",
"(",
"url",
")",
"if",
"uri",
".",
"host",
"!=",
"'podcasts.google.com'",
":",
"log",
".",
"debug",
"(",
"f\"URL '{url}' is not Google Podcasts UR... | https://github.com/mediacloud/backend/blob/d36b489e4fbe6e44950916a04d9543a1d6cd5df0/apps/crawler-fetcher/src/python/crawler_fetcher/handlers/feed_podcast.py#L80-L136 | |
virt-manager/virt-manager | c51ebdd76a9fc198c40cefcd78838860199467d3 | virtManager/lib/uiutil.py | python | spin_get_helper | (widget) | Safely get spin button contents, converting to int if possible | Safely get spin button contents, converting to int if possible | [
"Safely",
"get",
"spin",
"button",
"contents",
"converting",
"to",
"int",
"if",
"possible"
] | def spin_get_helper(widget):
"""
Safely get spin button contents, converting to int if possible
"""
adj = widget.get_adjustment()
txt = widget.get_text()
try:
return int(txt)
except Exception:
return adj.get_value() | [
"def",
"spin_get_helper",
"(",
"widget",
")",
":",
"adj",
"=",
"widget",
".",
"get_adjustment",
"(",
")",
"txt",
"=",
"widget",
".",
"get_text",
"(",
")",
"try",
":",
"return",
"int",
"(",
"txt",
")",
"except",
"Exception",
":",
"return",
"adj",
".",
... | https://github.com/virt-manager/virt-manager/blob/c51ebdd76a9fc198c40cefcd78838860199467d3/virtManager/lib/uiutil.py#L17-L27 | ||
veusz/veusz | 5a1e2af5f24df0eb2a2842be51f2997c4999c7fb | veusz/dataimport/dialog_fits.py | python | ImportTabFITS.newCurrentSel | (self, new, old) | New item selected in the tree. | New item selected in the tree. | [
"New",
"item",
"selected",
"in",
"the",
"tree",
"."
] | def newCurrentSel(self, new, old):
"""New item selected in the tree."""
self.updateOptions()
# show appropriate widgets at bottom for editing options
toshow = node = None
if new is not None and new.isValid():
node = new.internalPointer()
if isinstance(node, fits_hdf5_tree.FileDataNode):
if node.getDims() == 2 and node.numeric:
toshow = 'twod'
self.showOptionsTwoD(node)
# so we know which options to update next
self.oldselection = (node, toshow)
for widget, name in (
(self.fitstwodgrp, 'twod'),
):
if name == toshow:
widget.show()
else:
widget.hide() | [
"def",
"newCurrentSel",
"(",
"self",
",",
"new",
",",
"old",
")",
":",
"self",
".",
"updateOptions",
"(",
")",
"# show appropriate widgets at bottom for editing options",
"toshow",
"=",
"node",
"=",
"None",
"if",
"new",
"is",
"not",
"None",
"and",
"new",
".",
... | https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/dataimport/dialog_fits.py#L243-L266 | ||
tonybaloney/wily | e72b7d95228bbe5538a072dc5d1186daa318bb03 | src/wily/operators/maintainability.py | python | MaintainabilityIndexOperator.run | (self, module, options) | return results | Run the operator.
:param module: The target module path.
:type module: ``str``
:param options: Any runtime options.
:type options: ``dict``
:return: The operator results.
:rtype: ``dict`` | Run the operator. | [
"Run",
"the",
"operator",
"."
] | def run(self, module, options):
"""
Run the operator.
:param module: The target module path.
:type module: ``str``
:param options: Any runtime options.
:type options: ``dict``
:return: The operator results.
:rtype: ``dict``
"""
logger.debug("Running maintainability harvester")
results = {}
for filename, metrics in dict(self.harvester.results).items():
results[filename] = {"total": metrics}
return results | [
"def",
"run",
"(",
"self",
",",
"module",
",",
"options",
")",
":",
"logger",
".",
"debug",
"(",
"\"Running maintainability harvester\"",
")",
"results",
"=",
"{",
"}",
"for",
"filename",
",",
"metrics",
"in",
"dict",
"(",
"self",
".",
"harvester",
".",
... | https://github.com/tonybaloney/wily/blob/e72b7d95228bbe5538a072dc5d1186daa318bb03/src/wily/operators/maintainability.py#L65-L82 | |
SheffieldML/GPy | bb1bc5088671f9316bc92a46d356734e34c2d5c0 | GPy/kern/src/trunclinear.py | python | TruncLinear.update_gradients_diag | (self, dL_dKdiag, X) | [] | def update_gradients_diag(self, dL_dKdiag, X):
if self.ARD:
self.variances.gradient[:] = np.einsum('nq,n->q',np.square(X-self.delta),dL_dKdiag)
self.delta.gradient[:] = np.einsum('nq,n->q',2*self.variances*(self.delta-X),dL_dKdiag)
else:
self.variances.gradient[:] = np.einsum('nq,n->',np.square(X-self.delta),dL_dKdiag)
self.delta.gradient[:] = np.einsum('nq,n->',2*self.variances*(self.delta-X),dL_dKdiag) | [
"def",
"update_gradients_diag",
"(",
"self",
",",
"dL_dKdiag",
",",
"X",
")",
":",
"if",
"self",
".",
"ARD",
":",
"self",
".",
"variances",
".",
"gradient",
"[",
":",
"]",
"=",
"np",
".",
"einsum",
"(",
"'nq,n->q'",
",",
"np",
".",
"square",
"(",
"... | https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/kern/src/trunclinear.py#L85-L91 | ||||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v9/services/services/google_ads_service/client.py | python | GoogleAdsServiceClient.ad_group_bid_modifier_path | (
customer_id: str, ad_group_id: str, criterion_id: str,
) | return "customers/{customer_id}/adGroupBidModifiers/{ad_group_id}~{criterion_id}".format(
customer_id=customer_id,
ad_group_id=ad_group_id,
criterion_id=criterion_id,
) | Return a fully-qualified ad_group_bid_modifier string. | Return a fully-qualified ad_group_bid_modifier string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"ad_group_bid_modifier",
"string",
"."
] | def ad_group_bid_modifier_path(
customer_id: str, ad_group_id: str, criterion_id: str,
) -> str:
"""Return a fully-qualified ad_group_bid_modifier string."""
return "customers/{customer_id}/adGroupBidModifiers/{ad_group_id}~{criterion_id}".format(
customer_id=customer_id,
ad_group_id=ad_group_id,
criterion_id=criterion_id,
) | [
"def",
"ad_group_bid_modifier_path",
"(",
"customer_id",
":",
"str",
",",
"ad_group_id",
":",
"str",
",",
"criterion_id",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"customers/{customer_id}/adGroupBidModifiers/{ad_group_id}~{criterion_id}\"",
".",
"format",
"("... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/google_ads_service/client.py#L383-L391 | |
cobbler/cobbler | eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc | cobbler/actions/buildiso/__init__.py | python | BuildIso._prepare_iso | (
self,
buildisodir: str = "",
iso_distro: str = "",
profiles: Optional[Union[str, list]] = None,
) | return buildisodir | Validates the directories we use for building the ISO and copies files to the right place.
:param buildisodir: The directory to use for building the ISO. If an empty string then the default directory is
used.
:param iso_distro: The distro to use for building the ISO.
:param profiles: The profiles to generate the ISO for.
:return: The normalized directory for further processing. | Validates the directories we use for building the ISO and copies files to the right place.
:param buildisodir: The directory to use for building the ISO. If an empty string then the default directory is
used.
:param iso_distro: The distro to use for building the ISO.
:param profiles: The profiles to generate the ISO for.
:return: The normalized directory for further processing. | [
"Validates",
"the",
"directories",
"we",
"use",
"for",
"building",
"the",
"ISO",
"and",
"copies",
"files",
"to",
"the",
"right",
"place",
".",
":",
"param",
"buildisodir",
":",
"The",
"directory",
"to",
"use",
"for",
"building",
"the",
"ISO",
".",
"If",
... | def _prepare_iso(
self,
buildisodir: str = "",
iso_distro: str = "",
profiles: Optional[Union[str, list]] = None,
):
"""
Validates the directories we use for building the ISO and copies files to the right place.
:param buildisodir: The directory to use for building the ISO. If an empty string then the default directory is
used.
:param iso_distro: The distro to use for building the ISO.
:param profiles: The profiles to generate the ISO for.
:return: The normalized directory for further processing.
"""
try:
iso_distro = self.api.find_distro(name=iso_distro)
except ValueError as value_error:
raise ValueError(
'Not existent distribution name passed to "cobbler buildiso"!'
) from value_error
buildisodir = self.__prepare_buildisodir(buildisodir)
self.__copy_files(iso_distro)
self.profiles = utils.input_string_or_list_no_inherit(profiles)
return buildisodir | [
"def",
"_prepare_iso",
"(",
"self",
",",
"buildisodir",
":",
"str",
"=",
"\"\"",
",",
"iso_distro",
":",
"str",
"=",
"\"\"",
",",
"profiles",
":",
"Optional",
"[",
"Union",
"[",
"str",
",",
"list",
"]",
"]",
"=",
"None",
",",
")",
":",
"try",
":",
... | https://github.com/cobbler/cobbler/blob/eed8cdca3e970c8aa1d199e80b8c8f19b3f940cc/cobbler/actions/buildiso/__init__.py#L270-L293 | |
Nikolay-Kha/PyCNC | f5ae14b72b0dee7e24f1c323771936f1daa1da97 | cnc/hal_virtual.py | python | get_extruder_temperature | () | return EXTRUDER_MAX_TEMPERATURE * 0.999 | Measure extruder temperature.
:return: temperature in Celsius. | Measure extruder temperature.
:return: temperature in Celsius. | [
"Measure",
"extruder",
"temperature",
".",
":",
"return",
":",
"temperature",
"in",
"Celsius",
"."
] | def get_extruder_temperature():
""" Measure extruder temperature.
:return: temperature in Celsius.
"""
return EXTRUDER_MAX_TEMPERATURE * 0.999 | [
"def",
"get_extruder_temperature",
"(",
")",
":",
"return",
"EXTRUDER_MAX_TEMPERATURE",
"*",
"0.999"
] | https://github.com/Nikolay-Kha/PyCNC/blob/f5ae14b72b0dee7e24f1c323771936f1daa1da97/cnc/hal_virtual.py#L51-L55 | |
titusjan/argos | 5a9c31a8a9a2ca825bbf821aa1e685740e3682d7 | argos/widgets/mainwindow.py | python | MainWindow.argosApplication | (self) | return self._argosApplication | The ArgosApplication to which this window belongs. | The ArgosApplication to which this window belongs. | [
"The",
"ArgosApplication",
"to",
"which",
"this",
"window",
"belongs",
"."
] | def argosApplication(self):
""" The ArgosApplication to which this window belongs.
"""
return self._argosApplication | [
"def",
"argosApplication",
"(",
"self",
")",
":",
"return",
"self",
".",
"_argosApplication"
] | https://github.com/titusjan/argos/blob/5a9c31a8a9a2ca825bbf821aa1e685740e3682d7/argos/widgets/mainwindow.py#L411-L414 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/plot/plot3d/tachyon.py | python | Tachyon.parametric_plot | (self, f, t_0, t_f, tex, r=.1, cylinders=True,
min_depth=4, max_depth=8, e_rel=.01, e_abs=.01) | r"""
Plot a space curve as a series of spheres and finite cylinders.
Example (twisted cubic) ::
sage: f = lambda t: (t,t^2,t^3)
sage: t = Tachyon(camera_position=(5,0,4))
sage: t.texture('t')
sage: t.light((-20,-20,40), 0.2, (1,1,1))
sage: t.parametric_plot(f,-5,5,'t',min_depth=6)
sage: t.show(verbose=1)
tachyon ...
Scene contains 482 objects.
... | r"""
Plot a space curve as a series of spheres and finite cylinders. | [
"r",
"Plot",
"a",
"space",
"curve",
"as",
"a",
"series",
"of",
"spheres",
"and",
"finite",
"cylinders",
"."
] | def parametric_plot(self, f, t_0, t_f, tex, r=.1, cylinders=True,
min_depth=4, max_depth=8, e_rel=.01, e_abs=.01):
r"""
Plot a space curve as a series of spheres and finite cylinders.
Example (twisted cubic) ::
sage: f = lambda t: (t,t^2,t^3)
sage: t = Tachyon(camera_position=(5,0,4))
sage: t.texture('t')
sage: t.light((-20,-20,40), 0.2, (1,1,1))
sage: t.parametric_plot(f,-5,5,'t',min_depth=6)
sage: t.show(verbose=1)
tachyon ...
Scene contains 482 objects.
...
"""
self._objects.append(
ParametricPlot(f, t_0, t_f, tex, r=r, cylinders=cylinders,
min_depth=min_depth, max_depth=max_depth,
e_rel=.01, e_abs=.01)) | [
"def",
"parametric_plot",
"(",
"self",
",",
"f",
",",
"t_0",
",",
"t_f",
",",
"tex",
",",
"r",
"=",
".1",
",",
"cylinders",
"=",
"True",
",",
"min_depth",
"=",
"4",
",",
"max_depth",
"=",
"8",
",",
"e_rel",
"=",
".01",
",",
"e_abs",
"=",
".01",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/plot/plot3d/tachyon.py#L1035-L1055 | ||
altair-viz/pdvega | e3f1fc9730f8cd9ad70e7ba0f0a557f41279839a | doc/sphinxext/pdvega_ext/utils.py | python | import_obj | (clsname, default_module=None) | return obj | Import the object given by clsname.
If default_module is specified, import from this module. | Import the object given by clsname.
If default_module is specified, import from this module. | [
"Import",
"the",
"object",
"given",
"by",
"clsname",
".",
"If",
"default_module",
"is",
"specified",
"import",
"from",
"this",
"module",
"."
] | def import_obj(clsname, default_module=None):
"""
Import the object given by clsname.
If default_module is specified, import from this module.
"""
if default_module is not None:
if not clsname.startswith(default_module + '.'):
clsname = '{0}.{1}'.format(default_module, clsname)
mod, clsname = clsname.rsplit('.', 1)
mod = importlib.import_module(mod)
try:
obj = getattr(mod, clsname)
except AttributeError:
raise ImportError('Cannot import {0} from {1}'.format(clsname, mod))
return obj | [
"def",
"import_obj",
"(",
"clsname",
",",
"default_module",
"=",
"None",
")",
":",
"if",
"default_module",
"is",
"not",
"None",
":",
"if",
"not",
"clsname",
".",
"startswith",
"(",
"default_module",
"+",
"'.'",
")",
":",
"clsname",
"=",
"'{0}.{1}'",
".",
... | https://github.com/altair-viz/pdvega/blob/e3f1fc9730f8cd9ad70e7ba0f0a557f41279839a/doc/sphinxext/pdvega_ext/utils.py#L33-L47 | |
VirtueSecurity/aws-extender | d123b7e1a845847709ba3a481f11996bddc68a1c | BappModules/s3transfer/futures.py | python | ExecutorFuture.__init__ | (self, future) | A future returned from the executor
Currently, it is just a wrapper around a concurrent.futures.Future.
However, this can eventually grow to implement the needed functionality
of concurrent.futures.Future if we move off of the library and not
affect the rest of the codebase.
:type future: concurrent.futures.Future
:param future: The underlying future | A future returned from the executor | [
"A",
"future",
"returned",
"from",
"the",
"executor"
] | def __init__(self, future):
"""A future returned from the executor
Currently, it is just a wrapper around a concurrent.futures.Future.
However, this can eventually grow to implement the needed functionality
of concurrent.futures.Future if we move off of the library and not
affect the rest of the codebase.
:type future: concurrent.futures.Future
:param future: The underlying future
"""
self._future = future | [
"def",
"__init__",
"(",
"self",
",",
"future",
")",
":",
"self",
".",
"_future",
"=",
"future"
] | https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/s3transfer/futures.py#L446-L457 | ||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/states/boto_iot.py | python | policy_present | (
name, policyName, policyDocument, region=None, key=None, keyid=None, profile=None
) | return ret | Ensure policy exists.
name
The name of the state definition
policyName
Name of the policy.
policyDocument
The JSON document that describes the policy. The length of the
policyDocument must be a minimum length of 1, with a maximum length of
2048, excluding whitespace.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | Ensure policy exists. | [
"Ensure",
"policy",
"exists",
"."
] | def policy_present(
name, policyName, policyDocument, region=None, key=None, keyid=None, profile=None
):
"""
Ensure policy exists.
name
The name of the state definition
policyName
Name of the policy.
policyDocument
The JSON document that describes the policy. The length of the
policyDocument must be a minimum length of 1, with a maximum length of
2048, excluding whitespace.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
"""
ret = {"name": policyName, "result": True, "comment": "", "changes": {}}
r = __salt__["boto_iot.policy_exists"](
policyName=policyName, region=region, key=key, keyid=keyid, profile=profile
)
if "error" in r:
ret["result"] = False
ret["comment"] = "Failed to create policy: {}.".format(r["error"]["message"])
return ret
if not r.get("exists"):
if __opts__["test"]:
ret["comment"] = "Policy {} is set to be created.".format(policyName)
ret["result"] = None
return ret
r = __salt__["boto_iot.create_policy"](
policyName=policyName,
policyDocument=policyDocument,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if not r.get("created"):
ret["result"] = False
ret["comment"] = "Failed to create policy: {}.".format(
r["error"]["message"]
)
return ret
_describe = __salt__["boto_iot.describe_policy"](
policyName, region=region, key=key, keyid=keyid, profile=profile
)
ret["changes"]["old"] = {"policy": None}
ret["changes"]["new"] = _describe
ret["comment"] = "Policy {} created.".format(policyName)
return ret
ret["comment"] = os.linesep.join(
[ret["comment"], "Policy {} is present.".format(policyName)]
)
ret["changes"] = {}
# policy exists, ensure config matches
_describe = __salt__["boto_iot.describe_policy"](
policyName=policyName, region=region, key=key, keyid=keyid, profile=profile
)["policy"]
if isinstance(_describe["policyDocument"], str):
describeDict = salt.utils.json.loads(_describe["policyDocument"])
else:
describeDict = _describe["policyDocument"]
if isinstance(policyDocument, str):
policyDocument = salt.utils.json.loads(policyDocument)
r = salt.utils.data.compare_dicts(describeDict, policyDocument)
if bool(r):
if __opts__["test"]:
msg = "Policy {} set to be modified.".format(policyName)
ret["comment"] = msg
ret["result"] = None
return ret
ret["comment"] = os.linesep.join([ret["comment"], "Policy to be modified"])
policyDocument = salt.utils.json.dumps(policyDocument)
r = __salt__["boto_iot.create_policy_version"](
policyName=policyName,
policyDocument=policyDocument,
setAsDefault=True,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if not r.get("created"):
ret["result"] = False
ret["comment"] = "Failed to update policy: {}.".format(
r["error"]["message"]
)
ret["changes"] = {}
return ret
__salt__["boto_iot.delete_policy_version"](
policyName=policyName,
policyVersionId=_describe["defaultVersionId"],
region=region,
key=key,
keyid=keyid,
profile=profile,
)
ret["changes"].setdefault("new", {})["policyDocument"] = policyDocument
ret["changes"].setdefault("old", {})["policyDocument"] = _describe[
"policyDocument"
]
return ret | [
"def",
"policy_present",
"(",
"name",
",",
"policyName",
",",
"policyDocument",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"\"name\"",
":",
"policyName",
",",
... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/boto_iot.py#L326-L452 | |
metabrainz/listenbrainz-server | 391a0b91ac3a48398027467651ce3160765c7f37 | listenbrainz/domain/importer_service.py | python | ImporterService.get_active_users_to_process | (self) | Return list of active users for importing listens. | Return list of active users for importing listens. | [
"Return",
"list",
"of",
"active",
"users",
"for",
"importing",
"listens",
"."
] | def get_active_users_to_process(self) -> List[dict]:
""" Return list of active users for importing listens. """
raise NotImplementedError() | [
"def",
"get_active_users_to_process",
"(",
"self",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/metabrainz/listenbrainz-server/blob/391a0b91ac3a48398027467651ce3160765c7f37/listenbrainz/domain/importer_service.py#L12-L14 | ||
ctxis/canape | 5f0e03424577296bcc60c2008a60a98ec5307e4b | CANAPE.Scripting/Lib/distutils/fancy_getopt.py | python | FancyGetopt.has_option | (self, long_option) | return long_option in self.option_index | Return true if the option table for this parser has an
option with long name 'long_option'. | Return true if the option table for this parser has an
option with long name 'long_option'. | [
"Return",
"true",
"if",
"the",
"option",
"table",
"for",
"this",
"parser",
"has",
"an",
"option",
"with",
"long",
"name",
"long_option",
"."
] | def has_option (self, long_option):
"""Return true if the option table for this parser has an
option with long name 'long_option'."""
return long_option in self.option_index | [
"def",
"has_option",
"(",
"self",
",",
"long_option",
")",
":",
"return",
"long_option",
"in",
"self",
".",
"option_index"
] | https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/distutils/fancy_getopt.py#L108-L111 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | postfix/setup.py | python | get_dependencies | () | [] | def get_dependencies():
dep_file = path.join(HERE, 'requirements.in')
if not path.isfile(dep_file):
return []
with open(dep_file, encoding='utf-8') as f:
return f.readlines() | [
"def",
"get_dependencies",
"(",
")",
":",
"dep_file",
"=",
"path",
".",
"join",
"(",
"HERE",
",",
"'requirements.in'",
")",
"if",
"not",
"path",
".",
"isfile",
"(",
"dep_file",
")",
":",
"return",
"[",
"]",
"with",
"open",
"(",
"dep_file",
",",
"encodi... | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/postfix/setup.py#L21-L27 | ||||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/pydoc.py | python | TextDoc._docdescriptor | (self, name, value, mod) | return ''.join(results) | [] | def _docdescriptor(self, name, value, mod):
results = []
push = results.append
if name:
push(self.bold(name))
push('\n')
doc = getdoc(value) or ''
if doc:
push(self.indent(doc))
push('\n')
return ''.join(results) | [
"def",
"_docdescriptor",
"(",
"self",
",",
"name",
",",
"value",
",",
"mod",
")",
":",
"results",
"=",
"[",
"]",
"push",
"=",
"results",
".",
"append",
"if",
"name",
":",
"push",
"(",
"self",
".",
"bold",
"(",
"name",
")",
")",
"push",
"(",
"'\\n... | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/pydoc.py#L1337-L1348 | |||
clinton-hall/nzbToMedia | 27669389216902d1085660167e7bda0bd8527ecf | libs/common/setuptools/msvc.py | python | SystemInfo.NetFxSdkVersion | (self) | Microsoft .NET Framework SDK versions. | Microsoft .NET Framework SDK versions. | [
"Microsoft",
".",
"NET",
"Framework",
"SDK",
"versions",
"."
] | def NetFxSdkVersion(self):
"""
Microsoft .NET Framework SDK versions.
"""
# Set FxSdk versions for specified MSVC++ version
if self.vc_ver >= 14.0:
return ('4.6.1', '4.6')
else:
return () | [
"def",
"NetFxSdkVersion",
"(",
"self",
")",
":",
"# Set FxSdk versions for specified MSVC++ version",
"if",
"self",
".",
"vc_ver",
">=",
"14.0",
":",
"return",
"(",
"'4.6.1'",
",",
"'4.6'",
")",
"else",
":",
"return",
"(",
")"
] | https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/setuptools/msvc.py#L712-L720 | ||
Flexget/Flexget | ffad58f206278abefc88d63a1ffaa80476fc4d98 | flexget/plugins/input/gazelle.py | python | InputGazelle.get_entries | (self, search_results) | Generator that yields Entry objects from search results | Generator that yields Entry objects from search results | [
"Generator",
"that",
"yields",
"Entry",
"objects",
"from",
"search",
"results"
] | def get_entries(self, search_results):
"""Generator that yields Entry objects from search results"""
for result in search_results:
# Get basic information on the release
info = dict((k, result[k]) for k in ('groupId', 'groupName'))
# Releases can have multiple download options
for tor in result['torrents']:
temp = info.copy()
temp['torrentId'] = tor['torrentId']
yield Entry(
title="{groupName} ({groupId} - {torrentId}).torrent".format(**temp),
url="{}/torrents.php?action=download&id={}&authkey={}&torrent_pass={}"
"".format(self.base_url, temp['torrentId'], self.authkey, self.passkey),
torrent_seeds=tor['seeders'],
torrent_leeches=tor['leechers'],
# Size is returned in bytes
content_size=parse_filesize(str(tor['size']) + "b"),
) | [
"def",
"get_entries",
"(",
"self",
",",
"search_results",
")",
":",
"for",
"result",
"in",
"search_results",
":",
"# Get basic information on the release",
"info",
"=",
"dict",
"(",
"(",
"k",
",",
"result",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"(",
"'grou... | https://github.com/Flexget/Flexget/blob/ffad58f206278abefc88d63a1ffaa80476fc4d98/flexget/plugins/input/gazelle.py#L275-L294 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/recorder/__init__.py | python | run_information | (hass, point_in_time: datetime | None = None) | Return information about current run.
There is also the run that covers point_in_time. | Return information about current run. | [
"Return",
"information",
"about",
"current",
"run",
"."
] | def run_information(hass, point_in_time: datetime | None = None):
"""Return information about current run.
There is also the run that covers point_in_time.
"""
run_info = run_information_from_instance(hass, point_in_time)
if run_info:
return run_info
with session_scope(hass=hass) as session:
return run_information_with_session(session, point_in_time) | [
"def",
"run_information",
"(",
"hass",
",",
"point_in_time",
":",
"datetime",
"|",
"None",
"=",
"None",
")",
":",
"run_info",
"=",
"run_information_from_instance",
"(",
"hass",
",",
"point_in_time",
")",
"if",
"run_info",
":",
"return",
"run_info",
"with",
"se... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/recorder/__init__.py#L196-L206 | ||
PaddlePaddle/PaddleX | 2bab73f81ab54e328204e7871e6ae4a82e719f5d | paddlex/ppdet/data/transform/autoaugment_utils.py | python | shear_with_bboxes | (image, bboxes, level, replace, shear_horizontal) | return image.astype(np.uint8), new_bboxes | Applies Shear Transformation to the image and shifts the bboxes.
Args:
image: 3D uint8 Tensor.
bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
has 4 elements (min_y, min_x, max_y, max_x) of type float with values
between [0, 1].
level: Float. How much to shear the image. This value will be between
-0.3 to 0.3.
replace: A one or three value 1D tensor to fill empty pixels.
shear_horizontal: Boolean. If true then shear in X dimension else shear in
the Y dimension.
Returns:
A tuple containing a 3D uint8 Tensor that will be the result of shearing
image by level. The second element of the tuple is bboxes, where now
the coordinates will be shifted to reflect the sheared image. | Applies Shear Transformation to the image and shifts the bboxes. | [
"Applies",
"Shear",
"Transformation",
"to",
"the",
"image",
"and",
"shifts",
"the",
"bboxes",
"."
] | def shear_with_bboxes(image, bboxes, level, replace, shear_horizontal):
"""Applies Shear Transformation to the image and shifts the bboxes.
Args:
image: 3D uint8 Tensor.
bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox
has 4 elements (min_y, min_x, max_y, max_x) of type float with values
between [0, 1].
level: Float. How much to shear the image. This value will be between
-0.3 to 0.3.
replace: A one or three value 1D tensor to fill empty pixels.
shear_horizontal: Boolean. If true then shear in X dimension else shear in
the Y dimension.
Returns:
A tuple containing a 3D uint8 Tensor that will be the result of shearing
image by level. The second element of the tuple is bboxes, where now
the coordinates will be shifted to reflect the sheared image.
"""
if shear_horizontal:
image = shear_x(image, level, replace)
else:
image = shear_y(image, level, replace)
# Convert bbox coordinates to pixel values.
image_height, image_width = image.shape[:2]
# pylint:disable=g-long-lambda
wrapped_shear_bbox = lambda bbox: _shear_bbox(bbox, image_height, image_width, level, shear_horizontal)
# pylint:enable=g-long-lambda
new_bboxes = deepcopy(bboxes)
num_bboxes = len(bboxes)
for idx in range(num_bboxes):
new_bboxes[idx] = wrapped_shear_bbox(bboxes[idx])
return image.astype(np.uint8), new_bboxes | [
"def",
"shear_with_bboxes",
"(",
"image",
",",
"bboxes",
",",
"level",
",",
"replace",
",",
"shear_horizontal",
")",
":",
"if",
"shear_horizontal",
":",
"image",
"=",
"shear_x",
"(",
"image",
",",
"level",
",",
"replace",
")",
"else",
":",
"image",
"=",
... | https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppdet/data/transform/autoaugment_utils.py#L1010-L1043 | |
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | python | UniSpeechSatAttention.__init__ | (
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
) | [] | def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim ** -0.5
self.is_decoder = is_decoder
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) | [
"def",
"__init__",
"(",
"self",
",",
"embed_dim",
":",
"int",
",",
"num_heads",
":",
"int",
",",
"dropout",
":",
"float",
"=",
"0.0",
",",
"is_decoder",
":",
"bool",
"=",
"False",
",",
"bias",
":",
"bool",
"=",
"True",
",",
")",
":",
"super",
"(",
... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/unispeech_sat/modeling_unispeech_sat.py#L475-L500 | ||||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | external/Scripting Engine/Xenotix Python Scripting Engine/Lib/ntpath.py | python | ismount | (path) | return len(p) == 1 and p[0] in '/\\' | Test whether a path is a mount point (defined as root of drive) | Test whether a path is a mount point (defined as root of drive) | [
"Test",
"whether",
"a",
"path",
"is",
"a",
"mount",
"point",
"(",
"defined",
"as",
"root",
"of",
"drive",
")"
] | def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
if unc:
return rest in ("", "/", "\\")
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in '/\\' | [
"def",
"ismount",
"(",
"path",
")",
":",
"unc",
",",
"rest",
"=",
"splitunc",
"(",
"path",
")",
"if",
"unc",
":",
"return",
"rest",
"in",
"(",
"\"\"",
",",
"\"/\"",
",",
"\"\\\\\"",
")",
"p",
"=",
"splitdrive",
"(",
"path",
")",
"[",
"1",
"]",
... | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/ntpath.py#L222-L228 | |
fedora-infra/anitya | cc01878ac023790646a76eb4cbef45d639e2372c | anitya/lib/backends/bitbucket.py | python | BitBucketBackend.get_version | (cls, project) | return cls.get_ordered_versions(project)[-1] | Method called to retrieve the latest version of the projects
provided, project that relies on the backend of this plugin.
:arg Project project: a :class:`anitya.db.models.Project` object whose backend
corresponds to the current plugin.
:return: the latest version found upstream
:return type: str
:raise AnityaPluginException: a
:class:`anitya.lib.exceptions.AnityaPluginException` exception
when the version cannot be retrieved correctly | Method called to retrieve the latest version of the projects
provided, project that relies on the backend of this plugin. | [
"Method",
"called",
"to",
"retrieve",
"the",
"latest",
"version",
"of",
"the",
"projects",
"provided",
"project",
"that",
"relies",
"on",
"the",
"backend",
"of",
"this",
"plugin",
"."
] | def get_version(cls, project):
"""Method called to retrieve the latest version of the projects
provided, project that relies on the backend of this plugin.
:arg Project project: a :class:`anitya.db.models.Project` object whose backend
corresponds to the current plugin.
:return: the latest version found upstream
:return type: str
:raise AnityaPluginException: a
:class:`anitya.lib.exceptions.AnityaPluginException` exception
when the version cannot be retrieved correctly
"""
return cls.get_ordered_versions(project)[-1] | [
"def",
"get_version",
"(",
"cls",
",",
"project",
")",
":",
"return",
"cls",
".",
"get_ordered_versions",
"(",
"project",
")",
"[",
"-",
"1",
"]"
] | https://github.com/fedora-infra/anitya/blob/cc01878ac023790646a76eb4cbef45d639e2372c/anitya/lib/backends/bitbucket.py#L32-L45 | |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | 5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e | deep-learning/fastai-docs/fastai_docs-master/dev_nb/nb_002.py | python | find_classes | (folder:Path) | return sorted(classes, key=lambda d: d.name) | Return class subdirectories in imagenet style train `folder` | Return class subdirectories in imagenet style train `folder` | [
"Return",
"class",
"subdirectories",
"in",
"imagenet",
"style",
"train",
"folder"
] | def find_classes(folder:Path)->FilePathList:
"Return class subdirectories in imagenet style train `folder`"
classes = [d for d in folder.iterdir()
if d.is_dir() and not d.name.startswith('.')]
assert(len(classes)>0)
return sorted(classes, key=lambda d: d.name) | [
"def",
"find_classes",
"(",
"folder",
":",
"Path",
")",
"->",
"FilePathList",
":",
"classes",
"=",
"[",
"d",
"for",
"d",
"in",
"folder",
".",
"iterdir",
"(",
")",
"if",
"d",
".",
"is_dir",
"(",
")",
"and",
"not",
"d",
".",
"name",
".",
"startswith"... | https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/deep-learning/fastai-docs/fastai_docs-master/dev_nb/nb_002.py#L42-L47 | |
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/sqlalchemy/schema.py | python | DDLElement.execute_if | (self, dialect=None, callable_=None, state=None) | Return a callable that will execute this
DDLElement conditionally.
Used to provide a wrapper for event listening::
event.listen(
metadata,
'before_create',
DDL("my_ddl").execute_if(dialect='postgresql')
)
:param dialect: May be a string, tuple or a callable
predicate. If a string, it will be compared to the name of the
executing database dialect::
DDL('something').execute_if(dialect='postgresql')
If a tuple, specifies multiple dialect names::
DDL('something').execute_if(dialect=('postgresql', 'mysql'))
:param callable_: A callable, which will be invoked with
four positional arguments as well as optional keyword
arguments:
:ddl:
This DDL element.
:target:
The :class:`.Table` or :class:`.MetaData` object which is the target of
this event. May be None if the DDL is executed explicitly.
:bind:
The :class:`.Connection` being used for DDL execution
:tables:
Optional keyword argument - a list of Table objects which are to
be created/ dropped within a MetaData.create_all() or drop_all()
method call.
:state:
Optional keyword argument - will be the ``state`` argument
passed to this function.
:checkfirst:
Keyword argument, will be True if the 'checkfirst' flag was
set during the call to ``create()``, ``create_all()``,
``drop()``, ``drop_all()``.
If the callable returns a true value, the DDL statement will be
executed.
:param state: any value which will be passed to the callable_
as the ``state`` keyword argument.
See also:
:class:`.DDLEvents`
:ref:`event_toplevel` | Return a callable that will execute this
DDLElement conditionally. | [
"Return",
"a",
"callable",
"that",
"will",
"execute",
"this",
"DDLElement",
"conditionally",
"."
] | def execute_if(self, dialect=None, callable_=None, state=None):
"""Return a callable that will execute this
DDLElement conditionally.
Used to provide a wrapper for event listening::
event.listen(
metadata,
'before_create',
DDL("my_ddl").execute_if(dialect='postgresql')
)
:param dialect: May be a string, tuple or a callable
predicate. If a string, it will be compared to the name of the
executing database dialect::
DDL('something').execute_if(dialect='postgresql')
If a tuple, specifies multiple dialect names::
DDL('something').execute_if(dialect=('postgresql', 'mysql'))
:param callable_: A callable, which will be invoked with
four positional arguments as well as optional keyword
arguments:
:ddl:
This DDL element.
:target:
The :class:`.Table` or :class:`.MetaData` object which is the target of
this event. May be None if the DDL is executed explicitly.
:bind:
The :class:`.Connection` being used for DDL execution
:tables:
Optional keyword argument - a list of Table objects which are to
be created/ dropped within a MetaData.create_all() or drop_all()
method call.
:state:
Optional keyword argument - will be the ``state`` argument
passed to this function.
:checkfirst:
Keyword argument, will be True if the 'checkfirst' flag was
set during the call to ``create()``, ``create_all()``,
``drop()``, ``drop_all()``.
If the callable returns a true value, the DDL statement will be
executed.
:param state: any value which will be passed to the callable_
as the ``state`` keyword argument.
See also:
:class:`.DDLEvents`
:ref:`event_toplevel`
"""
self.dialect = dialect
self.callable_ = callable_
self.state = state | [
"def",
"execute_if",
"(",
"self",
",",
"dialect",
"=",
"None",
",",
"callable_",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"self",
".",
"dialect",
"=",
"dialect",
"self",
".",
"callable_",
"=",
"callable_",
"self",
".",
"state",
"=",
"state"
] | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/schema.py#L2727-L2792 | ||
pydata/xarray | 9226c7ac87b3eb246f7a7e49f8f0f23d68951624 | xarray/core/computation.py | python | corr | (da_a, da_b, dim=None) | return _cov_corr(da_a, da_b, dim=dim, method="corr") | Compute the Pearson correlation coefficient between
two DataArray objects along a shared dimension.
Parameters
----------
da_a : DataArray
Array to compute.
da_b : DataArray
Array to compute.
dim : str, optional
The dimension along which the correlation will be computed
Returns
-------
correlation: DataArray
See Also
--------
pandas.Series.corr : corresponding pandas function
xarray.cov : underlying covariance function
Examples
--------
>>> from xarray import DataArray
>>> da_a = DataArray(
... np.array([[1, 2, 3], [0.1, 0.2, 0.3], [3.2, 0.6, 1.8]]),
... dims=("space", "time"),
... coords=[
... ("space", ["IA", "IL", "IN"]),
... ("time", pd.date_range("2000-01-01", freq="1D", periods=3)),
... ],
... )
>>> da_a
<xarray.DataArray (space: 3, time: 3)>
array([[1. , 2. , 3. ],
[0.1, 0.2, 0.3],
[3.2, 0.6, 1.8]])
Coordinates:
* space (space) <U2 'IA' 'IL' 'IN'
* time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03
>>> da_b = DataArray(
... np.array([[0.2, 0.4, 0.6], [15, 10, 5], [3.2, 0.6, 1.8]]),
... dims=("space", "time"),
... coords=[
... ("space", ["IA", "IL", "IN"]),
... ("time", pd.date_range("2000-01-01", freq="1D", periods=3)),
... ],
... )
>>> da_b
<xarray.DataArray (space: 3, time: 3)>
array([[ 0.2, 0.4, 0.6],
[15. , 10. , 5. ],
[ 3.2, 0.6, 1.8]])
Coordinates:
* space (space) <U2 'IA' 'IL' 'IN'
* time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03
>>> xr.corr(da_a, da_b)
<xarray.DataArray ()>
array(-0.57087777)
>>> xr.corr(da_a, da_b, dim="time")
<xarray.DataArray (space: 3)>
array([ 1., -1., 1.])
Coordinates:
* space (space) <U2 'IA' 'IL' 'IN' | Compute the Pearson correlation coefficient between
two DataArray objects along a shared dimension. | [
"Compute",
"the",
"Pearson",
"correlation",
"coefficient",
"between",
"two",
"DataArray",
"objects",
"along",
"a",
"shared",
"dimension",
"."
] | def corr(da_a, da_b, dim=None):
"""
Compute the Pearson correlation coefficient between
two DataArray objects along a shared dimension.
Parameters
----------
da_a : DataArray
Array to compute.
da_b : DataArray
Array to compute.
dim : str, optional
The dimension along which the correlation will be computed
Returns
-------
correlation: DataArray
See Also
--------
pandas.Series.corr : corresponding pandas function
xarray.cov : underlying covariance function
Examples
--------
>>> from xarray import DataArray
>>> da_a = DataArray(
... np.array([[1, 2, 3], [0.1, 0.2, 0.3], [3.2, 0.6, 1.8]]),
... dims=("space", "time"),
... coords=[
... ("space", ["IA", "IL", "IN"]),
... ("time", pd.date_range("2000-01-01", freq="1D", periods=3)),
... ],
... )
>>> da_a
<xarray.DataArray (space: 3, time: 3)>
array([[1. , 2. , 3. ],
[0.1, 0.2, 0.3],
[3.2, 0.6, 1.8]])
Coordinates:
* space (space) <U2 'IA' 'IL' 'IN'
* time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03
>>> da_b = DataArray(
... np.array([[0.2, 0.4, 0.6], [15, 10, 5], [3.2, 0.6, 1.8]]),
... dims=("space", "time"),
... coords=[
... ("space", ["IA", "IL", "IN"]),
... ("time", pd.date_range("2000-01-01", freq="1D", periods=3)),
... ],
... )
>>> da_b
<xarray.DataArray (space: 3, time: 3)>
array([[ 0.2, 0.4, 0.6],
[15. , 10. , 5. ],
[ 3.2, 0.6, 1.8]])
Coordinates:
* space (space) <U2 'IA' 'IL' 'IN'
* time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03
>>> xr.corr(da_a, da_b)
<xarray.DataArray ()>
array(-0.57087777)
>>> xr.corr(da_a, da_b, dim="time")
<xarray.DataArray (space: 3)>
array([ 1., -1., 1.])
Coordinates:
* space (space) <U2 'IA' 'IL' 'IN'
"""
from .dataarray import DataArray
if any(not isinstance(arr, DataArray) for arr in [da_a, da_b]):
raise TypeError(
"Only xr.DataArray is supported."
"Given {}.".format([type(arr) for arr in [da_a, da_b]])
)
return _cov_corr(da_a, da_b, dim=dim, method="corr") | [
"def",
"corr",
"(",
"da_a",
",",
"da_b",
",",
"dim",
"=",
"None",
")",
":",
"from",
".",
"dataarray",
"import",
"DataArray",
"if",
"any",
"(",
"not",
"isinstance",
"(",
"arr",
",",
"DataArray",
")",
"for",
"arr",
"in",
"[",
"da_a",
",",
"da_b",
"]"... | https://github.com/pydata/xarray/blob/9226c7ac87b3eb246f7a7e49f8f0f23d68951624/xarray/core/computation.py#L1262-L1337 | |
JDAI-CV/DCL | 895081603dc68aeeda07301dbddf32b364ecacf7 | transforms/transforms.py | python | RandomRotation.get_params | (degrees) | return angle | Get parameters for ``rotate`` for a random rotation.
Returns:
sequence: params to be passed to ``rotate`` for random rotation. | Get parameters for ``rotate`` for a random rotation. | [
"Get",
"parameters",
"for",
"rotate",
"for",
"a",
"random",
"rotation",
"."
] | def get_params(degrees):
"""Get parameters for ``rotate`` for a random rotation.
Returns:
sequence: params to be passed to ``rotate`` for random rotation.
"""
angle = random.uniform(degrees[0], degrees[1])
return angle | [
"def",
"get_params",
"(",
"degrees",
")",
":",
"angle",
"=",
"random",
".",
"uniform",
"(",
"degrees",
"[",
"0",
"]",
",",
"degrees",
"[",
"1",
"]",
")",
"return",
"angle"
] | https://github.com/JDAI-CV/DCL/blob/895081603dc68aeeda07301dbddf32b364ecacf7/transforms/transforms.py#L818-L826 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/lib/_datasource.py | python | open | (path, mode='r', destpath=os.curdir, encoding=None, newline=None) | return ds.open(path, mode, encoding=encoding, newline=newline) | Open `path` with `mode` and return the file object.
If ``path`` is an URL, it will be downloaded, stored in the
`DataSource` `destpath` directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open.
mode : str, optional
Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
append. Available modes depend on the type of object specified by
path. Default is 'r'.
destpath : str, optional
Path to the directory where the source file gets downloaded to for
use. If `destpath` is None, a temporary directory will be created.
The default path is the current directory.
encoding : {None, str}, optional
Open text file with given encoding. The default encoding will be
what `io.open` uses.
newline : {None, str}, optional
Newline to use when reading text file.
Returns
-------
out : file object
The opened file.
Notes
-----
This is a convenience function that instantiates a `DataSource` and
returns the file object from ``DataSource.open(path)``. | Open `path` with `mode` and return the file object. | [
"Open",
"path",
"with",
"mode",
"and",
"return",
"the",
"file",
"object",
"."
] | def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None):
"""
Open `path` with `mode` and return the file object.
If ``path`` is an URL, it will be downloaded, stored in the
`DataSource` `destpath` directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open.
mode : str, optional
Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
append. Available modes depend on the type of object specified by
path. Default is 'r'.
destpath : str, optional
Path to the directory where the source file gets downloaded to for
use. If `destpath` is None, a temporary directory will be created.
The default path is the current directory.
encoding : {None, str}, optional
Open text file with given encoding. The default encoding will be
what `io.open` uses.
newline : {None, str}, optional
Newline to use when reading text file.
Returns
-------
out : file object
The opened file.
Notes
-----
This is a convenience function that instantiates a `DataSource` and
returns the file object from ``DataSource.open(path)``.
"""
ds = DataSource(destpath)
return ds.open(path, mode, encoding=encoding, newline=newline) | [
"def",
"open",
"(",
"path",
",",
"mode",
"=",
"'r'",
",",
"destpath",
"=",
"os",
".",
"curdir",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"ds",
"=",
"DataSource",
"(",
"destpath",
")",
"return",
"ds",
".",
"open",
"(",
... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/lib/_datasource.py#L228-L266 | |
python-telegram-bot/python-telegram-bot | ade1529986f5b6d394a65372d6a27045a70725b2 | setup.py | python | main | () | [] | def main():
# If we're building, build ptb-raw as well
if set(sys.argv[1:]) in [{'bdist_wheel'}, {'sdist'}, {'sdist', 'bdist_wheel'}]:
args = ['python', 'setup-raw.py']
args.extend(sys.argv[1:])
subprocess.run(args, check=True, capture_output=True)
setup(**get_setup_kwargs(raw=False)) | [
"def",
"main",
"(",
")",
":",
"# If we're building, build ptb-raw as well",
"if",
"set",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"in",
"[",
"{",
"'bdist_wheel'",
"}",
",",
"{",
"'sdist'",
"}",
",",
"{",
"'sdist'",
",",
"'bdist_wheel'",
"}",
"... | https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/setup.py#L112-L119 | ||||
emposha/Shell-Detector | 5ac8ab2bf514bea737ddff16a75d85d887478f85 | shelldetect.py | python | PhpSerializer._unserialize_array | (self, s) | return (a, s[1:]) | [] | def _unserialize_array(self, s):
(l, _, s) = s.partition(':')
a, k, s = {}, None, s[1:]
for i in range(0, int(l) * 2):
(v, s) = PhpSerializer._unserialize_var(self, s)
if k:
a[k] = v
k = None
else:
k = v
return (a, s[1:]) | [
"def",
"_unserialize_array",
"(",
"self",
",",
"s",
")",
":",
"(",
"l",
",",
"_",
",",
"s",
")",
"=",
"s",
".",
"partition",
"(",
"':'",
")",
"a",
",",
"k",
",",
"s",
"=",
"{",
"}",
",",
"None",
",",
"s",
"[",
"1",
":",
"]",
"for",
"i",
... | https://github.com/emposha/Shell-Detector/blob/5ac8ab2bf514bea737ddff16a75d85d887478f85/shelldetect.py#L61-L74 | |||
urwid/urwid | e2423b5069f51d318ea1ac0f355a0efe5448f7eb | docs/tutorial/adventure.py | python | Thing.__init__ | (self, name) | [] | def __init__(self, name):
super(Thing, self).__init__(
ActionButton([u" * take ", name], self.take_thing))
self.name = name | [
"def",
"__init__",
"(",
"self",
",",
"name",
")",
":",
"super",
"(",
"Thing",
",",
"self",
")",
".",
"__init__",
"(",
"ActionButton",
"(",
"[",
"u\" * take \"",
",",
"name",
"]",
",",
"self",
".",
"take_thing",
")",
")",
"self",
".",
"name",
"=",
"... | https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/docs/tutorial/adventure.py#L24-L27 | ||||
QData/TextAttack | 33c98738b84e88a46d9f01f17b85ec595863b43a | textattack/goal_function_results/text_to_text_goal_function_result.py | python | TextToTextGoalFunctionResult.get_text_color_perturbed | (self) | return "blue" | A string representing the color this result's changed portion should
be if it represents the perturbed input. | A string representing the color this result's changed portion should
be if it represents the perturbed input. | [
"A",
"string",
"representing",
"the",
"color",
"this",
"result",
"s",
"changed",
"portion",
"should",
"be",
"if",
"it",
"represents",
"the",
"perturbed",
"input",
"."
] | def get_text_color_perturbed(self):
"""A string representing the color this result's changed portion should
be if it represents the perturbed input."""
return "blue" | [
"def",
"get_text_color_perturbed",
"(",
"self",
")",
":",
"return",
"\"blue\""
] | https://github.com/QData/TextAttack/blob/33c98738b84e88a46d9f01f17b85ec595863b43a/textattack/goal_function_results/text_to_text_goal_function_result.py#L21-L24 | |
wrye-bash/wrye-bash | d495c47cfdb44475befa523438a40c4419cb386f | Mopy/bash/bosh/_saves.py | python | SreNPC.dumpText | (self,saveFile) | return buff.getvalue() | Returns informal string representation of data. | Returns informal string representation of data. | [
"Returns",
"informal",
"string",
"representation",
"of",
"data",
"."
] | def dumpText(self,saveFile):
"""Returns informal string representation of data."""
buff = io.StringIO()
fids = saveFile.fids
if self.form is not None:
buff.write(u'Form:\n %d' % self.form)
if self.attributes is not None:
buff.write(
u'Attributes\n strength %3d\n intelligence %3d\n '
u'willpower %3d\n agility %3d\n speed %3d\n endurance '
u'%3d\n personality %3d\n luck %3d\n' % tuple(
self.attributes))
if self.acbs is not None:
buff.write(u'ACBS:\n')
for attr in SreNPC.ACBS.__slots__:
buff.write(u' %s %s\n' % (attr, getattr(self.acbs, attr)))
if self.factions is not None:
buff.write(u'Factions:\n')
for faction in self.factions:
buff.write(u' %8X %2X\n' % (fids[faction[0]], faction[1]))
if self.spells is not None:
buff.write(u'Spells:\n')
for spell in self.spells:
buff.write(u' %8X\n' % fids[spell])
if self.ai is not None:
buff.write(_(u'AI')+u':\n ' + self.ai + u'\n')
if self.health is not None:
buff.write(u'Health\n %s\n' % self.health)
buff.write(u'Unused2\n %s\n' % self.unused2)
if self.modifiers is not None:
buff.write(u'Modifiers:\n')
for modifier in self.modifiers:
buff.write(u' %s\n' % modifier)
if self.full is not None:
buff.write(u'Full:\n %s\n' % self.full)
if self.skills is not None:
buff.write(
u'Skills:\n armorer %3d\n athletics %3d\n blade %3d\n '
u' block %3d\n blunt %3d\n handToHand %3d\n '
u'heavyArmor %3d\n alchemy %3d\n alteration %3d\n '
u'conjuration %3d\n destruction %3d\n illusion %3d\n '
u'mysticism %3d\n restoration %3d\n acrobatics %3d\n '
u'lightArmor %3d\n marksman %3d\n mercantile %3d\n '
u'security %3d\n sneak %3d\n speechcraft %3d\n' % tuple(
self.skills))
return buff.getvalue() | [
"def",
"dumpText",
"(",
"self",
",",
"saveFile",
")",
":",
"buff",
"=",
"io",
".",
"StringIO",
"(",
")",
"fids",
"=",
"saveFile",
".",
"fids",
"if",
"self",
".",
"form",
"is",
"not",
"None",
":",
"buff",
".",
"write",
"(",
"u'Form:\\n %d'",
"%",
"... | https://github.com/wrye-bash/wrye-bash/blob/d495c47cfdb44475befa523438a40c4419cb386f/Mopy/bash/bosh/_saves.py#L176-L221 | |
nopernik/mpDNS | b17dc39e7068406df82cb3431b3042e74e520cf9 | dnslib/dns.py | python | SRV.__init__ | (self,priority=0,weight=0,port=0,target=None) | [] | def __init__(self,priority=0,weight=0,port=0,target=None):
self.priority = priority
self.weight = weight
self.port = port
self.target = target | [
"def",
"__init__",
"(",
"self",
",",
"priority",
"=",
"0",
",",
"weight",
"=",
"0",
",",
"port",
"=",
"0",
",",
"target",
"=",
"None",
")",
":",
"self",
".",
"priority",
"=",
"priority",
"self",
".",
"weight",
"=",
"weight",
"self",
".",
"port",
... | https://github.com/nopernik/mpDNS/blob/b17dc39e7068406df82cb3431b3042e74e520cf9/dnslib/dns.py#L1355-L1359 | ||||
ddbourgin/numpy-ml | b0359af5285fbf9699d64fd5ec059493228af03e | numpy_ml/neural_nets/layers/layers.py | python | BatchNorm1D.reset_running_stats | (self) | Reset the running mean and variance estimates to 0 and 1. | Reset the running mean and variance estimates to 0 and 1. | [
"Reset",
"the",
"running",
"mean",
"and",
"variance",
"estimates",
"to",
"0",
"and",
"1",
"."
] | def reset_running_stats(self):
"""Reset the running mean and variance estimates to 0 and 1."""
assert self.trainable, "Layer is frozen"
self.parameters["running_mean"] = np.zeros(self.n_in)
self.parameters["running_var"] = np.ones(self.n_in) | [
"def",
"reset_running_stats",
"(",
"self",
")",
":",
"assert",
"self",
".",
"trainable",
",",
"\"Layer is frozen\"",
"self",
".",
"parameters",
"[",
"\"running_mean\"",
"]",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"n_in",
")",
"self",
".",
"parameters",
... | https://github.com/ddbourgin/numpy-ml/blob/b0359af5285fbf9699d64fd5ec059493228af03e/numpy_ml/neural_nets/layers/layers.py#L1336-L1340 | ||
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/fimap/plugininterface.py | python | pluginXMLInfo.__init__ | (self, xmlfile) | [] | def __init__(self, xmlfile):
self.xmlFile = xmlfile
if (os.path.exists(xmlfile)):
XML_plugin = xml.dom.minidom.parse(xmlfile)
XML_Rootitem = XML_plugin.firstChild
self.name = str(XML_Rootitem.getAttribute("name"))
self.startupclass = str(XML_Rootitem.getAttribute("startup"))
self.autor = str(XML_Rootitem.getAttribute("autor"))
self.email = str(XML_Rootitem.getAttribute("email"))
self.version = int(XML_Rootitem.getAttribute("version"))
self.url = str(XML_Rootitem.getAttribute("url")) | [
"def",
"__init__",
"(",
"self",
",",
"xmlfile",
")",
":",
"self",
".",
"xmlFile",
"=",
"xmlfile",
"if",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"xmlfile",
")",
")",
":",
"XML_plugin",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parse",
"(",
... | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/fimap/plugininterface.py#L94-L105 | ||||
niosus/EasyClangComplete | 3b16eb17735aaa3f56bb295fc5481b269ee9f2ef | plugin/clang/cindex40.py | python | Cursor.is_default_constructor | (self) | return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) | Returns True if the cursor refers to a C++ default constructor. | Returns True if the cursor refers to a C++ default constructor. | [
"Returns",
"True",
"if",
"the",
"cursor",
"refers",
"to",
"a",
"C",
"++",
"default",
"constructor",
"."
] | def is_default_constructor(self):
"""Returns True if the cursor refers to a C++ default constructor.
"""
return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) | [
"def",
"is_default_constructor",
"(",
"self",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_CXXConstructor_isDefaultConstructor",
"(",
"self",
")"
] | https://github.com/niosus/EasyClangComplete/blob/3b16eb17735aaa3f56bb295fc5481b269ee9f2ef/plugin/clang/cindex40.py#L1373-L1376 | |
Fallen-Breath/MCDReforged | fdb1d2520b35f916123f265dbd94603981bb2b0c | mcdreforged/handler/abstract_server_handler.py | python | AbstractServerHandler.test_server_stopping | (self, info: Info) | Check if the server is stopping and return a bool
:param Info info: The info instance that will be checked
:return: If the server is stopping
:rtype: bool | Check if the server is stopping and return a bool | [
"Check",
"if",
"the",
"server",
"is",
"stopping",
"and",
"return",
"a",
"bool"
] | def test_server_stopping(self, info: Info) -> bool:
"""
Check if the server is stopping and return a bool
:param Info info: The info instance that will be checked
:return: If the server is stopping
:rtype: bool
"""
raise NotImplementedError() | [
"def",
"test_server_stopping",
"(",
"self",
",",
"info",
":",
"Info",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/Fallen-Breath/MCDReforged/blob/fdb1d2520b35f916123f265dbd94603981bb2b0c/mcdreforged/handler/abstract_server_handler.py#L222-L230 | ||
pika/pika | 12dcdf15d0932c388790e0fa990810bfd21b1a32 | pika/adapters/select_connection.py | python | _Timeout.__ge__ | (self, other) | return NotImplemented | NOTE: not supporting sort stability | NOTE: not supporting sort stability | [
"NOTE",
":",
"not",
"supporting",
"sort",
"stability"
] | def __ge__(self, other):
"""NOTE: not supporting sort stability"""
if isinstance(other, _Timeout):
return self.deadline >= other.deadline
return NotImplemented | [
"def",
"__ge__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"_Timeout",
")",
":",
"return",
"self",
".",
"deadline",
">=",
"other",
".",
"deadline",
"return",
"NotImplemented"
] | https://github.com/pika/pika/blob/12dcdf15d0932c388790e0fa990810bfd21b1a32/pika/adapters/select_connection.py#L204-L208 | |
geoopt/geoopt | c0163cde17aa215aa0f34e833364ac918ec5e974 | geoopt/manifolds/base.py | python | Manifold.norm | (self, x: torch.Tensor, u: torch.Tensor, *, keepdim=False) | return self.inner(x, u, keepdim=keepdim) ** 0.5 | Norm of a tangent vector at point :math:`x`.
Parameters
----------
x : torch.Tensor
point on the manifold
u : torch.Tensor
tangent vector at point :math:`x`
keepdim : bool
keep the last dim?
Returns
-------
torch.Tensor
inner product (broadcasted) | Norm of a tangent vector at point :math:`x`. | [
"Norm",
"of",
"a",
"tangent",
"vector",
"at",
"point",
":",
"math",
":",
"x",
"."
] | def norm(self, x: torch.Tensor, u: torch.Tensor, *, keepdim=False) -> torch.Tensor:
"""
Norm of a tangent vector at point :math:`x`.
Parameters
----------
x : torch.Tensor
point on the manifold
u : torch.Tensor
tangent vector at point :math:`x`
keepdim : bool
keep the last dim?
Returns
-------
torch.Tensor
inner product (broadcasted)
"""
return self.inner(x, u, keepdim=keepdim) ** 0.5 | [
"def",
"norm",
"(",
"self",
",",
"x",
":",
"torch",
".",
"Tensor",
",",
"u",
":",
"torch",
".",
"Tensor",
",",
"*",
",",
"keepdim",
"=",
"False",
")",
"->",
"torch",
".",
"Tensor",
":",
"return",
"self",
".",
"inner",
"(",
"x",
",",
"u",
",",
... | https://github.com/geoopt/geoopt/blob/c0163cde17aa215aa0f34e833364ac918ec5e974/geoopt/manifolds/base.py#L663-L681 | |
smicallef/spiderfoot | fd4bf9394c9ab3ecc90adc3115c56349fb23165b | modules/sfp_crxcavator.py | python | sfp_crxcavator.setup | (self, sfc, userOpts=dict()) | [] | def setup(self, sfc, userOpts=dict()):
self.sf = sfc
self.results = self.tempStorage()
for opt in list(userOpts.keys()):
self.opts[opt] = userOpts[opt] | [
"def",
"setup",
"(",
"self",
",",
"sfc",
",",
"userOpts",
"=",
"dict",
"(",
")",
")",
":",
"self",
".",
"sf",
"=",
"sfc",
"self",
".",
"results",
"=",
"self",
".",
"tempStorage",
"(",
")",
"for",
"opt",
"in",
"list",
"(",
"userOpts",
".",
"keys",... | https://github.com/smicallef/spiderfoot/blob/fd4bf9394c9ab3ecc90adc3115c56349fb23165b/modules/sfp_crxcavator.py#L52-L57 | ||||
FederatedAI/FATE | 32540492623568ecd1afcb367360133616e02fa3 | python/federatedml/evaluation/metrics/classification_metric.py | python | BiClassAccuracy.compute | (self, labels, scores, normalize=True) | return list(metric_scores), score_threshold[: len(metric_scores)], cuts[: len(metric_scores)] | [] | def compute(self, labels, scores, normalize=True):
confusion_mat, score_threshold, cuts = self.prepare_confusion_mat(labels, scores)
metric_scores = self.compute_metric_from_confusion_mat(confusion_mat, normalize=normalize)
return list(metric_scores), score_threshold[: len(metric_scores)], cuts[: len(metric_scores)] | [
"def",
"compute",
"(",
"self",
",",
"labels",
",",
"scores",
",",
"normalize",
"=",
"True",
")",
":",
"confusion_mat",
",",
"score_threshold",
",",
"cuts",
"=",
"self",
".",
"prepare_confusion_mat",
"(",
"labels",
",",
"scores",
")",
"metric_scores",
"=",
... | https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/evaluation/metrics/classification_metric.py#L361-L364 | |||
cwoac/nvvim | 8b4a7cc4b94f6971d590fc6622175f24cbb5eec7 | python/nvim.py | python | populate_complete | (base='') | Looks up the values to populate the [[...]] completion box. | Looks up the values to populate the [[...]] completion box. | [
"Looks",
"up",
"the",
"values",
"to",
"populate",
"the",
"[[",
"...",
"]]",
"completion",
"box",
"."
] | def populate_complete(base=''): # {{{
''' Looks up the values to populate the [[...]] completion box.
'''
hits = ["'" + r.document.get_value(1) + "'" for r in nvimdb.get(base)]
result = ','.join(hits)
vim.command("let g:nvim_ret=[" + result + "]") | [
"def",
"populate_complete",
"(",
"base",
"=",
"''",
")",
":",
"# {{{",
"hits",
"=",
"[",
"\"'\"",
"+",
"r",
".",
"document",
".",
"get_value",
"(",
"1",
")",
"+",
"\"'\"",
"for",
"r",
"in",
"nvimdb",
".",
"get",
"(",
"base",
")",
"]",
"result",
"... | https://github.com/cwoac/nvvim/blob/8b4a7cc4b94f6971d590fc6622175f24cbb5eec7/python/nvim.py#L153-L158 | ||
gramps-project/gramps | 04d4651a43eb210192f40a9f8c2bad8ee8fa3753 | gramps/gui/widgets/validatedmaskedentry.py | python | MaskedEntry.set_exact_completion | (self, value) | Enable exact entry completion.
Exact means it needs to start with the value typed
and the case needs to be correct.
:param value: enable exact completion
:type value: boolean | Enable exact entry completion.
Exact means it needs to start with the value typed
and the case needs to be correct. | [
"Enable",
"exact",
"entry",
"completion",
".",
"Exact",
"means",
"it",
"needs",
"to",
"start",
"with",
"the",
"value",
"typed",
"and",
"the",
"case",
"needs",
"to",
"be",
"correct",
"."
] | def set_exact_completion(self, value):
"""
Enable exact entry completion.
Exact means it needs to start with the value typed
and the case needs to be correct.
:param value: enable exact completion
:type value: boolean
"""
self._exact_completion = value
if value:
match_func = self._completion_exact_match_func
else:
match_func = self._completion_normal_match_func
completion = self._get_completion()
completion.set_match_func(match_func, None) | [
"def",
"set_exact_completion",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_exact_completion",
"=",
"value",
"if",
"value",
":",
"match_func",
"=",
"self",
".",
"_completion_exact_match_func",
"else",
":",
"match_func",
"=",
"self",
".",
"_completion_norm... | https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/widgets/validatedmaskedentry.py#L426-L442 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/messaging/v1/service/__init__.py | python | ServiceInstance.status_callback | (self) | return self._properties['status_callback'] | :returns: The URL we call to pass status updates about message delivery
:rtype: unicode | :returns: The URL we call to pass status updates about message delivery
:rtype: unicode | [
":",
"returns",
":",
"The",
"URL",
"we",
"call",
"to",
"pass",
"status",
"updates",
"about",
"message",
"delivery",
":",
"rtype",
":",
"unicode"
] | def status_callback(self):
"""
:returns: The URL we call to pass status updates about message delivery
:rtype: unicode
"""
return self._properties['status_callback'] | [
"def",
"status_callback",
"(",
"self",
")",
":",
"return",
"self",
".",
"_properties",
"[",
"'status_callback'",
"]"
] | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/messaging/v1/service/__init__.py#L557-L562 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/compiler/pyassem.py | python | StackDepthTracker.CALL_FUNCTION_KW | (self, argc) | return self.CALL_FUNCTION(argc)-1 | [] | def CALL_FUNCTION_KW(self, argc):
return self.CALL_FUNCTION(argc)-1 | [
"def",
"CALL_FUNCTION_KW",
"(",
"self",
",",
"argc",
")",
":",
"return",
"self",
".",
"CALL_FUNCTION",
"(",
"argc",
")",
"-",
"1"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/pyassem.py#L746-L747 | |||
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/barpolar/marker/_colorbar.py | python | ColorBar.tickmode | (self) | return self["tickmode"] | Sets the tick mode for this axis. If "auto", the number of
ticks is set via `nticks`. If "linear", the placement of the
ticks is determined by a starting position `tick0` and a tick
step `dtick` ("linear" is the default value if `tick0` and
`dtick` are provided). If "array", the placement of the ticks
is set via `tickvals` and the tick text is `ticktext`. ("array"
is the default value if `tickvals` is provided).
The 'tickmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'linear', 'array']
Returns
-------
Any | Sets the tick mode for this axis. If "auto", the number of
ticks is set via `nticks`. If "linear", the placement of the
ticks is determined by a starting position `tick0` and a tick
step `dtick` ("linear" is the default value if `tick0` and
`dtick` are provided). If "array", the placement of the ticks
is set via `tickvals` and the tick text is `ticktext`. ("array"
is the default value if `tickvals` is provided).
The 'tickmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'linear', 'array'] | [
"Sets",
"the",
"tick",
"mode",
"for",
"this",
"axis",
".",
"If",
"auto",
"the",
"number",
"of",
"ticks",
"is",
"set",
"via",
"nticks",
".",
"If",
"linear",
"the",
"placement",
"of",
"the",
"ticks",
"is",
"determined",
"by",
"a",
"starting",
"position",
... | def tickmode(self):
"""
Sets the tick mode for this axis. If "auto", the number of
ticks is set via `nticks`. If "linear", the placement of the
ticks is determined by a starting position `tick0` and a tick
step `dtick` ("linear" is the default value if `tick0` and
`dtick` are provided). If "array", the placement of the ticks
is set via `tickvals` and the tick text is `ticktext`. ("array"
is the default value if `tickvals` is provided).
The 'tickmode' property is an enumeration that may be specified as:
- One of the following enumeration values:
['auto', 'linear', 'array']
Returns
-------
Any
"""
return self["tickmode"] | [
"def",
"tickmode",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"tickmode\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/barpolar/marker/_colorbar.py#L948-L966 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/plat-sunos5/STROPTS.py | python | dtop | (DD) | return (((DD) + NDPP - 1) >> (PAGESHIFT - DEV_BSHIFT)) | [] | def dtop(DD): return (((DD) + NDPP - 1) >> (PAGESHIFT - DEV_BSHIFT)) | [
"def",
"dtop",
"(",
"DD",
")",
":",
"return",
"(",
"(",
"(",
"DD",
")",
"+",
"NDPP",
"-",
"1",
")",
">>",
"(",
"PAGESHIFT",
"-",
"DEV_BSHIFT",
")",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-sunos5/STROPTS.py#L153-L153 | |||
mapnik/Cascadenik | 82f66859340a31dfcb24af127274f262d4f3ad85 | cascadenik/output.py | python | LineSymbolizer.__repr__ | (self) | return 'Line(%s, %s)' % (self.color, self.width) | [] | def __repr__(self):
return 'Line(%s, %s)' % (self.color, self.width) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'Line(%s, %s)'",
"%",
"(",
"self",
".",
"color",
",",
"self",
".",
"width",
")"
] | https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/output.py#L237-L238 | |||
getpatchwork/patchwork | 60a7b11d12f9e1a6bd08d787d37066c8d89a52ae | patchwork/filters.py | python | SeriesFilter.key | (self, key) | [] | def key(self, key):
self.series = None
key = key.strip()
if not key:
return
try:
self.series = Series.objects.get(id=int(key))
except (ValueError, Series.DoesNotExist):
return
self.applied = True | [
"def",
"key",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"series",
"=",
"None",
"key",
"=",
"key",
".",
"strip",
"(",
")",
"if",
"not",
"key",
":",
"return",
"try",
":",
"self",
".",
"series",
"=",
"Series",
".",
"objects",
".",
"get",
"("... | https://github.com/getpatchwork/patchwork/blob/60a7b11d12f9e1a6bd08d787d37066c8d89a52ae/patchwork/filters.py#L92-L104 | ||||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/json/encoder.py | python | JSONEncoder.__init__ | (self, *, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, default=None) | Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming non-ASCII characters escaped. If
ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be an (item_separator, key_separator)
tuple. The default is (', ', ': ') if *indent* is ``None`` and
(',', ': ') otherwise. To get the most compact JSON representation,
you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``. | Constructor for JSONEncoder, with sensible defaults. | [
"Constructor",
"for",
"JSONEncoder",
"with",
"sensible",
"defaults",
"."
] | def __init__(self, *, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, default=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming non-ASCII characters escaped. If
ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be an (item_separator, key_separator)
tuple. The default is (', ', ': ') if *indent* is ``None`` and
(',', ': ') otherwise. To get the most compact JSON representation,
you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
elif indent is not None:
self.item_separator = ','
if default is not None:
self.default = default | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"skipkeys",
"=",
"False",
",",
"ensure_ascii",
"=",
"True",
",",
"check_circular",
"=",
"True",
",",
"allow_nan",
"=",
"True",
",",
"sort_keys",
"=",
"False",
",",
"indent",
"=",
"None",
",",
"separators",
... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/json/encoder.py#L104-L158 | ||
ask/mode | a104009f0c96790b9f6140179b4968da07a38c81 | mode/utils/queues.py | python | FlowControlEvent.acquire | (self) | Wait until flow control is resumed. | Wait until flow control is resumed. | [
"Wait",
"until",
"flow",
"control",
"is",
"resumed",
"."
] | async def acquire(self) -> None:
"""Wait until flow control is resumed."""
if self._suspend.is_set():
await self._resume.wait() | [
"async",
"def",
"acquire",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_suspend",
".",
"is_set",
"(",
")",
":",
"await",
"self",
".",
"_resume",
".",
"wait",
"(",
")"
] | https://github.com/ask/mode/blob/a104009f0c96790b9f6140179b4968da07a38c81/mode/utils/queues.py#L87-L90 | ||
zim-desktop-wiki/zim-desktop-wiki | fe717d7ee64e5c06d90df90eb87758e5e72d25c5 | zim/history.py | python | History.set_current | (self, path) | Set current path (changes the pointer, does not change
the list of pages)
@param path: a L{HistoryPath} object
@raises ValueError: when the path is not in the history list | Set current path (changes the pointer, does not change
the list of pages) | [
"Set",
"current",
"path",
"(",
"changes",
"the",
"pointer",
"does",
"not",
"change",
"the",
"list",
"of",
"pages",
")"
] | def set_current(self, path):
'''Set current path (changes the pointer, does not change
the list of pages)
@param path: a L{HistoryPath} object
@raises ValueError: when the path is not in the history list
'''
assert isinstance(path, HistoryPath)
self._current = self._history.index(path)
# fails if path not in history
if not isinstance(path, RecentPath) \
and self._update_recent(path):
self.emit('changed') | [
"def",
"set_current",
"(",
"self",
",",
"path",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"HistoryPath",
")",
"self",
".",
"_current",
"=",
"self",
".",
"_history",
".",
"index",
"(",
"path",
")",
"# fails if path not in history",
"if",
"not",
"i... | https://github.com/zim-desktop-wiki/zim-desktop-wiki/blob/fe717d7ee64e5c06d90df90eb87758e5e72d25c5/zim/history.py#L253-L264 | ||
tav/pylibs | 3c16b843681f54130ee6a022275289cadb2f2a69 | paramiko/channel.py | python | Channel.setblocking | (self, blocking) | Set blocking or non-blocking mode of the channel: if C{blocking} is 0,
the channel is set to non-blocking mode; otherwise it's set to blocking
mode. Initially all channels are in blocking mode.
In non-blocking mode, if a L{recv} call doesn't find any data, or if a
L{send} call can't immediately dispose of the data, an error exception
is raised. In blocking mode, the calls block until they can proceed. An
EOF condition is considered "immediate data" for L{recv}, so if the
channel is closed in the read direction, it will never block.
C{chan.setblocking(0)} is equivalent to C{chan.settimeout(0)};
C{chan.setblocking(1)} is equivalent to C{chan.settimeout(None)}.
@param blocking: 0 to set non-blocking mode; non-0 to set blocking
mode.
@type blocking: int | Set blocking or non-blocking mode of the channel: if C{blocking} is 0,
the channel is set to non-blocking mode; otherwise it's set to blocking
mode. Initially all channels are in blocking mode. | [
"Set",
"blocking",
"or",
"non",
"-",
"blocking",
"mode",
"of",
"the",
"channel",
":",
"if",
"C",
"{",
"blocking",
"}",
"is",
"0",
"the",
"channel",
"is",
"set",
"to",
"non",
"-",
"blocking",
"mode",
";",
"otherwise",
"it",
"s",
"set",
"to",
"blocking... | def setblocking(self, blocking):
"""
Set blocking or non-blocking mode of the channel: if C{blocking} is 0,
the channel is set to non-blocking mode; otherwise it's set to blocking
mode. Initially all channels are in blocking mode.
In non-blocking mode, if a L{recv} call doesn't find any data, or if a
L{send} call can't immediately dispose of the data, an error exception
is raised. In blocking mode, the calls block until they can proceed. An
EOF condition is considered "immediate data" for L{recv}, so if the
channel is closed in the read direction, it will never block.
C{chan.setblocking(0)} is equivalent to C{chan.settimeout(0)};
C{chan.setblocking(1)} is equivalent to C{chan.settimeout(None)}.
@param blocking: 0 to set non-blocking mode; non-0 to set blocking
mode.
@type blocking: int
"""
if blocking:
self.settimeout(None)
else:
self.settimeout(0.0) | [
"def",
"setblocking",
"(",
"self",
",",
"blocking",
")",
":",
"if",
"blocking",
":",
"self",
".",
"settimeout",
"(",
"None",
")",
"else",
":",
"self",
".",
"settimeout",
"(",
"0.0",
")"
] | https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/paramiko/channel.py#L495-L517 | ||
alduxvm/DronePilot | 08848522a7342057209d5e82d3b554e53e394e0f | modules/pyrenn.py | python | calc_error | (net,data) | return E | Calculate Error for NN based on data
Args:
net: neural network
data: Training Data
Returns:
E: Mean squared Error of the Neural Network compared to Training data | Calculate Error for NN based on data
Args:
net: neural network
data: Training Data
Returns:
E: Mean squared Error of the Neural Network compared to Training data | [
"Calculate",
"Error",
"for",
"NN",
"based",
"on",
"data",
"Args",
":",
"net",
":",
"neural",
"network",
"data",
":",
"Training",
"Data",
"Returns",
":",
"E",
":",
"Mean",
"squared",
"Error",
"of",
"the",
"Neural",
"Network",
"compared",
"to",
"Training",
... | def calc_error(net,data):
""" Calculate Error for NN based on data
Args:
net: neural network
data: Training Data
Returns:
E: Mean squared Error of the Neural Network compared to Training data
"""
P = data['P'] #Training data Inputs
Y = data['Y'] #Training data Outputs
a = data['a'] #Layer Outputs
q0 = data['q0'] #Use training data [q0:]
IW,LW,b = w2Wb(net) #input-weight matrices,connection weight matrices, bias vectors
########################
# 1. Calculate NN Output
Y_NN,n,a = NNOut_(P,net,IW,LW,b,a=a,q0=q0)
########################
# 2. Calculate Cost function E
Y_delta = Y - Y_NN #error matrix
e = np.reshape(Y_delta,(1,np.size(Y_delta)),order='F')[0] #error vector
E = np.dot(e,e.transpose()) #Cost function (mean squared error)
return E | [
"def",
"calc_error",
"(",
"net",
",",
"data",
")",
":",
"P",
"=",
"data",
"[",
"'P'",
"]",
"#Training data Inputs",
"Y",
"=",
"data",
"[",
"'Y'",
"]",
"#Training data Outputs",
"a",
"=",
"data",
"[",
"'a'",
"]",
"#Layer Outputs",
"q0",
"=",
"data",
"["... | https://github.com/alduxvm/DronePilot/blob/08848522a7342057209d5e82d3b554e53e394e0f/modules/pyrenn.py#L749-L775 | |
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/models/neural_architecture_search/nas_model.py | python | nas_seq2seq_base | () | return hparams | Base parameters for Nas Seq2Seq model.
The default parameters are set to create the Transformer.
Returns:
Hyperparameters for Nas Seq2Seq model. | Base parameters for Nas Seq2Seq model. | [
"Base",
"parameters",
"for",
"Nas",
"Seq2Seq",
"model",
"."
] | def nas_seq2seq_base():
"""Base parameters for Nas Seq2Seq model.
The default parameters are set to create the Transformer.
Returns:
Hyperparameters for Nas Seq2Seq model.
"""
hparams = transformer.transformer_base()
hparams.add_hparam("encoder_num_cells", 6)
hparams.add_hparam("encoder_left_inputs", [0, 1, 2, 3])
hparams.add_hparam("encoder_left_layers", [
"standard_attention", "standard_conv_1x1", "standard_conv_1x1", "identity"
])
hparams.add_hparam("encoder_left_output_dims", [512, 2048, 512, 512])
hparams.add_hparam("encoder_left_activations",
["none", "relu", "none", "none"])
hparams.add_hparam("encoder_left_norms",
["layer_norm", "layer_norm", "none", "none"])
hparams.add_hparam("encoder_right_inputs", [0, 1, 1, 1])
hparams.add_hparam("encoder_right_layers",
["identity", "dead_branch", "identity", "dead_branch"])
hparams.add_hparam("encoder_right_activations",
["none", "none", "none", "none"])
hparams.add_hparam("encoder_right_output_dims", [512, 512, 512, 512])
hparams.add_hparam("encoder_right_norms", ["none", "none", "none", "none"])
hparams.add_hparam("encoder_combiner_functions", ["add", "add", "add", "add"])
hparams.add_hparam("encoder_final_combiner_function", "add")
hparams.add_hparam("decoder_num_cells", 6)
hparams.add_hparam("decoder_left_inputs", [0, 1, 2, 3, 4])
hparams.add_hparam("decoder_left_layers", [
"standard_attention", "attend_to_encoder", "standard_conv_1x1",
"standard_conv_1x1", "identity"
])
hparams.add_hparam("decoder_left_activations",
["none", "none", "relu", "none", "none"])
hparams.add_hparam("decoder_left_output_dims", [512, 512, 2048, 512, 512])
hparams.add_hparam("decoder_left_norms",
["layer_norm", "layer_norm", "layer_norm", "none", "none"])
hparams.add_hparam("decoder_right_inputs", [0, 1, 2, 2, 4])
hparams.add_hparam(
"decoder_right_layers",
["identity", "identity", "dead_branch", "identity", "dead_branch"])
hparams.add_hparam("decoder_right_activations",
["none", "none", "none", "none", "none"])
hparams.add_hparam("decoder_right_output_dims", [512, 512, 512, 512, 512])
hparams.add_hparam("decoder_right_norms",
["none", "none", "none", "none", "none"])
hparams.add_hparam("decoder_combiner_functions",
["add", "add", "add", "add", "add"])
hparams.add_hparam("decoder_final_combiner_function", "add")
return hparams | [
"def",
"nas_seq2seq_base",
"(",
")",
":",
"hparams",
"=",
"transformer",
".",
"transformer_base",
"(",
")",
"hparams",
".",
"add_hparam",
"(",
"\"encoder_num_cells\"",
",",
"6",
")",
"hparams",
".",
"add_hparam",
"(",
"\"encoder_left_inputs\"",
",",
"[",
"0",
... | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/neural_architecture_search/nas_model.py#L1078-L1132 | |
Socialbird-AILab/BERT-Classification-Tutorial | 46f2ded8f985b65021a7f559967da9fc78a792ac | modeling.py | python | create_initializer | (initializer_range=0.02) | return tf.truncated_normal_initializer(stddev=initializer_range) | Creates a `truncated_normal_initializer` with the given range. | Creates a `truncated_normal_initializer` with the given range. | [
"Creates",
"a",
"truncated_normal_initializer",
"with",
"the",
"given",
"range",
"."
] | def create_initializer(initializer_range=0.02):
"""Creates a `truncated_normal_initializer` with the given range."""
return tf.truncated_normal_initializer(stddev=initializer_range) | [
"def",
"create_initializer",
"(",
"initializer_range",
"=",
"0.02",
")",
":",
"return",
"tf",
".",
"truncated_normal_initializer",
"(",
"stddev",
"=",
"initializer_range",
")"
] | https://github.com/Socialbird-AILab/BERT-Classification-Tutorial/blob/46f2ded8f985b65021a7f559967da9fc78a792ac/modeling.py#L376-L378 | |
aiven/pghoard | 1de0d2e33bf087b7ce3b6af556bbf941acfac3a4 | pghoard/common.py | python | set_subprocess_stdout_and_stderr_nonblocking | (proc) | [] | def set_subprocess_stdout_and_stderr_nonblocking(proc):
set_stream_nonblocking(proc.stdout)
set_stream_nonblocking(proc.stderr) | [
"def",
"set_subprocess_stdout_and_stderr_nonblocking",
"(",
"proc",
")",
":",
"set_stream_nonblocking",
"(",
"proc",
".",
"stdout",
")",
"set_stream_nonblocking",
"(",
"proc",
".",
"stderr",
")"
] | https://github.com/aiven/pghoard/blob/1de0d2e33bf087b7ce3b6af556bbf941acfac3a4/pghoard/common.py#L167-L169 | ||||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/functions/special/error_functions.py | python | erfc.as_real_imag | (self, deep=True, **hints) | return (re, im) | [] | def as_real_imag(self, deep=True, **hints):
if self.args[0].is_real:
if deep:
hints['complex'] = False
return (self.expand(deep, **hints), S.Zero)
else:
return (self, S.Zero)
if deep:
x, y = self.args[0].expand(deep, **hints).as_real_imag()
else:
x, y = self.args[0].as_real_imag()
sq = -y**2/x**2
re = S.Half*(self.func(x + x*sqrt(sq)) + self.func(x - x*sqrt(sq)))
im = x/(2*y) * sqrt(sq) * (self.func(x - x*sqrt(sq)) -
self.func(x + x*sqrt(sq)))
return (re, im) | [
"def",
"as_real_imag",
"(",
"self",
",",
"deep",
"=",
"True",
",",
"*",
"*",
"hints",
")",
":",
"if",
"self",
".",
"args",
"[",
"0",
"]",
".",
"is_real",
":",
"if",
"deep",
":",
"hints",
"[",
"'complex'",
"]",
"=",
"False",
"return",
"(",
"self",... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/special/error_functions.py#L380-L396 | |||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/xml/sax/expatreader.py | python | ExpatParser.getLineNumber | (self) | return self._parser.ErrorLineNumber | [] | def getLineNumber(self):
if self._parser is None:
return 1
return self._parser.ErrorLineNumber | [
"def",
"getLineNumber",
"(",
"self",
")",
":",
"if",
"self",
".",
"_parser",
"is",
"None",
":",
"return",
"1",
"return",
"self",
".",
"_parser",
".",
"ErrorLineNumber"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/xml/sax/expatreader.py#L291-L294 | |||
davidoren/CuckooSploit | 3fce8183bee8f7917e08f765ce2a01c921f86354 | lib/cuckoo/common/abstracts.py | python | LibVirtMachinery._status | (self, label) | Gets current status of a vm.
@param label: virtual machine name.
@return: status string. | Gets current status of a vm. | [
"Gets",
"current",
"status",
"of",
"a",
"vm",
"."
] | def _status(self, label):
"""Gets current status of a vm.
@param label: virtual machine name.
@return: status string.
"""
log.debug("Getting status for %s", label)
# Stetes mapping of python-libvirt.
# virDomainState
# VIR_DOMAIN_NOSTATE = 0
# VIR_DOMAIN_RUNNING = 1
# VIR_DOMAIN_BLOCKED = 2
# VIR_DOMAIN_PAUSED = 3
# VIR_DOMAIN_SHUTDOWN = 4
# VIR_DOMAIN_SHUTOFF = 5
# VIR_DOMAIN_CRASHED = 6
# VIR_DOMAIN_PMSUSPENDED = 7
conn = self._connect()
try:
state = self.vms[label].state(flags=0)
except libvirt.libvirtError as e:
raise CuckooMachineError("Error getting status for virtual "
"machine {0}: {1}".format(label, e))
finally:
self._disconnect(conn)
if state:
if state[0] == 1:
status = self.RUNNING
elif state[0] == 3:
status = self.PAUSED
elif state[0] == 4 or state[0] == 5:
status = self.POWEROFF
else:
status = self.ERROR
# Report back status.
if status:
self.set_status(label, status)
return status
else:
raise CuckooMachineError("Unable to get status for "
"{0}".format(label)) | [
"def",
"_status",
"(",
"self",
",",
"label",
")",
":",
"log",
".",
"debug",
"(",
"\"Getting status for %s\"",
",",
"label",
")",
"# Stetes mapping of python-libvirt.",
"# virDomainState",
"# VIR_DOMAIN_NOSTATE = 0",
"# VIR_DOMAIN_RUNNING = 1",
"# VIR_DOMAIN_BLOCKED = 2",
"#... | https://github.com/davidoren/CuckooSploit/blob/3fce8183bee8f7917e08f765ce2a01c921f86354/lib/cuckoo/common/abstracts.py#L439-L482 | ||
a1ext/auto_re | 5a4a21a869493297c3f34b7ae45e07efb9157329 | auto_re.py | python | auto_re_t.start_ea_of | (cls, o) | return getattr(o, 'start_ea' if idaapi.IDA_SDK_VERSION >= 700 else 'startEA') | [] | def start_ea_of(cls, o):
return getattr(o, 'start_ea' if idaapi.IDA_SDK_VERSION >= 700 else 'startEA') | [
"def",
"start_ea_of",
"(",
"cls",
",",
"o",
")",
":",
"return",
"getattr",
"(",
"o",
",",
"'start_ea'",
"if",
"idaapi",
".",
"IDA_SDK_VERSION",
">=",
"700",
"else",
"'startEA'",
")"
] | https://github.com/a1ext/auto_re/blob/5a4a21a869493297c3f34b7ae45e07efb9157329/auto_re.py#L636-L637 | |||
ChenJoya/sampling-free | 01dfd40cf794ee5afea4f052216483f3901ecd20 | sampling_free/structures/segmentation_mask.py | python | SegmentationMask.__init__ | (self, instances, size, mode="poly") | Arguments:
instances: two types
(1) polygon
(2) binary mask
size: (width, height)
mode: 'poly', 'mask'. if mode is 'mask', convert mask of any format to binary mask | Arguments:
instances: two types
(1) polygon
(2) binary mask
size: (width, height)
mode: 'poly', 'mask'. if mode is 'mask', convert mask of any format to binary mask | [
"Arguments",
":",
"instances",
":",
"two",
"types",
"(",
"1",
")",
"polygon",
"(",
"2",
")",
"binary",
"mask",
"size",
":",
"(",
"width",
"height",
")",
"mode",
":",
"poly",
"mask",
".",
"if",
"mode",
"is",
"mask",
"convert",
"mask",
"of",
"any",
"... | def __init__(self, instances, size, mode="poly"):
"""
Arguments:
instances: two types
(1) polygon
(2) binary mask
size: (width, height)
mode: 'poly', 'mask'. if mode is 'mask', convert mask of any format to binary mask
"""
assert isinstance(size, (list, tuple))
assert len(size) == 2
if isinstance(size[0], torch.Tensor):
assert isinstance(size[1], torch.Tensor)
size = size[0].item(), size[1].item()
assert isinstance(size[0], (int, float))
assert isinstance(size[1], (int, float))
if mode == "poly":
self.instances = PolygonList(instances, size)
elif mode == "mask":
self.instances = BinaryMaskList(instances, size)
else:
raise NotImplementedError("Unknown mode: %s" % str(mode))
self.mode = mode
self.size = tuple(size) | [
"def",
"__init__",
"(",
"self",
",",
"instances",
",",
"size",
",",
"mode",
"=",
"\"poly\"",
")",
":",
"assert",
"isinstance",
"(",
"size",
",",
"(",
"list",
",",
"tuple",
")",
")",
"assert",
"len",
"(",
"size",
")",
"==",
"2",
"if",
"isinstance",
... | https://github.com/ChenJoya/sampling-free/blob/01dfd40cf794ee5afea4f052216483f3901ecd20/sampling_free/structures/segmentation_mask.py#L442-L469 | ||
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/registry/models/bundle_version_metadata.py | python | BundleVersionMetadata.version | (self, version) | Sets the version of this BundleVersionMetadata.
The version of the extension bundle
:param version: The version of this BundleVersionMetadata.
:type: str | Sets the version of this BundleVersionMetadata.
The version of the extension bundle | [
"Sets",
"the",
"version",
"of",
"this",
"BundleVersionMetadata",
".",
"The",
"version",
"of",
"the",
"extension",
"bundle"
] | def version(self, version):
"""
Sets the version of this BundleVersionMetadata.
The version of the extension bundle
:param version: The version of this BundleVersionMetadata.
:type: str
"""
self._version = version | [
"def",
"version",
"(",
"self",
",",
"version",
")",
":",
"self",
".",
"_version",
"=",
"version"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/registry/models/bundle_version_metadata.py#L265-L274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.