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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jliljebl/flowblade | 995313a509b80e99eb1ad550d945bdda5995093b | flowblade-trunk/Flowblade/edit.py | python | _container_clip_full_render_replace_redo | (self) | [] | def _container_clip_full_render_replace_redo(self):
_remove_clip(self.track, self.index)
_insert_clip(self.track, self.new_clip, self.index, self.old_clip.clip_in, self.old_clip.clip_out)
if self.new_clip.container_data == None:
self.new_clip.container_data = copy.deepcopy(self.old_clip.container_data)
if not hasattr(self, "clone_filters") and self.do_filters_clone == True:
self.clone_filters = current_sequence().clone_filters(self.old_clip)
if self.do_filters_clone == True:
_detach_all(self.new_clip)
self.new_clip.filters = self.clone_filters
_attach_all(self.new_clip)
self.new_clip.container_data.rendered_media = self.rendered_media_path
self.new_clip.container_data.rendered_media_range_in = 0
self.new_clip.container_data.rendered_media_range_out = self.old_clip.container_data.unrendered_length | [
"def",
"_container_clip_full_render_replace_redo",
"(",
"self",
")",
":",
"_remove_clip",
"(",
"self",
".",
"track",
",",
"self",
".",
"index",
")",
"_insert_clip",
"(",
"self",
".",
"track",
",",
"self",
".",
"new_clip",
",",
"self",
".",
"index",
",",
"s... | https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/edit.py#L2907-L2924 | ||||
n1nj4sec/pupy | a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39 | pupy/packages/windows/all/pupwinutils/security.py | python | get_thread_token | () | return hToken | [] | def get_thread_token():
hThread = GetCurrentThread()
hToken = HANDLE(INVALID_HANDLE_VALUE)
dwError = None
if not OpenThreadToken(hThread, tokenprivs, False, byref(hToken)):
dwError = get_last_error()
CloseHandle(hThread)
if dwError:
if dwError == ERROR_NO_TOKEN:
return get_process_token()
raise WinError(dwError)
return hToken | [
"def",
"get_thread_token",
"(",
")",
":",
"hThread",
"=",
"GetCurrentThread",
"(",
")",
"hToken",
"=",
"HANDLE",
"(",
"INVALID_HANDLE_VALUE",
")",
"dwError",
"=",
"None",
"if",
"not",
"OpenThreadToken",
"(",
"hThread",
",",
"tokenprivs",
",",
"False",
",",
"... | https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/packages/windows/all/pupwinutils/security.py#L1561-L1576 | |||
DLR-RM/stable-baselines3 | e9a8979022d7005560d43b7a9c1dc1ba85f7989a | stable_baselines3/common/results_plotter.py | python | plot_results | (
dirs: List[str], num_timesteps: Optional[int], x_axis: str, task_name: str, figsize: Tuple[int, int] = (8, 2)
) | Plot the results using csv files from ``Monitor`` wrapper.
:param dirs: the save location of the results to plot
:param num_timesteps: only plot the points below this value
:param x_axis: the axis for the x and y output
(can be X_TIMESTEPS='timesteps', X_EPISODES='episodes' or X_WALLTIME='walltime_hrs')
:param task_name: the title of the task to plot
:param figsize: Size of the figure (width, height) | Plot the results using csv files from ``Monitor`` wrapper. | [
"Plot",
"the",
"results",
"using",
"csv",
"files",
"from",
"Monitor",
"wrapper",
"."
] | def plot_results(
dirs: List[str], num_timesteps: Optional[int], x_axis: str, task_name: str, figsize: Tuple[int, int] = (8, 2)
) -> None:
"""
Plot the results using csv files from ``Monitor`` wrapper.
:param dirs: the save location of the results to plot
:param num_timesteps: only plot the points below this value
:param x_axis: the axis for the x and y output
(can be X_TIMESTEPS='timesteps', X_EPISODES='episodes' or X_WALLTIME='walltime_hrs')
:param task_name: the title of the task to plot
:param figsize: Size of the figure (width, height)
"""
data_frames = []
for folder in dirs:
data_frame = load_results(folder)
if num_timesteps is not None:
data_frame = data_frame[data_frame.l.cumsum() <= num_timesteps]
data_frames.append(data_frame)
xy_list = [ts2xy(data_frame, x_axis) for data_frame in data_frames]
plot_curves(xy_list, x_axis, task_name, figsize) | [
"def",
"plot_results",
"(",
"dirs",
":",
"List",
"[",
"str",
"]",
",",
"num_timesteps",
":",
"Optional",
"[",
"int",
"]",
",",
"x_axis",
":",
"str",
",",
"task_name",
":",
"str",
",",
"figsize",
":",
"Tuple",
"[",
"int",
",",
"int",
"]",
"=",
"(",
... | https://github.com/DLR-RM/stable-baselines3/blob/e9a8979022d7005560d43b7a9c1dc1ba85f7989a/stable_baselines3/common/results_plotter.py#L101-L122 | ||
gaubert/gmvault | 61a3f633a352503a395b7f5a0d9cf5fc9e0ac9b4 | src/gmv/gmvault_utils.py | python | UTC.utcoffset | (self, a_dt) | return ZERO | return utcoffset | return utcoffset | [
"return",
"utcoffset"
] | def utcoffset(self, a_dt): #pylint: disable=W0613
''' return utcoffset '''
return ZERO | [
"def",
"utcoffset",
"(",
"self",
",",
"a_dt",
")",
":",
"#pylint: disable=W0613",
"return",
"ZERO"
] | https://github.com/gaubert/gmvault/blob/61a3f633a352503a395b7f5a0d9cf5fc9e0ac9b4/src/gmv/gmvault_utils.py#L232-L234 | |
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/pip/req/req_uninstall.py | python | UninstallPathSet.compact | (self, paths) | return short_paths | Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path. | Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path. | [
"Compact",
"a",
"path",
"set",
"to",
"contain",
"the",
"minimal",
"number",
"of",
"paths",
"necessary",
"to",
"contain",
"all",
"paths",
"in",
"the",
"set",
".",
"If",
"/",
"a",
"/",
"path",
"/",
"and",
"/",
"a",
"/",
"path",
"/",
"to",
"/",
"a",
... | def compact(self, paths):
"""Compact a path set to contain the minimal number of paths
necessary to contain all paths in the set. If /a/path/ and
/a/path/to/a/file.txt are both in the set, leave only the
shorter path."""
short_paths = set()
for path in sorted(paths, key=len):
if not any([
(path.startswith(shortpath) and
path[len(shortpath.rstrip(os.path.sep))] == os.path.sep)
for shortpath in short_paths]):
short_paths.add(path)
return short_paths | [
"def",
"compact",
"(",
"self",
",",
"paths",
")",
":",
"short_paths",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"sorted",
"(",
"paths",
",",
"key",
"=",
"len",
")",
":",
"if",
"not",
"any",
"(",
"[",
"(",
"path",
".",
"startswith",
"(",
"shortpa... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/req/req_uninstall.py#L63-L75 | |
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | thirdparty_libs/nltk/grammar.py | python | FeatureGrammar._get_type_if_possible | (self, item) | Helper function which returns the ``TYPE`` feature of the ``item``,
if it exists, otherwise it returns the ``item`` itself | Helper function which returns the ``TYPE`` feature of the ``item``,
if it exists, otherwise it returns the ``item`` itself | [
"Helper",
"function",
"which",
"returns",
"the",
"TYPE",
"feature",
"of",
"the",
"item",
"if",
"it",
"exists",
"otherwise",
"it",
"returns",
"the",
"item",
"itself"
] | def _get_type_if_possible(self, item):
"""
Helper function which returns the ``TYPE`` feature of the ``item``,
if it exists, otherwise it returns the ``item`` itself
"""
if isinstance(item, dict) and TYPE in item:
return FeatureValueType(item[TYPE])
else:
return item | [
"def",
"_get_type_if_possible",
"(",
"self",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
"and",
"TYPE",
"in",
"item",
":",
"return",
"FeatureValueType",
"(",
"item",
"[",
"TYPE",
"]",
")",
"else",
":",
"return",
"item"
] | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/nltk/grammar.py#L808-L816 | ||
guildai/guildai | 1665985a3d4d788efc1a3180ca51cc417f71ca78 | guild/external/pip/_vendor/urllib3/contrib/pyopenssl.py | python | get_subj_alt_name | (peer_cert) | return names | Given an PyOpenSSL certificate, provides all the subject alternative names. | Given an PyOpenSSL certificate, provides all the subject alternative names. | [
"Given",
"an",
"PyOpenSSL",
"certificate",
"provides",
"all",
"the",
"subject",
"alternative",
"names",
"."
] | def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
if hasattr(peer_cert, "to_cryptography"):
cert = peer_cert.to_cryptography()
else:
# This is technically using private APIs, but should work across all
# relevant versions before PyOpenSSL got a proper API for this.
cert = _Certificate(openssl_backend, peer_cert._x509)
# We want to find the SAN extension. Ask Cryptography to locate it (it's
# faster than looping in Python)
try:
ext = cert.extensions.get_extension_for_class(
x509.SubjectAlternativeName
).value
except x509.ExtensionNotFound:
# No such extension, return the empty list.
return []
except (x509.DuplicateExtension, UnsupportedExtension,
x509.UnsupportedGeneralNameType, UnicodeError) as e:
# A problem has been found with the quality of the certificate. Assume
# no SAN field is present.
log.warning(
"A problem was encountered with the certificate that prevented "
"urllib3 from finding the SubjectAlternativeName field. This can "
"affect certificate validation. The error was %s",
e,
)
return []
# We want to return dNSName and iPAddress fields. We need to cast the IPs
# back to strings because the match_hostname function wants them as
# strings.
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
# decoded. This is pretty frustrating, but that's what the standard library
# does with certificates, and so we need to attempt to do the same.
names = [
('DNS', _dnsname_to_stdlib(name))
for name in ext.get_values_for_type(x509.DNSName)
]
names.extend(
('IP Address', str(name))
for name in ext.get_values_for_type(x509.IPAddress)
)
return names | [
"def",
"get_subj_alt_name",
"(",
"peer_cert",
")",
":",
"# Pass the cert to cryptography, which has much better APIs for this.",
"if",
"hasattr",
"(",
"peer_cert",
",",
"\"to_cryptography\"",
")",
":",
"cert",
"=",
"peer_cert",
".",
"to_cryptography",
"(",
")",
"else",
... | https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/urllib3/contrib/pyopenssl.py#L187-L235 | |
PyHDI/Pyverilog | 2a42539bebd1b4587ee577d491ff002d0cc7295d | pyverilog/vparser/parser.py | python | VerilogParser.p_paramlist_empty | (self, p) | paramlist : empty | paramlist : empty | [
"paramlist",
":",
"empty"
] | def p_paramlist_empty(self, p):
'paramlist : empty'
p[0] = Paramlist(params=()) | [
"def",
"p_paramlist_empty",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Paramlist",
"(",
"params",
"=",
"(",
")",
")"
] | https://github.com/PyHDI/Pyverilog/blob/2a42539bebd1b4587ee577d491ff002d0cc7295d/pyverilog/vparser/parser.py#L148-L150 | ||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/captcha/v20190722/models.py | python | TicketThroughUnit.__init__ | (self) | r"""
:param DateKey: 时间
:type DateKey: str
:param Through: 票据验证的通过量
:type Through: int | r"""
:param DateKey: 时间
:type DateKey: str
:param Through: 票据验证的通过量
:type Through: int | [
"r",
":",
"param",
"DateKey",
":",
"时间",
":",
"type",
"DateKey",
":",
"str",
":",
"param",
"Through",
":",
"票据验证的通过量",
":",
"type",
"Through",
":",
"int"
] | def __init__(self):
r"""
:param DateKey: 时间
:type DateKey: str
:param Through: 票据验证的通过量
:type Through: int
"""
self.DateKey = None
self.Through = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"DateKey",
"=",
"None",
"self",
".",
"Through",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/captcha/v20190722/models.py#L1435-L1443 | ||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/configparser.py | python | RawConfigParser.get | (self, section, option, *, raw=False, vars=None, fallback=_UNSET) | Get an option value for a given section.
If `vars' is provided, it must be a dictionary. The option is looked up
in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
If the key is not found and `fallback' is provided, it is used as
a fallback value. `None' can be provided as a `fallback' value.
If interpolation is enabled and the optional argument `raw' is False,
all interpolations are expanded in the return values.
Arguments `raw', `vars', and `fallback' are keyword only.
The section DEFAULT is special. | Get an option value for a given section. | [
"Get",
"an",
"option",
"value",
"for",
"a",
"given",
"section",
"."
] | def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
"""Get an option value for a given section.
If `vars' is provided, it must be a dictionary. The option is looked up
in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
If the key is not found and `fallback' is provided, it is used as
a fallback value. `None' can be provided as a `fallback' value.
If interpolation is enabled and the optional argument `raw' is False,
all interpolations are expanded in the return values.
Arguments `raw', `vars', and `fallback' are keyword only.
The section DEFAULT is special.
"""
try:
d = self._unify_values(section, vars)
except NoSectionError:
if fallback is _UNSET:
raise
else:
return fallback
option = self.optionxform(option)
try:
value = d[option]
except KeyError:
if fallback is _UNSET:
raise NoOptionError(option, section)
else:
return fallback
if raw or value is None:
return value
else:
return self._interpolation.before_get(self, section, option, value,
d) | [
"def",
"get",
"(",
"self",
",",
"section",
",",
"option",
",",
"*",
",",
"raw",
"=",
"False",
",",
"vars",
"=",
"None",
",",
"fallback",
"=",
"_UNSET",
")",
":",
"try",
":",
"d",
"=",
"self",
".",
"_unify_values",
"(",
"section",
",",
"vars",
")"... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/configparser.py#L766-L801 | ||
python-discord/site | 899c304730598812a41be68a037c723d815e95e1 | pydis_site/apps/api/viewsets/bot/user.py | python | UserListPagination.get_previous_page_number | (self) | return page_number | Get the previous page number. | Get the previous page number. | [
"Get",
"the",
"previous",
"page",
"number",
"."
] | def get_previous_page_number(self) -> typing.Optional[int]:
"""Get the previous page number."""
if not self.page.has_previous():
return None
page_number = self.page.previous_page_number()
return page_number | [
"def",
"get_previous_page_number",
"(",
"self",
")",
"->",
"typing",
".",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
".",
"page",
".",
"has_previous",
"(",
")",
":",
"return",
"None",
"page_number",
"=",
"self",
".",
"page",
".",
"previous_pa... | https://github.com/python-discord/site/blob/899c304730598812a41be68a037c723d815e95e1/pydis_site/apps/api/viewsets/bot/user.py#L32-L38 | |
researchmm/tasn | 5dba8ccc096cedc63913730eeea14a9647911129 | tasn-mxnet/3rdparty/tvm/python/tvm/relay/op/tensor.py | python | less | (lhs, rhs) | return _make.less(lhs, rhs) | Broadcasted elementwise test for (lhs < rhs).
Parameters
----------
lhs : relay.Expr
The left hand side input data
rhs : relay.Expr
The right hand side input data
Returns
-------
result : relay.Expr
The computed result. | Broadcasted elementwise test for (lhs < rhs). | [
"Broadcasted",
"elementwise",
"test",
"for",
"(",
"lhs",
"<",
"rhs",
")",
"."
] | def less(lhs, rhs):
"""Broadcasted elementwise test for (lhs < rhs).
Parameters
----------
lhs : relay.Expr
The left hand side input data
rhs : relay.Expr
The right hand side input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.less(lhs, rhs) | [
"def",
"less",
"(",
"lhs",
",",
"rhs",
")",
":",
"return",
"_make",
".",
"less",
"(",
"lhs",
",",
"rhs",
")"
] | https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/3rdparty/tvm/python/tvm/relay/op/tensor.py#L343-L358 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/decimal.py | python | Context.copy_abs | (self, a) | return a.copy_abs() | Returns a copy of the operand with the sign set to 0.
>>> ExtendedContext.copy_abs(Decimal('2.1'))
Decimal('2.1')
>>> ExtendedContext.copy_abs(Decimal('-100'))
Decimal('100')
>>> ExtendedContext.copy_abs(-1)
Decimal('1') | Returns a copy of the operand with the sign set to 0. | [
"Returns",
"a",
"copy",
"of",
"the",
"operand",
"with",
"the",
"sign",
"set",
"to",
"0",
"."
] | def copy_abs(self, a):
"""Returns a copy of the operand with the sign set to 0.
>>> ExtendedContext.copy_abs(Decimal('2.1'))
Decimal('2.1')
>>> ExtendedContext.copy_abs(Decimal('-100'))
Decimal('100')
>>> ExtendedContext.copy_abs(-1)
Decimal('1')
"""
a = _convert_other(a, raiseit=True)
return a.copy_abs() | [
"def",
"copy_abs",
"(",
"self",
",",
"a",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"copy_abs",
"(",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/decimal.py#L4175-L4186 | |
datawire/forge | d501be4571dcef5691804c7db7008ee877933c8d | forge/schema.py | python | Sequence.name | (self) | return "sequence[%s]" % self.type.name | [] | def name(self):
return "sequence[%s]" % self.type.name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"\"sequence[%s]\"",
"%",
"self",
".",
"type",
".",
"name"
] | https://github.com/datawire/forge/blob/d501be4571dcef5691804c7db7008ee877933c8d/forge/schema.py#L397-L398 | |||
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/configobj.py | python | ConfigObj._decode | (self, infile, encoding) | return infile | Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list. | Decode infile to unicode. Using the specified encoding. | [
"Decode",
"infile",
"to",
"unicode",
".",
"Using",
"the",
"specified",
"encoding",
"."
] | def _decode(self, infile, encoding):
"""
Decode infile to unicode. Using the specified encoding.
if is a string, it also needs converting to a list.
"""
if isinstance(infile, basestring):
# can't be unicode
# NOTE: Could raise a ``UnicodeDecodeError``
return infile.decode(encoding).splitlines(True)
for i, line in enumerate(infile):
if not isinstance(line, unicode):
# NOTE: The isinstance test here handles mixed lists of unicode/string
# NOTE: But the decode will break on any non-string values
# NOTE: Or could raise a ``UnicodeDecodeError``
infile[i] = line.decode(encoding)
return infile | [
"def",
"_decode",
"(",
"self",
",",
"infile",
",",
"encoding",
")",
":",
"if",
"isinstance",
"(",
"infile",
",",
"basestring",
")",
":",
"# can't be unicode",
"# NOTE: Could raise a ``UnicodeDecodeError``",
"return",
"infile",
".",
"decode",
"(",
"encoding",
")",
... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/configobj.py#L1494-L1510 | |
inconvergent/svgsort | de54f1973d87009c37ff9755ebd5ee880f08e3f4 | svgsort/svgpathtools/path.py | python | Path.cropped | (self, T0, T1) | return new_path | returns a cropped copy of the path. | returns a cropped copy of the path. | [
"returns",
"a",
"cropped",
"copy",
"of",
"the",
"path",
"."
] | def cropped(self, T0, T1):
"""returns a cropped copy of the path."""
assert 0 <= T0 <= 1 and 0 <= T1<= 1
assert T0 != T1
assert not (T0 == 1 and T1 == 0)
if T0 == 1 and 0 < T1 < 1 and self.isclosed():
return self.cropped(0, T1)
if T1 == 1:
seg1 = self[-1]
t_seg1 = 1
i1 = len(self) - 1
else:
seg1_idx, t_seg1 = self.T2t(T1)
seg1 = self[seg1_idx]
if np.isclose(t_seg1, 0):
i1 = (self.index(seg1) - 1) % len(self)
seg1 = self[i1]
t_seg1 = 1
else:
i1 = self.index(seg1)
if T0 == 0:
seg0 = self[0]
t_seg0 = 0
i0 = 0
else:
seg0_idx, t_seg0 = self.T2t(T0)
seg0 = self[seg0_idx]
if np.isclose(t_seg0, 1):
i0 = (self.index(seg0) + 1) % len(self)
seg0 = self[i0]
t_seg0 = 0
else:
i0 = self.index(seg0)
if T0 < T1 and i0 == i1:
new_path = Path(seg0.cropped(t_seg0, t_seg1))
else:
new_path = Path(seg0.cropped(t_seg0, 1))
# T1<T0 must cross discontinuity case
if T1 < T0:
if not self.isclosed():
raise ValueError("This path is not closed, thus T0 must "
"be less than T1.")
else:
for i in range(i0 + 1, len(self)):
new_path.append(self[i])
for i in range(0, i1):
new_path.append(self[i])
# T0<T1 straight-forward case
else:
for i in range(i0 + 1, i1):
new_path.append(self[i])
if t_seg1 != 0:
new_path.append(seg1.cropped(0, t_seg1))
return new_path | [
"def",
"cropped",
"(",
"self",
",",
"T0",
",",
"T1",
")",
":",
"assert",
"0",
"<=",
"T0",
"<=",
"1",
"and",
"0",
"<=",
"T1",
"<=",
"1",
"assert",
"T0",
"!=",
"T1",
"assert",
"not",
"(",
"T0",
"==",
"1",
"and",
"T1",
"==",
"0",
")",
"if",
"T... | https://github.com/inconvergent/svgsort/blob/de54f1973d87009c37ff9755ebd5ee880f08e3f4/svgsort/svgpathtools/path.py#L2547-L2606 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.40/roles/openshift_health_checker/library/ocutil.py | python | main | () | Module that executes commands on a remote OpenShift cluster | Module that executes commands on a remote OpenShift cluster | [
"Module",
"that",
"executes",
"commands",
"on",
"a",
"remote",
"OpenShift",
"cluster"
] | def main():
"""Module that executes commands on a remote OpenShift cluster"""
module = AnsibleModule(
argument_spec=dict(
namespace=dict(type="str", required=False),
config_file=dict(type="str", required=True),
cmd=dict(type="str", required=True),
extra_args=dict(type="list", default=[]),
),
)
cmd = [locate_oc_binary(), '--config', module.params["config_file"]]
if module.params["namespace"]:
cmd += ['-n', module.params["namespace"]]
cmd += shlex.split(module.params["cmd"]) + module.params["extra_args"]
failed = True
try:
cmd_result = subprocess.check_output(list(cmd), stderr=subprocess.STDOUT)
failed = False
except subprocess.CalledProcessError as exc:
cmd_result = '[rc {}] {}\n{}'.format(exc.returncode, ' '.join(exc.cmd), exc.output)
except OSError as exc:
# we get this when 'oc' is not there
cmd_result = str(exc)
module.exit_json(
changed=False,
failed=failed,
result=cmd_result,
) | [
"def",
"main",
"(",
")",
":",
"module",
"=",
"AnsibleModule",
"(",
"argument_spec",
"=",
"dict",
"(",
"namespace",
"=",
"dict",
"(",
"type",
"=",
"\"str\"",
",",
"required",
"=",
"False",
")",
",",
"config_file",
"=",
"dict",
"(",
"type",
"=",
"\"str\"... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/openshift_health_checker/library/ocutil.py#L38-L69 | ||
astropy/astroquery | 11c9c83fa8e5f948822f8f73c854ec4b72043016 | astroquery/utils/mocks.py | python | MockResponse.__init__ | (self, content=None, url=None, headers={}, content_type=None,
stream=False, auth=None, status_code=200, verify=True,
allow_redirects=True, json=None) | [] | def __init__(self, content=None, url=None, headers={}, content_type=None,
stream=False, auth=None, status_code=200, verify=True,
allow_redirects=True, json=None):
assert content is None or hasattr(content, 'decode')
self.content = content
self.raw = content
self.headers = headers
if content_type is not None:
self.headers.update({'Content-Type': content_type})
self.url = url
self.auth = auth
self.status_code = status_code | [
"def",
"__init__",
"(",
"self",
",",
"content",
"=",
"None",
",",
"url",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
",",
"content_type",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"auth",
"=",
"None",
",",
"status_code",
"=",
"200",
",",
"veri... | https://github.com/astropy/astroquery/blob/11c9c83fa8e5f948822f8f73c854ec4b72043016/astroquery/utils/mocks.py#L15-L26 | ||||
google/clusterfuzz | f358af24f414daa17a3649b143e71ea71871ef59 | src/clusterfuzz/_internal/bot/untrusted_runner/tasks_host.py | python | process_testcase | (engine_name, tool_name, target_name, arguments,
testcase_path, output_path, timeout) | return engine.ReproduceResult(
list(response.command), response.return_code, response.time_executed,
response.output) | Process testcase on untrusted worker. | Process testcase on untrusted worker. | [
"Process",
"testcase",
"on",
"untrusted",
"worker",
"."
] | def process_testcase(engine_name, tool_name, target_name, arguments,
testcase_path, output_path, timeout):
"""Process testcase on untrusted worker."""
if tool_name == 'minimize':
operation = untrusted_runner_pb2.ProcessTestcaseRequest.MINIMIZE
else:
operation = untrusted_runner_pb2.ProcessTestcaseRequest.CLEANSE
rebased_testcase_path = file_host.rebase_to_worker_root(testcase_path)
file_host.copy_file_to_worker(testcase_path, rebased_testcase_path)
request = untrusted_runner_pb2.ProcessTestcaseRequest(
engine=engine_name,
operation=operation,
target_name=target_name,
arguments=arguments,
testcase_path=file_host.rebase_to_worker_root(testcase_path),
output_path=file_host.rebase_to_worker_root(output_path),
timeout=timeout)
response = host.stub().ProcessTestcase(request)
rebased_output_path = file_host.rebase_to_worker_root(output_path)
file_host.copy_file_from_worker(rebased_output_path, output_path)
return engine.ReproduceResult(
list(response.command), response.return_code, response.time_executed,
response.output) | [
"def",
"process_testcase",
"(",
"engine_name",
",",
"tool_name",
",",
"target_name",
",",
"arguments",
",",
"testcase_path",
",",
"output_path",
",",
"timeout",
")",
":",
"if",
"tool_name",
"==",
"'minimize'",
":",
"operation",
"=",
"untrusted_runner_pb2",
".",
... | https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/bot/untrusted_runner/tasks_host.py#L109-L136 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/sloane_functions.py | python | A000120._repr_ | (self) | return "1's-counting sequence: number of 1's in binary expansion of n." | EXAMPLES::
sage: sloane.A000120._repr_()
"1's-counting sequence: number of 1's in binary expansion of n." | EXAMPLES:: | [
"EXAMPLES",
"::"
] | def _repr_(self):
"""
EXAMPLES::
sage: sloane.A000120._repr_()
"1's-counting sequence: number of 1's in binary expansion of n."
"""
return "1's-counting sequence: number of 1's in binary expansion of n." | [
"def",
"_repr_",
"(",
"self",
")",
":",
"return",
"\"1's-counting sequence: number of 1's in binary expansion of n.\""
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/sloane_functions.py#L1972-L1979 | |
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | cpython/Lib/lib-tk/turtle.py | python | TurtleScreen.listen | (self, xdummy=None, ydummy=None) | Set focus on TurtleScreen (in order to collect key-events)
No arguments.
Dummy arguments are provided in order
to be able to pass listen to the onclick method.
Example (for a TurtleScreen instance named screen):
>>> screen.listen() | Set focus on TurtleScreen (in order to collect key-events) | [
"Set",
"focus",
"on",
"TurtleScreen",
"(",
"in",
"order",
"to",
"collect",
"key",
"-",
"events",
")"
] | def listen(self, xdummy=None, ydummy=None):
"""Set focus on TurtleScreen (in order to collect key-events)
No arguments.
Dummy arguments are provided in order
to be able to pass listen to the onclick method.
Example (for a TurtleScreen instance named screen):
>>> screen.listen()
"""
self._listen() | [
"def",
"listen",
"(",
"self",
",",
"xdummy",
"=",
"None",
",",
"ydummy",
"=",
"None",
")",
":",
"self",
".",
"_listen",
"(",
")"
] | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/lib-tk/turtle.py#L1349-L1359 | ||
leancloud/satori | 701caccbd4fe45765001ca60435c0cb499477c03 | satori-rules/plugin/libs/urllib3/connectionpool.py | python | HTTPConnectionPool._prepare_proxy | (self, conn) | [] | def _prepare_proxy(self, conn):
# Nothing to do for HTTP connections.
pass | [
"def",
"_prepare_proxy",
"(",
"self",
",",
"conn",
")",
":",
"# Nothing to do for HTTP connections.",
"pass"
] | https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/urllib3/connectionpool.py#L287-L289 | ||||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | pypy/module/cpyext/stubs.py | python | PyUnicode_RichCompare | (space, left, right, op) | Rich compare two unicode strings and return one of the following:
NULL in case an exception was raised
Py_True or Py_False for successful comparisons
Py_NotImplemented in case the type combination is unknown
Note that Py_EQ and Py_NE comparisons can cause a
UnicodeWarning in case the conversion of the arguments to Unicode fails
with a UnicodeDecodeError.
Possible values for op are Py_GT, Py_GE, Py_EQ,
Py_NE, Py_LT, and Py_LE. | Rich compare two unicode strings and return one of the following: | [
"Rich",
"compare",
"two",
"unicode",
"strings",
"and",
"return",
"one",
"of",
"the",
"following",
":"
] | def PyUnicode_RichCompare(space, left, right, op):
"""Rich compare two unicode strings and return one of the following:
NULL in case an exception was raised
Py_True or Py_False for successful comparisons
Py_NotImplemented in case the type combination is unknown
Note that Py_EQ and Py_NE comparisons can cause a
UnicodeWarning in case the conversion of the arguments to Unicode fails
with a UnicodeDecodeError.
Possible values for op are Py_GT, Py_GE, Py_EQ,
Py_NE, Py_LT, and Py_LE."""
raise NotImplementedError | [
"def",
"PyUnicode_RichCompare",
"(",
"space",
",",
"left",
",",
"right",
",",
"op",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/module/cpyext/stubs.py#L1736-L1751 | ||
SforAiDl/Neural-Voice-Cloning-With-Few-Samples | 33fb609427657c9492f46507184ecba4dcc272b0 | speaker_adaptatation-libri.py | python | masked_mean | (y, mask) | return (y * mask_).sum() / mask_.sum() | [] | def masked_mean(y, mask):
# (B, T, D)
mask_ = mask.expand_as(y)
return (y * mask_).sum() / mask_.sum() | [
"def",
"masked_mean",
"(",
"y",
",",
"mask",
")",
":",
"# (B, T, D)",
"mask_",
"=",
"mask",
".",
"expand_as",
"(",
"y",
")",
"return",
"(",
"y",
"*",
"mask_",
")",
".",
"sum",
"(",
")",
"/",
"mask_",
".",
"sum",
"(",
")"
] | https://github.com/SforAiDl/Neural-Voice-Cloning-With-Few-Samples/blob/33fb609427657c9492f46507184ecba4dcc272b0/speaker_adaptatation-libri.py#L532-L535 | |||
svip-lab/impersonator | b041dd415157c1e7f5b46e579a1ad4dffabb2e66 | thirdparty/his_evaluators/his_evaluators/metrics/bodynets/batch_smpl.py | python | SMPL.skinning | (self, theta, offsets=0) | return detail_info | Args:
theta: (N, 3 + 72 + 10)
offsets (torch.tensor) : (N, nv, 3) or 0
Returns: | Args:
theta: (N, 3 + 72 + 10)
offsets (torch.tensor) : (N, nv, 3) or 0
Returns: | [
"Args",
":",
"theta",
":",
"(",
"N",
"3",
"+",
"72",
"+",
"10",
")",
"offsets",
"(",
"torch",
".",
"tensor",
")",
":",
"(",
"N",
"nv",
"3",
")",
"or",
"0",
"Returns",
":"
] | def skinning(self, theta, offsets=0) -> dict:
"""
Args:
theta: (N, 3 + 72 + 10)
offsets (torch.tensor) : (N, nv, 3) or 0
Returns:
"""
cam = theta[:, 0:3]
pose = theta[:, 3:-10].contiguous()
shape = theta[:, -10:].contiguous()
verts, j3d, rs = self.forward(beta=shape, theta=pose, offsets=offsets, get_skin=True)
detail_info = {
'cam': cam,
'pose': pose,
'shape': shape,
'verts': verts,
'theta': theta
}
return detail_info | [
"def",
"skinning",
"(",
"self",
",",
"theta",
",",
"offsets",
"=",
"0",
")",
"->",
"dict",
":",
"cam",
"=",
"theta",
"[",
":",
",",
"0",
":",
"3",
"]",
"pose",
"=",
"theta",
"[",
":",
",",
"3",
":",
"-",
"10",
"]",
".",
"contiguous",
"(",
"... | https://github.com/svip-lab/impersonator/blob/b041dd415157c1e7f5b46e579a1ad4dffabb2e66/thirdparty/his_evaluators/his_evaluators/metrics/bodynets/batch_smpl.py#L424-L446 | |
googleapis/python-dialogflow | e48ea001b7c8a4a5c1fe4b162bad49ea397458e9 | google/cloud/dialogflow_v2/services/intents/async_client.py | python | IntentsAsyncClient.batch_update_intents | (
self,
request: Union[intent.BatchUpdateIntentsRequest, dict] = None,
*,
parent: str = None,
intent_batch_uri: str = None,
intent_batch_inline: intent.IntentBatch = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | return response | r"""Updates/Creates multiple intents in the specified agent.
This method is a `long-running
operation <https://cloud.google.com/dialogflow/es/docs/how/long-running-operations>`__.
The returned ``Operation`` type has the following
method-specific fields:
- ``metadata``: An empty `Struct
message <https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct>`__
- ``response``:
[BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse]
Note: You should always train an agent prior to sending it
queries. See the `training
documentation <https://cloud.google.com/dialogflow/es/docs/training>`__.
Args:
request (Union[google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest, dict]):
The request object.
parent (:class:`str`):
Required. The name of the agent to update or create
intents in. Format: ``projects/<Project ID>/agent``.
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
intent_batch_uri (:class:`str`):
The URI to a Google Cloud Storage
file containing intents to update or
create. The file format can either be a
serialized proto (of IntentBatch type)
or JSON object. Note: The URI must start
with "gs://".
This corresponds to the ``intent_batch_uri`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
intent_batch_inline (:class:`google.cloud.dialogflow_v2.types.IntentBatch`):
The collection of intents to update
or create.
This corresponds to the ``intent_batch_inline`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
The result type for the operation will be
:class:`google.cloud.dialogflow_v2.types.BatchUpdateIntentsResponse`
The response message for
[Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents]. | r"""Updates/Creates multiple intents in the specified agent. | [
"r",
"Updates",
"/",
"Creates",
"multiple",
"intents",
"in",
"the",
"specified",
"agent",
"."
] | async def batch_update_intents(
self,
request: Union[intent.BatchUpdateIntentsRequest, dict] = None,
*,
parent: str = None,
intent_batch_uri: str = None,
intent_batch_inline: intent.IntentBatch = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operation_async.AsyncOperation:
r"""Updates/Creates multiple intents in the specified agent.
This method is a `long-running
operation <https://cloud.google.com/dialogflow/es/docs/how/long-running-operations>`__.
The returned ``Operation`` type has the following
method-specific fields:
- ``metadata``: An empty `Struct
message <https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct>`__
- ``response``:
[BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse]
Note: You should always train an agent prior to sending it
queries. See the `training
documentation <https://cloud.google.com/dialogflow/es/docs/training>`__.
Args:
request (Union[google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest, dict]):
The request object.
parent (:class:`str`):
Required. The name of the agent to update or create
intents in. Format: ``projects/<Project ID>/agent``.
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
intent_batch_uri (:class:`str`):
The URI to a Google Cloud Storage
file containing intents to update or
create. The file format can either be a
serialized proto (of IntentBatch type)
or JSON object. Note: The URI must start
with "gs://".
This corresponds to the ``intent_batch_uri`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
intent_batch_inline (:class:`google.cloud.dialogflow_v2.types.IntentBatch`):
The collection of intents to update
or create.
This corresponds to the ``intent_batch_inline`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.api_core.operation_async.AsyncOperation:
An object representing a long-running operation.
The result type for the operation will be
:class:`google.cloud.dialogflow_v2.types.BatchUpdateIntentsResponse`
The response message for
[Intents.BatchUpdateIntents][google.cloud.dialogflow.v2.Intents.BatchUpdateIntents].
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent, intent_batch_uri, intent_batch_inline])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
request = intent.BatchUpdateIntentsRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if parent is not None:
request.parent = parent
if intent_batch_uri is not None:
request.intent_batch_uri = intent_batch_uri
if intent_batch_inline is not None:
request.intent_batch_inline = intent_batch_inline
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.batch_update_intents,
default_timeout=None,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
)
# Send the request.
response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Wrap the response in an operation future.
response = operation_async.from_gapic(
response,
self._client._transport.operations_client,
intent.BatchUpdateIntentsResponse,
metadata_type=struct_pb2.Struct,
)
# Done; return the response.
return response | [
"async",
"def",
"batch_update_intents",
"(",
"self",
",",
"request",
":",
"Union",
"[",
"intent",
".",
"BatchUpdateIntentsRequest",
",",
"dict",
"]",
"=",
"None",
",",
"*",
",",
"parent",
":",
"str",
"=",
"None",
",",
"intent_batch_uri",
":",
"str",
"=",
... | https://github.com/googleapis/python-dialogflow/blob/e48ea001b7c8a4a5c1fe4b162bad49ea397458e9/google/cloud/dialogflow_v2/services/intents/async_client.py#L649-L767 | |
googleanalytics/google-analytics-super-proxy | f5bad82eb1375d222638423e6ae302173a9a7948 | src/controllers/util/request_timestamp_shard.py | python | IncreaseShards | (name, num_shards) | Increase the number of shards for a given sharded counter.
Will never decrease the number of shards.
Args:
name: The name of the counter.
num_shards: How many shards to use. | Increase the number of shards for a given sharded counter. | [
"Increase",
"the",
"number",
"of",
"shards",
"for",
"a",
"given",
"sharded",
"counter",
"."
] | def IncreaseShards(name, num_shards):
"""Increase the number of shards for a given sharded counter.
Will never decrease the number of shards.
Args:
name: The name of the counter.
num_shards: How many shards to use.
"""
config = GeneralTimestampShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put() | [
"def",
"IncreaseShards",
"(",
"name",
",",
"num_shards",
")",
":",
"config",
"=",
"GeneralTimestampShardConfig",
".",
"get_or_insert",
"(",
"name",
")",
"if",
"config",
".",
"num_shards",
"<",
"num_shards",
":",
"config",
".",
"num_shards",
"=",
"num_shards",
... | https://github.com/googleanalytics/google-analytics-super-proxy/blob/f5bad82eb1375d222638423e6ae302173a9a7948/src/controllers/util/request_timestamp_shard.py#L118-L130 | ||
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/Centos_6.4/rsa/_version133.py | python | decrypt_int | (cyphertext, dkey, n) | return encrypt_int(cyphertext, dkey, n) | Decrypts a cypher text using the decryption key 'dkey', working
modulo n | Decrypts a cypher text using the decryption key 'dkey', working
modulo n | [
"Decrypts",
"a",
"cypher",
"text",
"using",
"the",
"decryption",
"key",
"dkey",
"working",
"modulo",
"n"
] | def decrypt_int(cyphertext, dkey, n):
"""Decrypts a cypher text using the decryption key 'dkey', working
modulo n"""
return encrypt_int(cyphertext, dkey, n) | [
"def",
"decrypt_int",
"(",
"cyphertext",
",",
"dkey",
",",
"n",
")",
":",
"return",
"encrypt_int",
"(",
"cyphertext",
",",
"dkey",
",",
"n",
")"
] | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_6.4/rsa/_version133.py#L345-L349 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/sets/family.py | python | TrivialFamily.__setstate__ | (self, state) | TESTS::
sage: from sage.sets.family import TrivialFamily
sage: f = TrivialFamily([3,4,7])
sage: f.__setstate__({'_enumeration': (2, 4, 8)})
sage: f
Family (2, 4, 8) | TESTS:: | [
"TESTS",
"::"
] | def __setstate__(self, state):
"""
TESTS::
sage: from sage.sets.family import TrivialFamily
sage: f = TrivialFamily([3,4,7])
sage: f.__setstate__({'_enumeration': (2, 4, 8)})
sage: f
Family (2, 4, 8)
"""
self.__init__(state['_enumeration']) | [
"def",
"__setstate__",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"__init__",
"(",
"state",
"[",
"'_enumeration'",
"]",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/sets/family.py#L1329-L1339 | ||
deepgully/me | f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0 | libs/werkzeug/contrib/profiler.py | python | make_action | (app_factory, hostname='localhost', port=5000,
threaded=False, processes=1, stream=None,
sort_by=('time', 'calls'), restrictions=()) | return action | Return a new callback for :mod:`werkzeug.script` that starts a local
server with the profiler enabled.
::
from werkzeug.contrib import profiler
action_profile = profiler.make_action(make_app) | Return a new callback for :mod:`werkzeug.script` that starts a local
server with the profiler enabled. | [
"Return",
"a",
"new",
"callback",
"for",
":",
"mod",
":",
"werkzeug",
".",
"script",
"that",
"starts",
"a",
"local",
"server",
"with",
"the",
"profiler",
"enabled",
"."
] | def make_action(app_factory, hostname='localhost', port=5000,
threaded=False, processes=1, stream=None,
sort_by=('time', 'calls'), restrictions=()):
"""Return a new callback for :mod:`werkzeug.script` that starts a local
server with the profiler enabled.
::
from werkzeug.contrib import profiler
action_profile = profiler.make_action(make_app)
"""
def action(hostname=('h', hostname), port=('p', port),
threaded=threaded, processes=processes):
"""Start a new development server."""
from werkzeug.serving import run_simple
app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions)
run_simple(hostname, port, app, False, None, threaded, processes)
return action | [
"def",
"make_action",
"(",
"app_factory",
",",
"hostname",
"=",
"'localhost'",
",",
"port",
"=",
"5000",
",",
"threaded",
"=",
"False",
",",
"processes",
"=",
"1",
",",
"stream",
"=",
"None",
",",
"sort_by",
"=",
"(",
"'time'",
",",
"'calls'",
")",
","... | https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/werkzeug/contrib/profiler.py#L101-L118 | |
roclark/sportsipy | c19f545d3376d62ded6304b137dc69238ac620a9 | sportsipy/ncaaf/player.py | python | AbstractPlayer.player_id | (self) | return self._player_id | Returns a ``string`` of the player's ID on sports-reference, such as
'david-blough-1' for David Blough. | Returns a ``string`` of the player's ID on sports-reference, such as
'david-blough-1' for David Blough. | [
"Returns",
"a",
"string",
"of",
"the",
"player",
"s",
"ID",
"on",
"sports",
"-",
"reference",
"such",
"as",
"david",
"-",
"blough",
"-",
"1",
"for",
"David",
"Blough",
"."
] | def player_id(self):
"""
Returns a ``string`` of the player's ID on sports-reference, such as
'david-blough-1' for David Blough.
"""
return self._player_id | [
"def",
"player_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_player_id"
] | https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/ncaaf/player.py#L193-L198 | |
LuxCoreRender/BlendLuxCore | bf31ca58501d54c02acd97001b6db7de81da7cbf | nodes/materials/tree.py | python | LuxCoreMaterialNodeTree.get_from_context | (cls, context) | return None, None, None | Switches the displayed node tree when user selects object/material | Switches the displayed node tree when user selects object/material | [
"Switches",
"the",
"displayed",
"node",
"tree",
"when",
"user",
"selects",
"object",
"/",
"material"
] | def get_from_context(cls, context):
"""
Switches the displayed node tree when user selects object/material
"""
obj = context.active_object
if obj and obj.type not in {"LIGHT", "CAMERA"}:
mat = obj.active_material
if mat:
node_tree = mat.luxcore.node_tree
if node_tree:
return node_tree, mat, mat
return None, None, None | [
"def",
"get_from_context",
"(",
"cls",
",",
"context",
")",
":",
"obj",
"=",
"context",
".",
"active_object",
"if",
"obj",
"and",
"obj",
".",
"type",
"not",
"in",
"{",
"\"LIGHT\"",
",",
"\"CAMERA\"",
"}",
":",
"mat",
"=",
"obj",
".",
"active_material",
... | https://github.com/LuxCoreRender/BlendLuxCore/blob/bf31ca58501d54c02acd97001b6db7de81da7cbf/nodes/materials/tree.py#L15-L30 | |
edfungus/Crouton | ada98b3930192938a48909072b45cb84b945f875 | clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/setuptools/package_index.py | python | htmldecode | (text) | return entity_sub(decode_entity, text) | Decode HTML entities in the given text. | Decode HTML entities in the given text. | [
"Decode",
"HTML",
"entities",
"in",
"the",
"given",
"text",
"."
] | def htmldecode(text):
"""Decode HTML entities in the given text."""
return entity_sub(decode_entity, text) | [
"def",
"htmldecode",
"(",
"text",
")",
":",
"return",
"entity_sub",
"(",
"decode_entity",
",",
"text",
")"
] | https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/cf_demo_client/cf_env/lib/python2.7/site-packages/setuptools/package_index.py#L884-L886 | |
Georce/lepus | 5b01bae82b5dc1df00c9e058989e2eb9b89ff333 | lepus/pymongo-2.7/pymongo/mongo_replica_set_client.py | python | MongoReplicaSetClient.max_write_batch_size | (self) | return common.MAX_WRITE_BATCH_SIZE | The maxWriteBatchSize reported by the server.
Returns a default value when connected to server versions prior to
MongoDB 2.6.
.. versionadded:: 2.7 | The maxWriteBatchSize reported by the server. | [
"The",
"maxWriteBatchSize",
"reported",
"by",
"the",
"server",
"."
] | def max_write_batch_size(self):
"""The maxWriteBatchSize reported by the server.
Returns a default value when connected to server versions prior to
MongoDB 2.6.
.. versionadded:: 2.7
"""
rs_state = self.__rs_state
if rs_state.primary_member:
return rs_state.primary_member.max_write_batch_size
return common.MAX_WRITE_BATCH_SIZE | [
"def",
"max_write_batch_size",
"(",
"self",
")",
":",
"rs_state",
"=",
"self",
".",
"__rs_state",
"if",
"rs_state",
".",
"primary_member",
":",
"return",
"rs_state",
".",
"primary_member",
".",
"max_write_batch_size",
"return",
"common",
".",
"MAX_WRITE_BATCH_SIZE"
... | https://github.com/Georce/lepus/blob/5b01bae82b5dc1df00c9e058989e2eb9b89ff333/lepus/pymongo-2.7/pymongo/mongo_replica_set_client.py#L990-L1001 | |
shiyanlou/louplus-python | 4c61697259e286e3d9116c3299f170d019ba3767 | taobei/challenge-06/tbweb/handlers/order.py | python | create | () | return render_template('order/create.html', form=form, cart_products=cart_products) | 创建订单 | 创建订单 | [
"创建订单"
] | def create():
"""创建订单
"""
form = OrderForm()
resp = TbUser(current_app).get_json('/addresses', params={
'user_id': current_user.get_id(),
})
addresses = resp['data']['addresses']
form.address_id.choices = [(str(v['id']), v['address']) for v in addresses]
for addresse in addresses:
if addresse['is_default']:
form.address_id.data = str(addresse['id'])
resp = TbBuy(current_app).get_json('/cart_products', params={
'user_id': current_user.get_id(),
})
cart_products = resp['data']['cart_products']
if len(cart_products) == 0:
flash('购物车为空', 'danger')
return redirect(url_for('cart_product.index'))
resp = TbMall(current_app).get_json('/products/infos', params={
'ids': ','.join([str(v['product_id']) for v in cart_products]),
})
for cart_product in cart_products:
cart_product['product'] = resp['data']['products'].get(
str(cart_product['product_id']))
if form.validate_on_submit():
# 检查商品数量是否足够
for cart_product in cart_products:
if cart_product['amount'] > cart_product['product']['amount']:
flash('商品“{}”数量不足'.format(
cart_product['product']['title']), 'danger')
return render_template('order/create.html', form=form, cart_products=cart_products)
# 创建订单
resp = TbBuy(current_app).post_json('/orders', json={
'address_id': form.address_id.data,
'note': form.note.data,
'order_products': [
{
'product_id': v['product_id'],
'amount': v['amount'],
'price': v['product']['price'],
} for v in cart_products
],
'user_id': current_user.get_id(),
}, check_code=False)
if resp['code'] != 0:
flash(resp['message'], 'danger')
return render_template('order/create.html', form=form, cart_products=cart_products)
# 扣除商品数量
for cart_product in cart_products:
resp = TbMall(current_app).post_json(
'/products/{}'.format(cart_product['product_id']), json={
'amount': cart_product['product']['amount'] - cart_product['amount'],
})
if resp['code'] != 0:
flash(resp['message'], 'danger')
return render_template('order/create.html', form=form, cart_products=cart_products)
# 清空购物车
resp = TbBuy(current_app).delete_json('/cart_products', params={
'user_id': current_user.get_id(),
})
if resp['code'] != 0:
flash(resp['message'], 'danger')
return render_template('order/create.html', form=form, cart_products=cart_products)
return redirect(url_for('.index'))
return render_template('order/create.html', form=form, cart_products=cart_products) | [
"def",
"create",
"(",
")",
":",
"form",
"=",
"OrderForm",
"(",
")",
"resp",
"=",
"TbUser",
"(",
"current_app",
")",
".",
"get_json",
"(",
"'/addresses'",
",",
"params",
"=",
"{",
"'user_id'",
":",
"current_user",
".",
"get_id",
"(",
")",
",",
"}",
")... | https://github.com/shiyanlou/louplus-python/blob/4c61697259e286e3d9116c3299f170d019ba3767/taobei/challenge-06/tbweb/handlers/order.py#L72-L147 | |
biopython/biopython | 2dd97e71762af7b046d7f7f8a4f1e38db6b06c86 | Bio/SeqFeature.py | python | WithinPosition.extension | (self) | return self._right - self._left | Legacy attribute to get extension (from left to right) as an integer (OBSOLETE). | Legacy attribute to get extension (from left to right) as an integer (OBSOLETE). | [
"Legacy",
"attribute",
"to",
"get",
"extension",
"(",
"from",
"left",
"to",
"right",
")",
"as",
"an",
"integer",
"(",
"OBSOLETE",
")",
"."
] | def extension(self): # noqa: D402
"""Legacy attribute to get extension (from left to right) as an integer (OBSOLETE).""" # noqa: D402
return self._right - self._left | [
"def",
"extension",
"(",
"self",
")",
":",
"# noqa: D402",
"# noqa: D402",
"return",
"self",
".",
"_right",
"-",
"self",
".",
"_left"
] | https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/SeqFeature.py#L1817-L1819 | |
PokemonGoF/PokemonGo-Bot-Desktop | 4bfa94f0183406c6a86f93645eff7abd3ad4ced8 | build/pywin/Lib/xml/sax/xmlreader.py | python | XMLReader.setFeature | (self, name, state) | Sets the state of a SAX2 feature. | Sets the state of a SAX2 feature. | [
"Sets",
"the",
"state",
"of",
"a",
"SAX2",
"feature",
"."
] | def setFeature(self, name, state):
"Sets the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name) | [
"def",
"setFeature",
"(",
"self",
",",
"name",
",",
"state",
")",
":",
"raise",
"SAXNotRecognizedException",
"(",
"\"Feature '%s' not recognized\"",
"%",
"name",
")"
] | https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/xml/sax/xmlreader.py#L79-L81 | ||
ParmEd/ParmEd | cd763f2e83c98ba9e51676f6dbebf0eebfd5157e | parmed/modeller/residue.py | python | ResidueTemplate.to_dataframe | (self) | return ret | Create a pandas dataframe from the atom information
Returns
-------
df : :class:`pandas.DataFrame`
The pandas DataFrame with all of the atomic properties
Notes
-----
The DataFrame will be over all atoms. The columns will be the attributes
of the atom (as well as its containing residue). Some columns will
*always* exist. Others will only exist if those attributes have been set
on the Atom instances (see the :class:`Atom` docs for possible
attributes and their meaning). The columns that will always be present
are:
- number : int
- name : str
- type : str
- atomic_number : int
- charge : float
- mass : float
- nb_idx : int
- solvent_radius : float
- screen : float
- occupancy : float
- bfactor : float
- altloc : str
- tree : str
- join : int
- irotat : int
- rmin : float
- epsilon : float
- rmin_14 : float
- epsilon_14 : float
The following attributes are optionally present if they were present in
the original file defining the structure:
- xx : float (x-coordinate position)
- xy : float (y-coordinate position)
- xz : float (z-coordinate position)
- vx : float (x-coordinate velocity)
- vy : float (y-coordinate velocity)
- vz : float (z-coordinate velocity) | Create a pandas dataframe from the atom information | [
"Create",
"a",
"pandas",
"dataframe",
"from",
"the",
"atom",
"information"
] | def to_dataframe(self):
""" Create a pandas dataframe from the atom information
Returns
-------
df : :class:`pandas.DataFrame`
The pandas DataFrame with all of the atomic properties
Notes
-----
The DataFrame will be over all atoms. The columns will be the attributes
of the atom (as well as its containing residue). Some columns will
*always* exist. Others will only exist if those attributes have been set
on the Atom instances (see the :class:`Atom` docs for possible
attributes and their meaning). The columns that will always be present
are:
- number : int
- name : str
- type : str
- atomic_number : int
- charge : float
- mass : float
- nb_idx : int
- solvent_radius : float
- screen : float
- occupancy : float
- bfactor : float
- altloc : str
- tree : str
- join : int
- irotat : int
- rmin : float
- epsilon : float
- rmin_14 : float
- epsilon_14 : float
The following attributes are optionally present if they were present in
the original file defining the structure:
- xx : float (x-coordinate position)
- xy : float (y-coordinate position)
- xz : float (z-coordinate position)
- vx : float (x-coordinate velocity)
- vy : float (y-coordinate velocity)
- vz : float (z-coordinate velocity)
"""
import pandas as pd
ret = pd.DataFrame()
ret['number'] = [atom.number for atom in self.atoms]
ret['name'] = [atom.name for atom in self.atoms]
ret['type'] = [atom.type for atom in self.atoms]
ret['atomic_number'] = [atom.atomic_number for atom in self.atoms]
ret['charge'] = [atom.charge for atom in self.atoms]
ret['mass'] = [atom.mass for atom in self.atoms]
ret['nb_idx'] = [atom.nb_idx for atom in self.atoms]
ret['solvent_radius'] = [atom.solvent_radius for atom in self.atoms]
ret['screen'] = [atom.screen for atom in self.atoms]
ret['occupancy'] = [atom.occupancy for atom in self.atoms]
ret['bfactor'] = [atom.bfactor for atom in self.atoms]
ret['altloc'] = [atom.altloc for atom in self.atoms]
ret['tree'] = [atom.tree for atom in self.atoms]
ret['join'] = [atom.join for atom in self.atoms]
ret['irotat'] = [atom.irotat for atom in self.atoms]
ret['rmin'] = [atom.rmin for atom in self.atoms]
ret['epsilon'] = [atom.epsilon for atom in self.atoms]
ret['rmin_14'] = [atom.rmin_14 for atom in self.atoms]
ret['epsilon_14'] = [atom.epsilon_14 for atom in self.atoms]
ret['resname'] = [atom.residue.name for atom in self.atoms]
# Now for optional attributes
# Coordinates
try:
coords = pd.DataFrame(
[[atom.xx, atom.xy, atom.xz] for atom in self.atoms], columns=['xx', 'xy', 'xz']
)
except AttributeError:
pass
else:
ret = ret.join(coords)
# Velocities
try:
vels = pd.DataFrame(
[[atom.vx, atom.vy, atom.vz] for atom in self.atoms], columns=['vx', 'vy', 'vz']
)
except AttributeError:
pass
else:
ret = ret.join(vels)
return ret | [
"def",
"to_dataframe",
"(",
"self",
")",
":",
"import",
"pandas",
"as",
"pd",
"ret",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"ret",
"[",
"'number'",
"]",
"=",
"[",
"atom",
".",
"number",
"for",
"atom",
"in",
"self",
".",
"atoms",
"]",
"ret",
"[",
... | https://github.com/ParmEd/ParmEd/blob/cd763f2e83c98ba9e51676f6dbebf0eebfd5157e/parmed/modeller/residue.py#L569-L659 | |
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/inject/thirdparty/gprof2dot/gprof2dot.py | python | CallgrindParser.parse_part_detail | (self) | return self.parse_keys(self._detail_keys) | [] | def parse_part_detail(self):
return self.parse_keys(self._detail_keys) | [
"def",
"parse_part_detail",
"(",
"self",
")",
":",
"return",
"self",
".",
"parse_keys",
"(",
"self",
".",
"_detail_keys",
")"
] | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/gprof2dot/gprof2dot.py#L1099-L1100 | |||
hahnyuan/nn_tools | e04903d2946a75b62128b64ada7eec8b9fbd841f | Datasets/lmdb_datasets.py | python | LMDB_generator.generate_dataset | (self,datas,targets,others=None) | return dataset | [] | def generate_dataset(self,datas,targets,others=None):
dataset = pb2.Dataset()
assert len(datas)==len(targets),ValueError('the lengths of datas and targets are not the same')
for idx in xrange(len(datas)):
try:
if others==None:
datum=self.generate_datum(datas[idx],targets[idx])
else:
datum = self.generate_datum(datas[idx], targets[idx],others[idx])
except:
print('generate the datum failed at %d, continue it'%idx)
continue
dataset.datums.extend([datum])
return dataset | [
"def",
"generate_dataset",
"(",
"self",
",",
"datas",
",",
"targets",
",",
"others",
"=",
"None",
")",
":",
"dataset",
"=",
"pb2",
".",
"Dataset",
"(",
")",
"assert",
"len",
"(",
"datas",
")",
"==",
"len",
"(",
"targets",
")",
",",
"ValueError",
"(",... | https://github.com/hahnyuan/nn_tools/blob/e04903d2946a75b62128b64ada7eec8b9fbd841f/Datasets/lmdb_datasets.py#L32-L45 | |||
enkore/i3pystatus | 34af13547dfb8407d9cf47473b8068e681dcc55f | i3pystatus/core/util.py | python | get_module | (function) | return call_wrapper | Function decorator for retrieving the ``self`` argument from the stack.
Intended for use with callbacks that need access to a modules variables, for example:
.. code:: python
from i3pystatus import Status, get_module
from i3pystatus.core.command import execute
status = Status(...)
# other modules etc.
@get_module
def display_ip_verbose(module):
execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface))
status.register("network", interface="wlan1", on_leftclick=display_ip_verbose) | Function decorator for retrieving the ``self`` argument from the stack. | [
"Function",
"decorator",
"for",
"retrieving",
"the",
"self",
"argument",
"from",
"the",
"stack",
"."
] | def get_module(function):
"""Function decorator for retrieving the ``self`` argument from the stack.
Intended for use with callbacks that need access to a modules variables, for example:
.. code:: python
from i3pystatus import Status, get_module
from i3pystatus.core.command import execute
status = Status(...)
# other modules etc.
@get_module
def display_ip_verbose(module):
execute('sh -c "ip addr show dev {dev} | xmessage -file -"'.format(dev=module.interface))
status.register("network", interface="wlan1", on_leftclick=display_ip_verbose)
"""
@functools.wraps(function)
def call_wrapper(*args, **kwargs):
stack = inspect.stack()
caller_frame_info = stack[1]
self = caller_frame_info[0].f_locals["self"]
# not completly sure whether this is necessary
# see note in Python docs about stack frames
del stack
function(self, *args, **kwargs)
return call_wrapper | [
"def",
"get_module",
"(",
"function",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"function",
")",
"def",
"call_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"caller_frame_info",
"=",... | https://github.com/enkore/i3pystatus/blob/34af13547dfb8407d9cf47473b8068e681dcc55f/i3pystatus/core/util.py#L668-L693 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/motech/repeaters/models.py | python | ReferCaseRepeater.get_url | (self, repeat_record) | return self.connection_settings.url.format(domain=new_domain) | [] | def get_url(self, repeat_record):
new_domain = self.payload_doc(repeat_record).get_case_property('new_domain')
return self.connection_settings.url.format(domain=new_domain) | [
"def",
"get_url",
"(",
"self",
",",
"repeat_record",
")",
":",
"new_domain",
"=",
"self",
".",
"payload_doc",
"(",
"repeat_record",
")",
".",
"get_case_property",
"(",
"'new_domain'",
")",
"return",
"self",
".",
"connection_settings",
".",
"url",
".",
"format"... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/motech/repeaters/models.py#L724-L726 | |||
shunsukesaito/PIFu | 02a6d8643d3267d06cb4a510b30a59e7e07255de | lib/train_util.py | python | calc_error_color | (opt, netG, netC, cuda, dataset, num_tests) | return np.average(error_color_arr) | [] | def calc_error_color(opt, netG, netC, cuda, dataset, num_tests):
if num_tests > len(dataset):
num_tests = len(dataset)
with torch.no_grad():
error_color_arr = []
for idx in tqdm(range(num_tests)):
data = dataset[idx * len(dataset) // num_tests]
# retrieve the data
image_tensor = data['img'].to(device=cuda)
calib_tensor = data['calib'].to(device=cuda)
color_sample_tensor = data['color_samples'].to(device=cuda).unsqueeze(0)
if opt.num_views > 1:
color_sample_tensor = reshape_sample_tensor(color_sample_tensor, opt.num_views)
rgb_tensor = data['rgbs'].to(device=cuda).unsqueeze(0)
netG.filter(image_tensor)
_, errorC = netC.forward(image_tensor, netG.get_im_feat(), color_sample_tensor, calib_tensor, labels=rgb_tensor)
# print('{0}/{1} | Error inout: {2:06f} | Error color: {3:06f}'
# .format(idx, num_tests, errorG.item(), errorC.item()))
error_color_arr.append(errorC.item())
return np.average(error_color_arr) | [
"def",
"calc_error_color",
"(",
"opt",
",",
"netG",
",",
"netC",
",",
"cuda",
",",
"dataset",
",",
"num_tests",
")",
":",
"if",
"num_tests",
">",
"len",
"(",
"dataset",
")",
":",
"num_tests",
"=",
"len",
"(",
"dataset",
")",
"with",
"torch",
".",
"no... | https://github.com/shunsukesaito/PIFu/blob/02a6d8643d3267d06cb4a510b30a59e7e07255de/lib/train_util.py#L178-L203 | |||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/polys/agca/modules.py | python | QuotientModule.is_submodule | (self, other) | return False | Return True if ``other`` is a submodule of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> S = Q.submodule([1, 0])
>>> Q.is_submodule(S)
True
>>> S.is_submodule(Q)
False | Return True if ``other`` is a submodule of ``self``. | [
"Return",
"True",
"if",
"other",
"is",
"a",
"submodule",
"of",
"self",
"."
] | def is_submodule(self, other):
"""
Return True if ``other`` is a submodule of ``self``.
>>> from sympy.abc import x
>>> from sympy import QQ
>>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)]
>>> S = Q.submodule([1, 0])
>>> Q.is_submodule(S)
True
>>> S.is_submodule(Q)
False
"""
if isinstance(other, QuotientModule):
return self.killed_module == other.killed_module and \
self.base.is_submodule(other.base)
if isinstance(other, SubQuotientModule):
return other.container == self
return False | [
"def",
"is_submodule",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"QuotientModule",
")",
":",
"return",
"self",
".",
"killed_module",
"==",
"other",
".",
"killed_module",
"and",
"self",
".",
"base",
".",
"is_submodule",
"("... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/polys/agca/modules.py#L1296-L1314 | |
jayleicn/scipy-lecture-notes-zh-CN | cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6 | packages/traits/reservoir_state_property.py | python | ReservoirState._get_storage | (self) | return min(new_storage, self.max_storage) | [] | def _get_storage(self):
new_storage = self._storage - self.release + self.inflows
return min(new_storage, self.max_storage) | [
"def",
"_get_storage",
"(",
"self",
")",
":",
"new_storage",
"=",
"self",
".",
"_storage",
"-",
"self",
".",
"release",
"+",
"self",
".",
"inflows",
"return",
"min",
"(",
"new_storage",
",",
"self",
".",
"max_storage",
")"
] | https://github.com/jayleicn/scipy-lecture-notes-zh-CN/blob/cc87204fcc4bd2f4702f7c29c83cb8ed5c94b7d6/packages/traits/reservoir_state_property.py#L31-L33 | |||
dBeker/Faster-RCNN-TensorFlow-Python3 | 027e5603551b3b9053042a113b4c7be9579dbb4a | demo.py | python | vis_detections | (im, class_name, dets, thresh=0.5) | Draw detected bounding boxes. | Draw detected bounding boxes. | [
"Draw",
"detected",
"bounding",
"boxes",
"."
] | def vis_detections(im, class_name, dets, thresh=0.5):
"""Draw detected bounding boxes."""
inds = np.where(dets[:, -1] >= thresh)[0]
if len(inds) == 0:
return
im = im[:, :, (2, 1, 0)]
fig, ax = plt.subplots(figsize=(12, 12))
ax.imshow(im, aspect='equal')
for i in inds:
bbox = dets[i, :4]
score = dets[i, -1]
ax.add_patch(
plt.Rectangle((bbox[0], bbox[1]),
bbox[2] - bbox[0],
bbox[3] - bbox[1], fill=False,
edgecolor='red', linewidth=3.5)
)
ax.text(bbox[0], bbox[1] - 2,
'{:s} {:.3f}'.format(class_name, score),
bbox=dict(facecolor='blue', alpha=0.5),
fontsize=14, color='white')
ax.set_title(('{} detections with '
'p({} | box) >= {:.1f}').format(class_name, class_name,
thresh),
fontsize=14)
plt.axis('off')
plt.tight_layout()
plt.draw() | [
"def",
"vis_detections",
"(",
"im",
",",
"class_name",
",",
"dets",
",",
"thresh",
"=",
"0.5",
")",
":",
"inds",
"=",
"np",
".",
"where",
"(",
"dets",
"[",
":",
",",
"-",
"1",
"]",
">=",
"thresh",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"inds",
... | https://github.com/dBeker/Faster-RCNN-TensorFlow-Python3/blob/027e5603551b3b9053042a113b4c7be9579dbb4a/demo.py#L43-L73 | ||
spack/spack | 675210bd8bd1c5d32ad1cc83d898fb43b569ed74 | lib/spack/external/altgraph/Graph.py | python | Graph.back_topo_sort | (self) | return self._topo_sort(forward=False) | Reverse topological sort.
Returns a list of nodes where the successors (based on incoming edges)
of any given node appear in the sequence after that node. | Reverse topological sort. | [
"Reverse",
"topological",
"sort",
"."
] | def back_topo_sort(self):
"""
Reverse topological sort.
Returns a list of nodes where the successors (based on incoming edges)
of any given node appear in the sequence after that node.
"""
return self._topo_sort(forward=False) | [
"def",
"back_topo_sort",
"(",
"self",
")",
":",
"return",
"self",
".",
"_topo_sort",
"(",
"forward",
"=",
"False",
")"
] | https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/external/altgraph/Graph.py#L433-L440 | |
thu-coai/CrossWOZ | 265e97379b34221f5949beb46f3eec0e2dc943c4 | convlab2/dst/trade/crosswoz/utils/logger.py | python | Logger.__init__ | (self, log_dir) | Create a summary writer logging to log_dir. | Create a summary writer logging to log_dir. | [
"Create",
"a",
"summary",
"writer",
"logging",
"to",
"log_dir",
"."
] | def __init__(self, log_dir):
"""Create a summary writer logging to log_dir."""
self.writer = tf.summary.FileWriter(log_dir) | [
"def",
"__init__",
"(",
"self",
",",
"log_dir",
")",
":",
"self",
".",
"writer",
"=",
"tf",
".",
"summary",
".",
"FileWriter",
"(",
"log_dir",
")"
] | https://github.com/thu-coai/CrossWOZ/blob/265e97379b34221f5949beb46f3eec0e2dc943c4/convlab2/dst/trade/crosswoz/utils/logger.py#L13-L15 | ||
glitchdotcom/WebPutty | 4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7 | libs/babel/messages/mofile.py | python | write_mo | (fileobj, catalog, use_fuzzy=False) | Write a catalog to the specified file-like object using the GNU MO file
format.
>>> from babel.messages import Catalog
>>> from gettext import GNUTranslations
>>> from StringIO import StringIO
>>> catalog = Catalog(locale='en_US')
>>> catalog.add('foo', 'Voh')
>>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz'))
>>> catalog.add('fuz', 'Futz', flags=['fuzzy'])
>>> catalog.add('Fizz', '')
>>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
>>> buf = StringIO()
>>> write_mo(buf, catalog)
>>> buf.seek(0)
>>> translations = GNUTranslations(fp=buf)
>>> translations.ugettext('foo')
u'Voh'
>>> translations.ungettext('bar', 'baz', 1)
u'Bahr'
>>> translations.ungettext('bar', 'baz', 2)
u'Batz'
>>> translations.ugettext('fuz')
u'fuz'
>>> translations.ugettext('Fizz')
u'Fizz'
>>> translations.ugettext('Fuzz')
u'Fuzz'
>>> translations.ugettext('Fuzzes')
u'Fuzzes'
:param fileobj: the file-like object to write to
:param catalog: the `Catalog` instance
:param use_fuzzy: whether translations marked as "fuzzy" should be included
in the output | Write a catalog to the specified file-like object using the GNU MO file
format.
>>> from babel.messages import Catalog
>>> from gettext import GNUTranslations
>>> from StringIO import StringIO
>>> catalog = Catalog(locale='en_US')
>>> catalog.add('foo', 'Voh')
>>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz'))
>>> catalog.add('fuz', 'Futz', flags=['fuzzy'])
>>> catalog.add('Fizz', '')
>>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
>>> buf = StringIO()
>>> write_mo(buf, catalog)
>>> buf.seek(0)
>>> translations = GNUTranslations(fp=buf)
>>> translations.ugettext('foo')
u'Voh'
>>> translations.ungettext('bar', 'baz', 1)
u'Bahr'
>>> translations.ungettext('bar', 'baz', 2)
u'Batz'
>>> translations.ugettext('fuz')
u'fuz'
>>> translations.ugettext('Fizz')
u'Fizz'
>>> translations.ugettext('Fuzz')
u'Fuzz'
>>> translations.ugettext('Fuzzes')
u'Fuzzes'
:param fileobj: the file-like object to write to
:param catalog: the `Catalog` instance
:param use_fuzzy: whether translations marked as "fuzzy" should be included
in the output | [
"Write",
"a",
"catalog",
"to",
"the",
"specified",
"file",
"-",
"like",
"object",
"using",
"the",
"GNU",
"MO",
"file",
"format",
".",
">>>",
"from",
"babel",
".",
"messages",
"import",
"Catalog",
">>>",
"from",
"gettext",
"import",
"GNUTranslations",
">>>",
... | def write_mo(fileobj, catalog, use_fuzzy=False):
"""Write a catalog to the specified file-like object using the GNU MO file
format.
>>> from babel.messages import Catalog
>>> from gettext import GNUTranslations
>>> from StringIO import StringIO
>>> catalog = Catalog(locale='en_US')
>>> catalog.add('foo', 'Voh')
>>> catalog.add((u'bar', u'baz'), (u'Bahr', u'Batz'))
>>> catalog.add('fuz', 'Futz', flags=['fuzzy'])
>>> catalog.add('Fizz', '')
>>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
>>> buf = StringIO()
>>> write_mo(buf, catalog)
>>> buf.seek(0)
>>> translations = GNUTranslations(fp=buf)
>>> translations.ugettext('foo')
u'Voh'
>>> translations.ungettext('bar', 'baz', 1)
u'Bahr'
>>> translations.ungettext('bar', 'baz', 2)
u'Batz'
>>> translations.ugettext('fuz')
u'fuz'
>>> translations.ugettext('Fizz')
u'Fizz'
>>> translations.ugettext('Fuzz')
u'Fuzz'
>>> translations.ugettext('Fuzzes')
u'Fuzzes'
:param fileobj: the file-like object to write to
:param catalog: the `Catalog` instance
:param use_fuzzy: whether translations marked as "fuzzy" should be included
in the output
"""
messages = list(catalog)
if not use_fuzzy:
messages[1:] = [m for m in messages[1:] if not m.fuzzy]
messages.sort()
ids = strs = ''
offsets = []
for message in messages:
# For each string, we need size and file offset. Each string is NUL
# terminated; the NUL does not count into the size.
if message.pluralizable:
msgid = '\x00'.join([
msgid.encode(catalog.charset) for msgid in message.id
])
msgstrs = []
for idx, string in enumerate(message.string):
if not string:
msgstrs.append(message.id[min(int(idx), 1)])
else:
msgstrs.append(string)
msgstr = '\x00'.join([
msgstr.encode(catalog.charset) for msgstr in msgstrs
])
else:
msgid = message.id.encode(catalog.charset)
if not message.string:
msgstr = message.id.encode(catalog.charset)
else:
msgstr = message.string.encode(catalog.charset)
offsets.append((len(ids), len(msgid), len(strs), len(msgstr)))
ids += msgid + '\x00'
strs += msgstr + '\x00'
# The header is 7 32-bit unsigned integers. We don't use hash tables, so
# the keys start right after the index tables.
keystart = 7 * 4 + 16 * len(messages)
valuestart = keystart + len(ids)
# The string table first has the list of keys, then the list of values.
# Each entry has first the size of the string, then the file offset.
koffsets = []
voffsets = []
for o1, l1, o2, l2 in offsets:
koffsets += [l1, o1 + keystart]
voffsets += [l2, o2 + valuestart]
offsets = koffsets + voffsets
fileobj.write(struct.pack('Iiiiiii',
0x950412deL, # magic
0, # version
len(messages), # number of entries
7 * 4, # start of key index
7 * 4 + len(messages) * 8, # start of value index
0, 0 # size and offset of hash table
) + array.array("i", offsets).tostring() + ids + strs) | [
"def",
"write_mo",
"(",
"fileobj",
",",
"catalog",
",",
"use_fuzzy",
"=",
"False",
")",
":",
"messages",
"=",
"list",
"(",
"catalog",
")",
"if",
"not",
"use_fuzzy",
":",
"messages",
"[",
"1",
":",
"]",
"=",
"[",
"m",
"for",
"m",
"in",
"messages",
"... | https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/libs/babel/messages/mofile.py#L27-L121 | ||
edisonlz/fastor | 342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3 | base/site-packages/django/utils/functional.py | python | allow_lazy | (func, *resultclasses) | return wrapper | A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed. | A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed. | [
"A",
"decorator",
"that",
"allows",
"a",
"function",
"to",
"be",
"called",
"with",
"one",
"or",
"more",
"lazy",
"arguments",
".",
"If",
"none",
"of",
"the",
"args",
"are",
"lazy",
"the",
"function",
"is",
"evaluated",
"immediately",
"otherwise",
"a",
"__pr... | def allow_lazy(func, *resultclasses):
"""
A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed.
"""
@wraps(func)
def wrapper(*args, **kwargs):
for arg in list(args) + list(six.itervalues(kwargs)):
if isinstance(arg, Promise):
break
else:
return func(*args, **kwargs)
return lazy(func, *resultclasses)(*args, **kwargs)
return wrapper | [
"def",
"allow_lazy",
"(",
"func",
",",
"*",
"resultclasses",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"arg",
"in",
"list",
"(",
"args",
")",
"+",
"list",
"(",
"six",
... | https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/utils/functional.py#L190-L205 | |
Yuliang-Liu/Box_Discretization_Network | 5b3a30c97429ef8e5c5e1c4e2476c7d9abdc03e6 | maskrcnn_benchmark/modeling/backbone/resnet.py | python | StemWithGN.__init__ | (self, cfg) | [] | def __init__(self, cfg):
super(StemWithGN, self).__init__(cfg, norm_func=group_norm) | [
"def",
"__init__",
"(",
"self",
",",
"cfg",
")",
":",
"super",
"(",
"StemWithGN",
",",
"self",
")",
".",
"__init__",
"(",
"cfg",
",",
"norm_func",
"=",
"group_norm",
")"
] | https://github.com/Yuliang-Liu/Box_Discretization_Network/blob/5b3a30c97429ef8e5c5e1c4e2476c7d9abdc03e6/maskrcnn_benchmark/modeling/backbone/resnet.py#L455-L456 | ||||
redhat-imaging/imagefactory | 176f6e045e1df049d50f33a924653128d5ab8b27 | imgfac/rest/bottle.py | python | ConfigDict.setdefault | (self, key, value) | return self[key] | [] | def setdefault(self, key, value):
if key not in self:
self[key] = value
return self[key] | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"self",
":",
"self",
"[",
"key",
"]",
"=",
"value",
"return",
"self",
"[",
"key",
"]"
] | https://github.com/redhat-imaging/imagefactory/blob/176f6e045e1df049d50f33a924653128d5ab8b27/imgfac/rest/bottle.py#L2138-L2141 | |||
huggingface/datasets | 249b4a38390bf1543f5b6e2f3dc208b5689c1c13 | datasets/igbo_ner/igbo_ner.py | python | IgboNer._generate_examples | (self, filepath, split) | Yields examples. | Yields examples. | [
"Yields",
"examples",
"."
] | def _generate_examples(self, filepath, split):
"""Yields examples."""
dictionary = {}
with open(filepath, "r", encoding="utf-8-sig") as f:
if self.config.name == "ner_data":
for id_, row in enumerate(f):
row = row.strip().split("\t")
content_n = row[0]
if content_n in dictionary.keys():
(dictionary[content_n]["sentences"]).append(row[1])
else:
dictionary[content_n] = {}
dictionary[content_n]["named_entity"] = row[1]
dictionary[content_n]["sentences"] = [row[1]]
yield id_, {
"content_n": content_n,
"named_entity": dictionary[content_n]["named_entity"],
"sentences": dictionary[content_n]["sentences"],
}
else:
for id_, row in enumerate(f):
yield id_, {
"sentences": row.strip(),
} | [
"def",
"_generate_examples",
"(",
"self",
",",
"filepath",
",",
"split",
")",
":",
"dictionary",
"=",
"{",
"}",
"with",
"open",
"(",
"filepath",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8-sig\"",
")",
"as",
"f",
":",
"if",
"self",
".",
"config",
".",... | https://github.com/huggingface/datasets/blob/249b4a38390bf1543f5b6e2f3dc208b5689c1c13/datasets/igbo_ner/igbo_ner.py#L99-L122 | ||
voc/voctomix | 3156f3546890e6ae8d379df17e5cc718eee14b15 | voctocore/lib/config.py | python | VoctocoreConfigParser.getScheduleEvent | (self) | return overlay/event or <None> from INI configuration | return overlay/event or <None> from INI configuration | [
"return",
"overlay",
"/",
"event",
"or",
"<None",
">",
"from",
"INI",
"configuration"
] | def getScheduleEvent(self):
''' return overlay/event or <None> from INI configuration '''
if self.has_option('overlay', 'event'):
if self.has_option('overlay', 'room'):
self.log.warning(
"'overlay'/'event' overwrites 'overlay'/'room'")
return self.get('overlay', 'event')
else:
return None | [
"def",
"getScheduleEvent",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_option",
"(",
"'overlay'",
",",
"'event'",
")",
":",
"if",
"self",
".",
"has_option",
"(",
"'overlay'",
",",
"'room'",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"'over... | https://github.com/voc/voctomix/blob/3156f3546890e6ae8d379df17e5cc718eee14b15/voctocore/lib/config.py#L56-L64 | ||
Project-MONAI/MONAI | 83f8b06372a3803ebe9281300cb794a1f3395018 | monai/data/dataset.py | python | SmartCacheDataset.start | (self) | Start the background thread to replace training items for every epoch. | Start the background thread to replace training items for every epoch. | [
"Start",
"the",
"background",
"thread",
"to",
"replace",
"training",
"items",
"for",
"every",
"epoch",
"."
] | def start(self):
"""
Start the background thread to replace training items for every epoch.
"""
if self._replace_mgr is None or not self.is_started():
self._restart() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_replace_mgr",
"is",
"None",
"or",
"not",
"self",
".",
"is_started",
"(",
")",
":",
"self",
".",
"_restart",
"(",
")"
] | https://github.com/Project-MONAI/MONAI/blob/83f8b06372a3803ebe9281300cb794a1f3395018/monai/data/dataset.py#L938-L944 | ||
tensorflow/tensorboard | 61d11d99ef034c30ba20b6a7840c8eededb9031c | tensorboard/compat/tensorflow_stub/tensor_shape.py | python | Dimension.__ge__ | (self, other) | Returns True if `self` is known to be greater than or equal to
`other`.
Dimensions are compared as follows:
```python
(tf.Dimension(m) >= tf.Dimension(n)) == (m >= n)
(tf.Dimension(m) >= tf.Dimension(None)) == None
(tf.Dimension(None) >= tf.Dimension(n)) == None
(tf.Dimension(None) >= tf.Dimension(None)) == None
```
Args:
other: Another Dimension.
Returns:
The value of `self.value >= other.value` if both are known, otherwise
None. | Returns True if `self` is known to be greater than or equal to
`other`. | [
"Returns",
"True",
"if",
"self",
"is",
"known",
"to",
"be",
"greater",
"than",
"or",
"equal",
"to",
"other",
"."
] | def __ge__(self, other):
"""Returns True if `self` is known to be greater than or equal to
`other`.
Dimensions are compared as follows:
```python
(tf.Dimension(m) >= tf.Dimension(n)) == (m >= n)
(tf.Dimension(m) >= tf.Dimension(None)) == None
(tf.Dimension(None) >= tf.Dimension(n)) == None
(tf.Dimension(None) >= tf.Dimension(None)) == None
```
Args:
other: Another Dimension.
Returns:
The value of `self.value >= other.value` if both are known, otherwise
None.
"""
other = as_dimension(other)
if self._value is None or other.value is None:
return None
else:
return self._value >= other.value | [
"def",
"__ge__",
"(",
"self",
",",
"other",
")",
":",
"other",
"=",
"as_dimension",
"(",
"other",
")",
"if",
"self",
".",
"_value",
"is",
"None",
"or",
"other",
".",
"value",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"self",
".",
... | https://github.com/tensorflow/tensorboard/blob/61d11d99ef034c30ba20b6a7840c8eededb9031c/tensorboard/compat/tensorflow_stub/tensor_shape.py#L441-L465 | ||
Tencent/QT4i | 75f8705c194505b483c6b7464da8522cd53ba679 | qt4i/driver/util/_task.py | python | Task.execute3 | (self) | return out, err, returncode | 执行命令
@return: (stdout<StringIO>, stderr<StringIO>, returncode<int>) | 执行命令 | [
"执行命令"
] | def execute3(self):
'''执行命令
@return: (stdout<StringIO>, stderr<StringIO>, returncode<int>)
'''
out, err = StringIO(), StringIO()
returncode = self.__execute__(out, err)[-1]
return out, err, returncode | [
"def",
"execute3",
"(",
"self",
")",
":",
"out",
",",
"err",
"=",
"StringIO",
"(",
")",
",",
"StringIO",
"(",
")",
"returncode",
"=",
"self",
".",
"__execute__",
"(",
"out",
",",
"err",
")",
"[",
"-",
"1",
"]",
"return",
"out",
",",
"err",
",",
... | https://github.com/Tencent/QT4i/blob/75f8705c194505b483c6b7464da8522cd53ba679/qt4i/driver/util/_task.py#L88-L94 | |
tobspr/RenderPipeline | d8c38c0406a63298f4801782a8e44e9c1e467acf | rpcore/common_resources.py | python | CommonResources.update | (self) | Updates the commonly used resources, mostly the shader inputs | Updates the commonly used resources, mostly the shader inputs | [
"Updates",
"the",
"commonly",
"used",
"resources",
"mostly",
"the",
"shader",
"inputs"
] | def update(self):
""" Updates the commonly used resources, mostly the shader inputs """
update = self._input_ubo.update_input
# Get the current transform matrix of the camera
view_mat = Globals.render.get_transform(self._showbase.cam).get_mat()
# Compute the view matrix, but with a z-up coordinate system
zup_conversion = Mat4.convert_mat(CS_zup_right, CS_yup_right)
update("view_mat_z_up", view_mat * zup_conversion)
# Compute the view matrix without the camera rotation
view_mat_billboard = Mat4(view_mat)
view_mat_billboard.set_row(0, Vec3(1, 0, 0))
view_mat_billboard.set_row(1, Vec3(0, 1, 0))
view_mat_billboard.set_row(2, Vec3(0, 0, 1))
update("view_mat_billboard", view_mat_billboard)
update("camera_pos", self._showbase.camera.get_pos(Globals.render))
# Compute last view projection mat
curr_vp = self._input_ubo.get_input("view_proj_mat_no_jitter")
update("last_view_proj_mat_no_jitter", curr_vp)
curr_vp = Mat4(curr_vp)
curr_vp.invert_in_place()
curr_inv_vp = curr_vp
update("last_inv_view_proj_mat_no_jitter", curr_inv_vp)
proj_mat = Mat4(self._showbase.camLens.get_projection_mat())
# Set the projection matrix as an input, but convert it to the correct
# coordinate system before.
proj_mat_zup = Mat4.convert_mat(CS_yup_right, CS_zup_right) * proj_mat
update("proj_mat", proj_mat_zup)
# Set the inverse projection matrix
update("inv_proj_mat", invert(proj_mat_zup))
# Remove jitter and set the new view projection mat
proj_mat.set_cell(1, 0, 0.0)
proj_mat.set_cell(1, 1, 0.0)
update("view_proj_mat_no_jitter", view_mat * proj_mat)
# Store the frame delta
update("frame_delta", Globals.clock.get_dt())
update("smooth_frame_delta", 1.0 / max(1e-5, Globals.clock.get_average_frame_rate()))
update("frame_time", Globals.clock.get_frame_time())
# Store the current film offset, we use this to compute the pixel-perfect
# velocity, which is otherwise not possible. Usually this is always 0
# except when SMAA and reprojection is enabled
update("current_film_offset", self._showbase.camLens.get_film_offset())
update("frame_index", Globals.clock.get_frame_count())
# Compute frustum corners in the order BL, BR, TL, TR
ws_frustum_directions = Mat4()
vs_frustum_directions = Mat4()
inv_proj_mat = Globals.base.camLens.get_projection_mat_inv()
view_mat_inv = Mat4(view_mat)
view_mat_inv.invert_in_place()
for i, point in enumerate(((-1, -1), (1, -1), (-1, 1), (1, 1))):
result = inv_proj_mat.xform(Vec4(point[0], point[1], 1.0, 1.0))
vs_dir = (zup_conversion.xform(result)).xyz.normalized()
vs_frustum_directions.set_row(i, Vec4(vs_dir, 1))
ws_dir = view_mat_inv.xform(Vec4(result.xyz, 0))
ws_frustum_directions.set_row(i, ws_dir)
update("vs_frustum_directions", vs_frustum_directions)
update("ws_frustum_directions", ws_frustum_directions)
update("screen_size", Globals.resolution)
update("native_screen_size", Globals.native_resolution)
update("lc_tile_count", self._pipeline.light_mgr.num_tiles) | [
"def",
"update",
"(",
"self",
")",
":",
"update",
"=",
"self",
".",
"_input_ubo",
".",
"update_input",
"# Get the current transform matrix of the camera",
"view_mat",
"=",
"Globals",
".",
"render",
".",
"get_transform",
"(",
"self",
".",
"_showbase",
".",
"cam",
... | https://github.com/tobspr/RenderPipeline/blob/d8c38c0406a63298f4801782a8e44e9c1e467acf/rpcore/common_resources.py#L173-L246 | ||
spesmilo/electrum | bdbd59300fbd35b01605e66145458e5f396108e8 | electrum/wallet.py | python | Wallet.wallet_class | (wallet_type) | [] | def wallet_class(wallet_type):
if multisig_type(wallet_type):
return Multisig_Wallet
if wallet_type in wallet_constructors:
return wallet_constructors[wallet_type]
raise WalletFileException("Unknown wallet type: " + str(wallet_type)) | [
"def",
"wallet_class",
"(",
"wallet_type",
")",
":",
"if",
"multisig_type",
"(",
"wallet_type",
")",
":",
"return",
"Multisig_Wallet",
"if",
"wallet_type",
"in",
"wallet_constructors",
":",
"return",
"wallet_constructors",
"[",
"wallet_type",
"]",
"raise",
"WalletFi... | https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/wallet.py#L3269-L3274 | ||||
mesonbuild/meson | a22d0f9a0a787df70ce79b05d0c45de90a970048 | mesonbuild/scripts/tags.py | python | ls_as_bytestream | () | return '\n'.join(files).encode() | [] | def ls_as_bytestream() -> bytes:
if os.path.exists('.git'):
return subprocess.run(['git', 'ls-tree', '-r', '--name-only', 'HEAD'],
stdout=subprocess.PIPE).stdout
files = [str(p) for p in Path('.').glob('**/*')
if not p.is_dir() and
not next((x for x in p.parts if x.startswith('.')), None)]
return '\n'.join(files).encode() | [
"def",
"ls_as_bytestream",
"(",
")",
"->",
"bytes",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'.git'",
")",
":",
"return",
"subprocess",
".",
"run",
"(",
"[",
"'git'",
",",
"'ls-tree'",
",",
"'-r'",
",",
"'--name-only'",
",",
"'HEAD'",
"]",
... | https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/scripts/tags.py#L20-L28 | |||
anitagraser/movingpandas | b171436f8e868f40e7a6dc611167f4de7dd66b10 | movingpandas/trajectory_collection.py | python | TrajectoryCollection.hvplot | (self, *args, **kwargs) | return _TrajectoryCollectionPlotter(self, *args, **kwargs).hvplot() | Generate an interactive plot.
Parameters
----------
args :
These parameters will be passed to the TrajectoryPlotter
kwargs :
These parameters will be passed to the TrajectoryPlotter
Examples
--------
Plot speed along trajectories (with legend and specified figure size):
>>> collection.hvplot(c='speed', line_width=7.0, width=700, height=400,
colorbar=True) | Generate an interactive plot. | [
"Generate",
"an",
"interactive",
"plot",
"."
] | def hvplot(self, *args, **kwargs):
"""
Generate an interactive plot.
Parameters
----------
args :
These parameters will be passed to the TrajectoryPlotter
kwargs :
These parameters will be passed to the TrajectoryPlotter
Examples
--------
Plot speed along trajectories (with legend and specified figure size):
>>> collection.hvplot(c='speed', line_width=7.0, width=700, height=400,
colorbar=True)
"""
return _TrajectoryCollectionPlotter(self, *args, **kwargs).hvplot() | [
"def",
"hvplot",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_TrajectoryCollectionPlotter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"hvplot",
"(",
")"
] | https://github.com/anitagraser/movingpandas/blob/b171436f8e868f40e7a6dc611167f4de7dd66b10/movingpandas/trajectory_collection.py#L426-L444 | |
fuzzbunch/fuzzbunch | 4b60a6c7cf9f84cf389d3fcdb9281de84ffb5802 | fuzzbunch/coli.py | python | CommandlineWrapper.__call__ | (self, argv) | Effectively "main" from Commandlinewrapper | Effectively "main" from Commandlinewrapper | [
"Effectively",
"main",
"from",
"Commandlinewrapper"
] | def __call__(self, argv):
"""Effectively "main" from Commandlinewrapper"""
logConfig = None
context = {}
rendezvous = None
try:
(opts, args) = self.__coli_parser.parse_args(argv)
if opts.InConfig is None:
raise ExploitConfigError("You must pass a valid --InConfig option")
# Read the input config and create a truanchild Config object
self.config = truantchild.Config([opts.InConfig])
# make sure the id from the binary matches the config
if self.getID() != self.config.id:
print "Mismatching configurations!!"
return 1
# XXX Add the bit about help, line 215
inputs = self.config._inputParams
outputs= self.config._outputParams
constants = None # Fuzzbunch doesn't support these yet
#pytrch.Params_parseCommandLine( inputs.parameters, len(sys.argv), sys.argv, doHelp)
# Convert the options from Truanchild to easy-to-handle input for the plugin
iOptions = self.tc2List( inputs )
oOptions = self.tc2Dict( outputs )
# add the params from the wrapper
valid = self.validateParams(iOptions)
# XXX Print the invalid options
if opts.ValidateOnly is True:
return 0
(fhNo, logConfig) = self.processWrapperParams( opts )
# Setup all of the existing sockets
self.doRendezvousClient(inputs)
retval = self.processParams(iOptions, constants, oOptions, context, logConfig)
try:
self.options2Tc( oOptions, outputs )
except Exception as e:
# If this fails, the plugin was not successful
print str(oOptions)
print "Failed: {0}".format(e)
return 1
# Add the output parameter for the rendezvous
(rendezvous, sock) = self.addWrapperOutputParams( outputs, self.config.namespaceUri, self.config.schemaVersion )
exma.writeParamsToEM( fhNo, self.config.getMarshalledInConfig() )
# This sends us into a send/recv loop
self.doRendezvousServer( rendezvous, sock )
self.cleanup( EDF_CLEANUP_WAIT, context, logConfig )
except Exception as e:
print "Failed: {0}".format(e)
raise | [
"def",
"__call__",
"(",
"self",
",",
"argv",
")",
":",
"logConfig",
"=",
"None",
"context",
"=",
"{",
"}",
"rendezvous",
"=",
"None",
"try",
":",
"(",
"opts",
",",
"args",
")",
"=",
"self",
".",
"__coli_parser",
".",
"parse_args",
"(",
"argv",
")",
... | https://github.com/fuzzbunch/fuzzbunch/blob/4b60a6c7cf9f84cf389d3fcdb9281de84ffb5802/fuzzbunch/coli.py#L57-L117 | ||
sosreport/sos | 900e8bea7f3cd36c1dd48f3cbb351ab92f766654 | sos/archive.py | python | Archive.cleanup | (self) | Clean up any temporary resources used by an Archive class. | Clean up any temporary resources used by an Archive class. | [
"Clean",
"up",
"any",
"temporary",
"resources",
"used",
"by",
"an",
"Archive",
"class",
"."
] | def cleanup(self):
"""Clean up any temporary resources used by an Archive class."""
pass | [
"def",
"cleanup",
"(",
"self",
")",
":",
"pass"
] | https://github.com/sosreport/sos/blob/900e8bea7f3cd36c1dd48f3cbb351ab92f766654/sos/archive.py#L114-L116 | ||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3db/cr.py | python | CRShelterInspection.inject_js | (widget_id, options) | Helper function to inject static JS and instantiate
the shelterInspection widget
Args:
widget_id: the node ID where to instantiate the widget
options: dict of widget options (JSON-serializable) | Helper function to inject static JS and instantiate
the shelterInspection widget | [
"Helper",
"function",
"to",
"inject",
"static",
"JS",
"and",
"instantiate",
"the",
"shelterInspection",
"widget"
] | def inject_js(widget_id, options):
"""
Helper function to inject static JS and instantiate
the shelterInspection widget
Args:
widget_id: the node ID where to instantiate the widget
options: dict of widget options (JSON-serializable)
"""
s3 = current.response.s3
appname = current.request.application
# Static JS
scripts = s3.scripts
if s3.debug:
script = "/%s/static/scripts/S3/s3.shelter_inspection.js" % appname
else:
script = "/%s/static/scripts/S3/s3.shelter_inspection.min.js" % appname
scripts.append(script)
# Instantiate widget
scripts = s3.jquery_ready
script = '''$('#%(id)s').shelterInspection(%(options)s)''' % \
{"id": widget_id, "options": json.dumps(options)}
if script not in scripts:
scripts.append(script) | [
"def",
"inject_js",
"(",
"widget_id",
",",
"options",
")",
":",
"s3",
"=",
"current",
".",
"response",
".",
"s3",
"appname",
"=",
"current",
".",
"request",
".",
"application",
"# Static JS",
"scripts",
"=",
"s3",
".",
"scripts",
"if",
"s3",
".",
"debug"... | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3db/cr.py#L3039-L3065 | ||
Hiroshiba/realtime-yukarin | a8cd36b180c93d7251327b3ca4a027d2a9f0c868 | realtime_voice_conversion/stream/base_stream.py | python | BaseStream.__init__ | (
self,
in_segment_method: BaseSegmentMethod[T_IN],
out_segment_method: BaseSegmentMethod[T_OUT],
) | [] | def __init__(
self,
in_segment_method: BaseSegmentMethod[T_IN],
out_segment_method: BaseSegmentMethod[T_OUT],
):
self.in_segment_method = in_segment_method
self.out_segment_method = out_segment_method
self.stream: List[Segment[T_IN]] = [] | [
"def",
"__init__",
"(",
"self",
",",
"in_segment_method",
":",
"BaseSegmentMethod",
"[",
"T_IN",
"]",
",",
"out_segment_method",
":",
"BaseSegmentMethod",
"[",
"T_OUT",
"]",
",",
")",
":",
"self",
".",
"in_segment_method",
"=",
"in_segment_method",
"self",
".",
... | https://github.com/Hiroshiba/realtime-yukarin/blob/a8cd36b180c93d7251327b3ca4a027d2a9f0c868/realtime_voice_conversion/stream/base_stream.py#L11-L19 | ||||
suurjaak/Skyperious | 6a4f264dbac8d326c2fa8aeb5483dbca987860bf | skyperious/lib/controls.py | python | ColourManager.Adjust | (cls, colour1, colour2, ratio=0.5) | return wx.Colour(result) | Returns first colour adjusted towards second.
Arguments can be wx.Colour, RGB tuple, colour hex string,
or wx.SystemSettings colour index.
@param ratio RGB channel adjustment ratio towards second colour | Returns first colour adjusted towards second.
Arguments can be wx.Colour, RGB tuple, colour hex string,
or wx.SystemSettings colour index. | [
"Returns",
"first",
"colour",
"adjusted",
"towards",
"second",
".",
"Arguments",
"can",
"be",
"wx",
".",
"Colour",
"RGB",
"tuple",
"colour",
"hex",
"string",
"or",
"wx",
".",
"SystemSettings",
"colour",
"index",
"."
] | def Adjust(cls, colour1, colour2, ratio=0.5):
"""
Returns first colour adjusted towards second.
Arguments can be wx.Colour, RGB tuple, colour hex string,
or wx.SystemSettings colour index.
@param ratio RGB channel adjustment ratio towards second colour
"""
colour1 = wx.SystemSettings.GetColour(colour1) \
if isinstance(colour1, (int, long)) else wx.Colour(colour1)
colour2 = wx.SystemSettings.GetColour(colour2) \
if isinstance(colour2, (int, long)) else wx.Colour(colour2)
rgb1, rgb2 = tuple(colour1)[:3], tuple(colour2)[:3]
delta = tuple(a - b for a, b in zip(rgb1, rgb2))
result = tuple(a - (d * ratio) for a, d in zip(rgb1, delta))
result = tuple(min(255, max(0, x)) for x in result)
return wx.Colour(result) | [
"def",
"Adjust",
"(",
"cls",
",",
"colour1",
",",
"colour2",
",",
"ratio",
"=",
"0.5",
")",
":",
"colour1",
"=",
"wx",
".",
"SystemSettings",
".",
"GetColour",
"(",
"colour1",
")",
"if",
"isinstance",
"(",
"colour1",
",",
"(",
"int",
",",
"long",
")"... | https://github.com/suurjaak/Skyperious/blob/6a4f264dbac8d326c2fa8aeb5483dbca987860bf/skyperious/lib/controls.py#L312-L328 | |
bids-standard/pybids | 9449fdc319c4bdff4ed9aa1b299964352f394d56 | bids/layout/layout.py | python | BIDSLayout.get_nearest | (self, path, return_type='filename', strict=True,
all_=False, ignore_strict_entities='extension',
full_search=False, **filters) | return matches if all_ else matches[0] if matches else None | Walk up file tree from specified path and return nearest matching file(s).
Parameters
----------
path (str): The file to search from.
return_type (str): What to return; must be one of 'filename'
(default) or 'tuple'.
strict (bool): When True, all entities present in both the input
path and the target file(s) must match perfectly. When False,
files will be ordered by the number of matching entities, and
partial matches will be allowed.
all_ (bool): When True, returns all matching files. When False
(default), only returns the first match.
ignore_strict_entities (str, list): Optional entity/entities to
exclude from strict matching when strict is True. This allows
one to search, e.g., for files of a different type while
matching all other entities perfectly by passing
ignore_strict_entities=['type']. Ignores extension by default.
full_search (bool): If True, searches all indexed files, even if
they don't share a common root with the provided path. If
False, only files that share a common root will be scanned.
filters : dict
Optional keywords to pass on to :obj:`bids.layout.BIDSLayout.get`. | Walk up file tree from specified path and return nearest matching file(s). | [
"Walk",
"up",
"file",
"tree",
"from",
"specified",
"path",
"and",
"return",
"nearest",
"matching",
"file",
"(",
"s",
")",
"."
] | def get_nearest(self, path, return_type='filename', strict=True,
all_=False, ignore_strict_entities='extension',
full_search=False, **filters):
"""Walk up file tree from specified path and return nearest matching file(s).
Parameters
----------
path (str): The file to search from.
return_type (str): What to return; must be one of 'filename'
(default) or 'tuple'.
strict (bool): When True, all entities present in both the input
path and the target file(s) must match perfectly. When False,
files will be ordered by the number of matching entities, and
partial matches will be allowed.
all_ (bool): When True, returns all matching files. When False
(default), only returns the first match.
ignore_strict_entities (str, list): Optional entity/entities to
exclude from strict matching when strict is True. This allows
one to search, e.g., for files of a different type while
matching all other entities perfectly by passing
ignore_strict_entities=['type']. Ignores extension by default.
full_search (bool): If True, searches all indexed files, even if
they don't share a common root with the provided path. If
False, only files that share a common root will be scanned.
filters : dict
Optional keywords to pass on to :obj:`bids.layout.BIDSLayout.get`.
"""
path = Path(path).absolute()
# Make sure we have a valid suffix
if not filters.get('suffix'):
f = self.get_file(path)
if 'suffix' not in f.entities:
raise BIDSValidationError(
"File '%s' does not have a valid suffix, most "
"likely because it is not a valid BIDS file." % path
)
filters['suffix'] = f.entities['suffix']
# Collect matches for all entities
entities = {}
for ent in self.get_entities(metadata=False).values():
m = ent.regex.search(str(path))
if m:
entities[ent.name] = ent._astype(m.group(1))
# Remove any entities we want to ignore when strict matching is on
if strict and ignore_strict_entities is not None:
for k in listify(ignore_strict_entities):
entities.pop(k, None)
# Get candidate files
results = self.get(**filters)
# Make a dictionary of directories --> contained files
folders = defaultdict(list)
for f in results:
folders[f._dirname].append(f)
# Build list of candidate directories to check
search_paths = []
while True:
if path in folders and folders[path]:
search_paths.append(path)
parent = path.parent
if parent == path:
break
path = parent
if full_search:
unchecked = set(folders.keys()) - set(search_paths)
search_paths.extend(path for path in unchecked if folders[path])
def count_matches(f):
# Count the number of entities shared with the passed file
f_ents = f.entities
keys = set(entities.keys()) & set(f_ents.keys())
shared = len(keys)
return [shared, sum([entities[k] == f_ents[k] for k in keys])]
matches = []
for path in search_paths:
# Sort by number of matching entities. Also store number of
# common entities, for filtering when strict=True.
num_ents = [[f] + count_matches(f) for f in folders[path]]
# Filter out imperfect matches (i.e., where number of common
# entities does not equal number of matching entities).
if strict:
num_ents = [f for f in num_ents if f[1] == f[2]]
num_ents.sort(key=lambda x: x[2], reverse=True)
if num_ents:
for f_match in num_ents:
matches.append(f_match[0])
if not all_:
break
matches = [match.path if return_type.startswith('file')
else match for match in matches]
return matches if all_ else matches[0] if matches else None | [
"def",
"get_nearest",
"(",
"self",
",",
"path",
",",
"return_type",
"=",
"'filename'",
",",
"strict",
"=",
"True",
",",
"all_",
"=",
"False",
",",
"ignore_strict_entities",
"=",
"'extension'",
",",
"full_search",
"=",
"False",
",",
"*",
"*",
"filters",
")"... | https://github.com/bids-standard/pybids/blob/9449fdc319c4bdff4ed9aa1b299964352f394d56/bids/layout/layout.py#L910-L1011 | |
khanhnamle1994/natural-language-processing | 01d450d5ac002b0156ef4cf93a07cb508c1bcdc5 | assignment1/.env/lib/python2.7/site-packages/zmq/eventloop/minitornado/ioloop.py | python | IOLoop.add_timeout | (self, deadline, callback) | Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current time.
Note that it is not safe to call `add_timeout` from other threads.
Instead, you must use `add_callback` to transfer control to the
`IOLoop`'s thread, and then call `add_timeout` from there. | Runs the ``callback`` at the time ``deadline`` from the I/O loop. | [
"Runs",
"the",
"callback",
"at",
"the",
"time",
"deadline",
"from",
"the",
"I",
"/",
"O",
"loop",
"."
] | def add_timeout(self, deadline, callback):
"""Runs the ``callback`` at the time ``deadline`` from the I/O loop.
Returns an opaque handle that may be passed to
`remove_timeout` to cancel.
``deadline`` may be a number denoting a time (on the same
scale as `IOLoop.time`, normally `time.time`), or a
`datetime.timedelta` object for a deadline relative to the
current time.
Note that it is not safe to call `add_timeout` from other threads.
Instead, you must use `add_callback` to transfer control to the
`IOLoop`'s thread, and then call `add_timeout` from there.
"""
raise NotImplementedError() | [
"def",
"add_timeout",
"(",
"self",
",",
"deadline",
",",
"callback",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/zmq/eventloop/minitornado/ioloop.py#L392-L407 | ||
anki/cozmo-python-sdk | dd29edef18748fcd816550469195323842a7872e | src/cozmo/objects.py | python | FixedCustomObject.object_id | (self) | return self._object_id | int: The internal ID assigned to the object.
This value can only be assigned once as it is static in the engine. | int: The internal ID assigned to the object. | [
"int",
":",
"The",
"internal",
"ID",
"assigned",
"to",
"the",
"object",
"."
] | def object_id(self):
'''int: The internal ID assigned to the object.
This value can only be assigned once as it is static in the engine.
'''
return self._object_id | [
"def",
"object_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_object_id"
] | https://github.com/anki/cozmo-python-sdk/blob/dd29edef18748fcd816550469195323842a7872e/src/cozmo/objects.py#L902-L907 | |
bbfamily/abu | 2de85ae57923a720dac99a545b4f856f6b87304b | abupy/FactorSellBu/ABuFactorSellBreak.py | python | AbuFactorSellBreak.support_direction | (self) | return [ESupportDirection.DIRECTION_CAll.value] | 支持的方向,只支持正向 | 支持的方向,只支持正向 | [
"支持的方向,只支持正向"
] | def support_direction(self):
"""支持的方向,只支持正向"""
return [ESupportDirection.DIRECTION_CAll.value] | [
"def",
"support_direction",
"(",
"self",
")",
":",
"return",
"[",
"ESupportDirection",
".",
"DIRECTION_CAll",
".",
"value",
"]"
] | https://github.com/bbfamily/abu/blob/2de85ae57923a720dac99a545b4f856f6b87304b/abupy/FactorSellBu/ABuFactorSellBreak.py#L27-L29 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/plat-unixware7/IN.py | python | IN6_SET_ADDR_ANY | (a) | return IN6_ADDR_COPY_L(a, 0, 0, 0, 0) | [] | def IN6_SET_ADDR_ANY(a): return IN6_ADDR_COPY_L(a, 0, 0, 0, 0) | [
"def",
"IN6_SET_ADDR_ANY",
"(",
"a",
")",
":",
"return",
"IN6_ADDR_COPY_L",
"(",
"a",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-unixware7/IN.py#L77-L77 | |||
brendano/tweetmotif | 1b0b1e3a941745cd5a26eba01f554688b7c4b27e | everything_else/djfrontend/django-1.0.2/contrib/gis/gdal/libgdal.py | python | gdal_version | () | return _version_info('RELEASE_NAME') | Returns only the GDAL version number information. | Returns only the GDAL version number information. | [
"Returns",
"only",
"the",
"GDAL",
"version",
"number",
"information",
"."
] | def gdal_version():
"Returns only the GDAL version number information."
return _version_info('RELEASE_NAME') | [
"def",
"gdal_version",
"(",
")",
":",
"return",
"_version_info",
"(",
"'RELEASE_NAME'",
")"
] | https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/contrib/gis/gdal/libgdal.py#L64-L66 | |
steeve/xbmctorrent | e6bcb1037668959e1e3cb5ba8cf3e379c6638da9 | resources/site-packages/bs4/dammit.py | python | UnicodeDammit.detwingle | (cls, in_bytes, main_encoding="utf8",
embedded_encoding="windows-1252") | return b''.join(byte_chunks) | Fix characters from one encoding embedded in some other encoding.
Currently the only situation supported is Windows-1252 (or its
subset ISO-8859-1), embedded in UTF-8.
The input must be a bytestring. If you've already converted
the document to Unicode, you're too late.
The output is a bytestring in which `embedded_encoding`
characters have been converted to their `main_encoding`
equivalents. | Fix characters from one encoding embedded in some other encoding. | [
"Fix",
"characters",
"from",
"one",
"encoding",
"embedded",
"in",
"some",
"other",
"encoding",
"."
] | def detwingle(cls, in_bytes, main_encoding="utf8",
embedded_encoding="windows-1252"):
"""Fix characters from one encoding embedded in some other encoding.
Currently the only situation supported is Windows-1252 (or its
subset ISO-8859-1), embedded in UTF-8.
The input must be a bytestring. If you've already converted
the document to Unicode, you're too late.
The output is a bytestring in which `embedded_encoding`
characters have been converted to their `main_encoding`
equivalents.
"""
if embedded_encoding.replace('_', '-').lower() not in (
'windows-1252', 'windows_1252'):
raise NotImplementedError(
"Windows-1252 and ISO-8859-1 are the only currently supported "
"embedded encodings.")
if main_encoding.lower() not in ('utf8', 'utf-8'):
raise NotImplementedError(
"UTF-8 is the only currently supported main encoding.")
byte_chunks = []
chunk_start = 0
pos = 0
while pos < len(in_bytes):
byte = in_bytes[pos]
if not isinstance(byte, int):
# Python 2.x
byte = ord(byte)
if (byte >= cls.FIRST_MULTIBYTE_MARKER
and byte <= cls.LAST_MULTIBYTE_MARKER):
# This is the start of a UTF-8 multibyte character. Skip
# to the end.
for start, end, size in cls.MULTIBYTE_MARKERS_AND_SIZES:
if byte >= start and byte <= end:
pos += size
break
elif byte >= 0x80 and byte in cls.WINDOWS_1252_TO_UTF8:
# We found a Windows-1252 character!
# Save the string up to this point as a chunk.
byte_chunks.append(in_bytes[chunk_start:pos])
# Now translate the Windows-1252 character into UTF-8
# and add it as another, one-byte chunk.
byte_chunks.append(cls.WINDOWS_1252_TO_UTF8[byte])
pos += 1
chunk_start = pos
else:
# Go on to the next character.
pos += 1
if chunk_start == 0:
# The string is unchanged.
return in_bytes
else:
# Store the final chunk.
byte_chunks.append(in_bytes[chunk_start:])
return b''.join(byte_chunks) | [
"def",
"detwingle",
"(",
"cls",
",",
"in_bytes",
",",
"main_encoding",
"=",
"\"utf8\"",
",",
"embedded_encoding",
"=",
"\"windows-1252\"",
")",
":",
"if",
"embedded_encoding",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
".",
"lower",
"(",
")",
"not",
"in"... | https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/bs4/dammit.py#L765-L825 | |
IntelAI/nauta | bbedb114a755cf1f43b834a58fc15fb6e3a4b291 | applications/cli/example-python/package_examples/mnist_converter_pb.py | python | do_conversion | (work_dir, num_tests) | Converts requested number of examples from mnist test set to proto buffer format. Results are saved in a
conversion_out subdir of workdir.
Args:
work_dir: The full path of working directory for test data set.
num_tests: Number of test images to convert.
Raises:
IOError: An error occurred processing test data set. | Converts requested number of examples from mnist test set to proto buffer format. Results are saved in a
conversion_out subdir of workdir. | [
"Converts",
"requested",
"number",
"of",
"examples",
"from",
"mnist",
"test",
"set",
"to",
"proto",
"buffer",
"format",
".",
"Results",
"are",
"saved",
"in",
"a",
"conversion_out",
"subdir",
"of",
"workdir",
"."
] | def do_conversion(work_dir, num_tests):
"""
Converts requested number of examples from mnist test set to proto buffer format. Results are saved in a
conversion_out subdir of workdir.
Args:
work_dir: The full path of working directory for test data set.
num_tests: Number of test images to convert.
Raises:
IOError: An error occurred processing test data set.
"""
conversion_out_path = os.path.join(work_dir, "conversion_out")
os.makedirs(conversion_out_path, exist_ok=True)
test_data_set = tf.contrib.learn.datasets.mnist.read_data_sets(work_dir).test
expected_labels = []
for i in range(num_tests):
request = predict_pb2.PredictRequest()
request.model_spec.name = MODEL_NAME
request.model_spec.signature_name = MODEL_SIGNATURE_NAME
image, label = test_data_set.next_batch(1)
request.inputs[MODEL_INPUT_NAME].CopyFrom(
tf.contrib.util.make_tensor_proto(image[0], shape=[1, image[0].size])
)
ser = request.SerializeToString()
expected_labels.append(label)
with open(os.path.join(conversion_out_path, "{}.pb".format(i)), mode='wb') as file:
file.write(ser)
print(i)
expected_labels = np.array(expected_labels)
np.save(os.path.join(work_dir, "labels"), expected_labels) | [
"def",
"do_conversion",
"(",
"work_dir",
",",
"num_tests",
")",
":",
"conversion_out_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"conversion_out\"",
")",
"os",
".",
"makedirs",
"(",
"conversion_out_path",
",",
"exist_ok",
"=",
"True",
... | https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/cli/example-python/package_examples/mnist_converter_pb.py#L39-L73 | ||
ZhaoJ9014/face.evoLVe | 63520924167efb9ef53dcceed0a15cf739cad1c9 | backbone/EfficientNets.py | python | round_repeats | (repeats, global_params) | return int(math.ceil(multiplier * repeats)) | Calculate module's repeat number of a block based on depth multiplier.
Use depth_coefficient of global_params.
Args:
repeats (int): num_repeat to be calculated.
global_params (namedtuple): Global params of the model.
Returns:
new repeat: New repeat number after calculating. | Calculate module's repeat number of a block based on depth multiplier.
Use depth_coefficient of global_params. | [
"Calculate",
"module",
"s",
"repeat",
"number",
"of",
"a",
"block",
"based",
"on",
"depth",
"multiplier",
".",
"Use",
"depth_coefficient",
"of",
"global_params",
"."
] | def round_repeats(repeats, global_params):
"""Calculate module's repeat number of a block based on depth multiplier.
Use depth_coefficient of global_params.
Args:
repeats (int): num_repeat to be calculated.
global_params (namedtuple): Global params of the model.
Returns:
new repeat: New repeat number after calculating.
"""
multiplier = global_params.depth_coefficient
if not multiplier:
return repeats
# follow the formula transferred from official TensorFlow implementation
return int(math.ceil(multiplier * repeats)) | [
"def",
"round_repeats",
"(",
"repeats",
",",
"global_params",
")",
":",
"multiplier",
"=",
"global_params",
".",
"depth_coefficient",
"if",
"not",
"multiplier",
":",
"return",
"repeats",
"# follow the formula transferred from official TensorFlow implementation",
"return",
"... | https://github.com/ZhaoJ9014/face.evoLVe/blob/63520924167efb9ef53dcceed0a15cf739cad1c9/backbone/EfficientNets.py#L103-L118 | |
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/pie/marker/_line.py | python | Line.colorsrc | (self) | return self["colorsrc"] | Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str | Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object | [
"Sets",
"the",
"source",
"reference",
"on",
"Chart",
"Studio",
"Cloud",
"for",
"color",
".",
"The",
"colorsrc",
"property",
"must",
"be",
"specified",
"as",
"a",
"string",
"or",
"as",
"a",
"plotly",
".",
"grid_objs",
".",
"Column",
"object"
] | def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"] | [
"def",
"colorsrc",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"colorsrc\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/pie/marker/_line.py#L76-L87 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/knutson_tao_puzzles.py | python | DeltaPiece.__hash__ | (self) | return hash((DeltaPiece, self.border())) | r"""
TESTS::
sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece
sage: delta = DeltaPiece('a','b','c')
sage: hash(delta) == hash(delta)
True | r"""
TESTS:: | [
"r",
"TESTS",
"::"
] | def __hash__(self):
r"""
TESTS::
sage: from sage.combinat.knutson_tao_puzzles import DeltaPiece
sage: delta = DeltaPiece('a','b','c')
sage: hash(delta) == hash(delta)
True
"""
return hash((DeltaPiece, self.border())) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"(",
"DeltaPiece",
",",
"self",
".",
"border",
"(",
")",
")",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/knutson_tao_puzzles.py#L403-L412 | |
Theano/Theano | 8fd9203edfeecebced9344b0c70193be292a9ade | theano/gof/type.py | python | CLinkerType.c_extract_out | (self, name, sub, check_input=True) | return """
if (py_%(name)s == Py_None)
{
%(c_init_code)s
}
else
{
%(c_extract_code)s
}
""" % dict(
name=name,
c_init_code=self.c_init(name, sub),
c_extract_code=self.c_extract(name, sub, check_input)) | Optional: C code to extract a PyObject * instance.
Unlike c_extract, c_extract_out has to accept Py_None,
meaning that the variable should be left uninitialized. | Optional: C code to extract a PyObject * instance. | [
"Optional",
":",
"C",
"code",
"to",
"extract",
"a",
"PyObject",
"*",
"instance",
"."
] | def c_extract_out(self, name, sub, check_input=True):
"""
Optional: C code to extract a PyObject * instance.
Unlike c_extract, c_extract_out has to accept Py_None,
meaning that the variable should be left uninitialized.
"""
return """
if (py_%(name)s == Py_None)
{
%(c_init_code)s
}
else
{
%(c_extract_code)s
}
""" % dict(
name=name,
c_init_code=self.c_init(name, sub),
c_extract_code=self.c_extract(name, sub, check_input)) | [
"def",
"c_extract_out",
"(",
"self",
",",
"name",
",",
"sub",
",",
"check_input",
"=",
"True",
")",
":",
"return",
"\"\"\"\n if (py_%(name)s == Py_None)\n {\n %(c_init_code)s\n }\n else\n {\n %(c_extract_code)s\n }\n ... | https://github.com/Theano/Theano/blob/8fd9203edfeecebced9344b0c70193be292a9ade/theano/gof/type.py#L188-L208 | |
phonopy/phonopy | 816586d0ba8177482ecf40e52f20cbdee2260d51 | phonopy/cui/settings.py | python | PhonopySettings.set_is_legacy_plot | (self, val) | Set is_legacy_plot. | Set is_legacy_plot. | [
"Set",
"is_legacy_plot",
"."
] | def set_is_legacy_plot(self, val):
"""Set is_legacy_plot."""
self._v["is_legacy_plot"] = val | [
"def",
"set_is_legacy_plot",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"_v",
"[",
"\"is_legacy_plot\"",
"]",
"=",
"val"
] | https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/cui/settings.py#L1304-L1306 | ||
Dvlv/Tkinter-By-Example | 30721f15f7bea41489a7c46819beb5282781e563 | Code/Chapter7-1.py | python | Timer.setup_worker | (self) | [] | def setup_worker(self):
now = datetime.datetime.now()
in_25_mins = now + datetime.timedelta(minutes=25)
#in_25_mins = now + datetime.timedelta(seconds=3)
worker = CountingThread(self, now, in_25_mins)
self.worker = worker | [
"def",
"setup_worker",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"in_25_mins",
"=",
"now",
"+",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"25",
")",
"#in_25_mins = now + datetime.timedelta(seconds=3)",
"work... | https://github.com/Dvlv/Tkinter-By-Example/blob/30721f15f7bea41489a7c46819beb5282781e563/Code/Chapter7-1.py#L76-L81 | ||||
deepinsight/insightface | c0b25f998a649f662c7136eb389abcacd7900e9d | detection/scrfd/mmdet/core/mask/structures.py | python | BaseInstanceMasks.expand | (self, expanded_h, expanded_w, top, left) | see :class:`Expand`. | see :class:`Expand`. | [
"see",
":",
"class",
":",
"Expand",
"."
] | def expand(self, expanded_h, expanded_w, top, left):
"""see :class:`Expand`."""
pass | [
"def",
"expand",
"(",
"self",
",",
"expanded_h",
",",
"expanded_w",
",",
"top",
",",
"left",
")",
":",
"pass"
] | https://github.com/deepinsight/insightface/blob/c0b25f998a649f662c7136eb389abcacd7900e9d/detection/scrfd/mmdet/core/mask/structures.py#L104-L106 | ||
jiangxinyang227/bert-for-task | 3e7aed9e3c757ebc22aabfd4f3fb7b4cd81b010a | albert_task/albert/optimization.py | python | LAMBOptimizer.apply_gradients | (self, grads_and_vars, global_step=None, name=None) | return tf.group(*assignments, name=name) | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""See base class."""
assignments = []
for (grad, param) in grads_and_vars:
if grad is None or param is None:
continue
param_name = self._get_variable_name(param.name)
m = tf.get_variable(
name=param_name + "/lamb_m",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
v = tf.get_variable(
name=param_name + "/lamb_v",
shape=param.shape.as_list(),
dtype=tf.float32,
trainable=False,
initializer=tf.zeros_initializer())
# Standard Adam update.
next_m = (
tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))
next_v = (
tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,
tf.square(grad)))
update = next_m / (tf.sqrt(next_v) + self.epsilon)
# Just adding the square of the weights to the loss function is *not*
# the correct way of using L2 regularization/weight decay with Adam,
# since that will interact with the m and v parameters in strange ways.
#
# Instead we want ot decay the weights in a manner that doesn't interact
# with the m/v parameters. This is equivalent to adding the square
# of the weights to the loss with plain (non-momentum) SGD.
if self._do_use_weight_decay(param_name):
update += self.weight_decay_rate * param
############## BELOW ARE THE SPECIFIC PARTS FOR LAMB ##############
# Note: Here are two choices for scaling function \phi(z)
# minmax: \phi(z) = min(max(z, \gamma_l), \gamma_u)
# identity: \phi(z) = z
# The authors does not mention what is \gamma_l and \gamma_u
# UPDATE: after asking authors, they provide me the code below.
# ratio = array_ops.where(math_ops.greater(w_norm, 0), array_ops.where(
# math_ops.greater(g_norm, 0), (w_norm / g_norm), 1.0), 1.0)
r1 = tf.sqrt(tf.reduce_sum(tf.square(param)))
r2 = tf.sqrt(tf.reduce_sum(tf.square(update)))
r = tf.where(tf.greater(r1, 0.0),
tf.where(tf.greater(r2, 0.0),
r1 / r2,
1.0),
1.0)
eta = self.learning_rate * r
update_with_lr = eta * update
next_param = param - update_with_lr
assignments.extend(
[param.assign(next_param),
m.assign(next_m),
v.assign(next_v)])
return tf.group(*assignments, name=name) | [
"def",
"apply_gradients",
"(",
"self",
",",
"grads_and_vars",
",",
"global_step",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"assignments",
"=",
"[",
"]",
"for",
"(",
"grad",
",",
"param",
")",
"in",
"grads_and_vars",
":",
"if",
"grad",
"is",
"No... | https://github.com/jiangxinyang227/bert-for-task/blob/3e7aed9e3c757ebc22aabfd4f3fb7b4cd81b010a/albert_task/albert/optimization.py#L213-L283 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_user.py | python | Yedit.separator | (self) | return self._separator | getter method for separator | getter method for separator | [
"getter",
"method",
"for",
"separator"
] | def separator(self):
''' getter method for separator '''
return self._separator | [
"def",
"separator",
"(",
"self",
")",
":",
"return",
"self",
".",
"_separator"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_user.py#L224-L226 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/pip/_internal/utils/outdated.py | python | was_installed_by_pip | (pkg) | Checks whether pkg was installed by pip
This is used not to display the upgrade message when pip is in fact
installed by system package manager, such as dnf on Fedora. | Checks whether pkg was installed by pip | [
"Checks",
"whether",
"pkg",
"was",
"installed",
"by",
"pip"
] | def was_installed_by_pip(pkg):
# type: (str) -> bool
"""Checks whether pkg was installed by pip
This is used not to display the upgrade message when pip is in fact
installed by system package manager, such as dnf on Fedora.
"""
try:
dist = pkg_resources.get_distribution(pkg)
return (dist.has_metadata('INSTALLER') and
'pip' in dist.get_metadata_lines('INSTALLER'))
except pkg_resources.DistributionNotFound:
return False | [
"def",
"was_installed_by_pip",
"(",
"pkg",
")",
":",
"# type: (str) -> bool",
"try",
":",
"dist",
"=",
"pkg_resources",
".",
"get_distribution",
"(",
"pkg",
")",
"return",
"(",
"dist",
".",
"has_metadata",
"(",
"'INSTALLER'",
")",
"and",
"'pip'",
"in",
"dist",... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_internal/utils/outdated.py#L79-L91 | ||
SolidCode/SolidPython | 4715c827ad90db26ee37df57bc425e6f2de3cf8d | solid/utils.py | python | _euc_obj | (an_obj: Any, intended_class:type=Vector3) | return result | Take a single object (not a list of them!) and return a euclid type
# If given a euclid obj, return the desired type,
# -- 3d types are projected to z=0 when intended_class is 2D
# -- 2D types are projected to z=0 when intended class is 3D
_euc_obj( Vector3(0,1,2), Vector3) -> Vector3(0,1,2)
_euc_obj( Vector3(0,1,2), Point3) -> Point3(0,1,2)
_euc_obj( Vector2(0,1), Vector3) -> Vector3(0,1,0)
_euc_obj( Vector2(0,1), Point3) -> Point3(0,1,0)
_euc_obj( (0,1), Vector3) -> Vector3(0,1,0)
_euc_obj( (0,1), Point3) -> Point3(0,1,0)
_euc_obj( (0,1), Point2) -> Point2(0,1,0)
_euc_obj( (0,1,2), Point2) -> Point2(0,1)
_euc_obj( (0,1,2), Point3) -> Point3(0,1,2) | Take a single object (not a list of them!) and return a euclid type
# If given a euclid obj, return the desired type,
# -- 3d types are projected to z=0 when intended_class is 2D
# -- 2D types are projected to z=0 when intended class is 3D
_euc_obj( Vector3(0,1,2), Vector3) -> Vector3(0,1,2)
_euc_obj( Vector3(0,1,2), Point3) -> Point3(0,1,2)
_euc_obj( Vector2(0,1), Vector3) -> Vector3(0,1,0)
_euc_obj( Vector2(0,1), Point3) -> Point3(0,1,0)
_euc_obj( (0,1), Vector3) -> Vector3(0,1,0)
_euc_obj( (0,1), Point3) -> Point3(0,1,0)
_euc_obj( (0,1), Point2) -> Point2(0,1,0)
_euc_obj( (0,1,2), Point2) -> Point2(0,1)
_euc_obj( (0,1,2), Point3) -> Point3(0,1,2) | [
"Take",
"a",
"single",
"object",
"(",
"not",
"a",
"list",
"of",
"them!",
")",
"and",
"return",
"a",
"euclid",
"type",
"#",
"If",
"given",
"a",
"euclid",
"obj",
"return",
"the",
"desired",
"type",
"#",
"--",
"3d",
"types",
"are",
"projected",
"to",
"z... | def _euc_obj(an_obj: Any, intended_class:type=Vector3) -> Union[Point23, Vector23]:
''' Take a single object (not a list of them!) and return a euclid type
# If given a euclid obj, return the desired type,
# -- 3d types are projected to z=0 when intended_class is 2D
# -- 2D types are projected to z=0 when intended class is 3D
_euc_obj( Vector3(0,1,2), Vector3) -> Vector3(0,1,2)
_euc_obj( Vector3(0,1,2), Point3) -> Point3(0,1,2)
_euc_obj( Vector2(0,1), Vector3) -> Vector3(0,1,0)
_euc_obj( Vector2(0,1), Point3) -> Point3(0,1,0)
_euc_obj( (0,1), Vector3) -> Vector3(0,1,0)
_euc_obj( (0,1), Point3) -> Point3(0,1,0)
_euc_obj( (0,1), Point2) -> Point2(0,1,0)
_euc_obj( (0,1,2), Point2) -> Point2(0,1)
_euc_obj( (0,1,2), Point3) -> Point3(0,1,2)
'''
elts_in_constructor = 3
if intended_class in (Point2, Vector2):
elts_in_constructor = 2
result = intended_class(*an_obj[:elts_in_constructor])
return result | [
"def",
"_euc_obj",
"(",
"an_obj",
":",
"Any",
",",
"intended_class",
":",
"type",
"=",
"Vector3",
")",
"->",
"Union",
"[",
"Point23",
",",
"Vector23",
"]",
":",
"elts_in_constructor",
"=",
"3",
"if",
"intended_class",
"in",
"(",
"Point2",
",",
"Vector2",
... | https://github.com/SolidCode/SolidPython/blob/4715c827ad90db26ee37df57bc425e6f2de3cf8d/solid/utils.py#L752-L771 | |
grnet/synnefo | d06ec8c7871092131cdaabf6b03ed0b504c93e43 | snf-common/synnefo/lib/utils.py | python | split_time | (value) | return (int(seconds), int(microseconds)) | Splits time as floating point number into a tuple.
@param value: Time in seconds
@type value: int or float
@return: Tuple containing (seconds, microseconds) | Splits time as floating point number into a tuple. | [
"Splits",
"time",
"as",
"floating",
"point",
"number",
"into",
"a",
"tuple",
"."
] | def split_time(value):
"""Splits time as floating point number into a tuple.
@param value: Time in seconds
@type value: int or float
@return: Tuple containing (seconds, microseconds)
"""
(seconds, microseconds) = divmod(int(value * 1000000), 1000000)
assert 0 <= seconds, \
"Seconds must be larger than or equal to 0, but are %s" % seconds
assert 0 <= microseconds <= 999999, \
"Microseconds must be 0-999999, but are %s" % microseconds
return (int(seconds), int(microseconds)) | [
"def",
"split_time",
"(",
"value",
")",
":",
"(",
"seconds",
",",
"microseconds",
")",
"=",
"divmod",
"(",
"int",
"(",
"value",
"*",
"1000000",
")",
",",
"1000000",
")",
"assert",
"0",
"<=",
"seconds",
",",
"\"Seconds must be larger than or equal to 0, but are... | https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-common/synnefo/lib/utils.py#L20-L35 | |
CastagnaIT/plugin.video.netflix | 5cf5fa436eb9956576c0f62aa31a4c7d6c5b8a4a | packages/httpcore/_async/http11.py | python | AsyncHTTP11Connection.should_close | (self) | return self._server_disconnected() or self._keepalive_expired() | Return `True` if the connection is in a state where it should be closed. | Return `True` if the connection is in a state where it should be closed. | [
"Return",
"True",
"if",
"the",
"connection",
"is",
"in",
"a",
"state",
"where",
"it",
"should",
"be",
"closed",
"."
] | def should_close(self) -> bool:
"""
Return `True` if the connection is in a state where it should be closed.
"""
return self._server_disconnected() or self._keepalive_expired() | [
"def",
"should_close",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_server_disconnected",
"(",
")",
"or",
"self",
".",
"_keepalive_expired",
"(",
")"
] | https://github.com/CastagnaIT/plugin.video.netflix/blob/5cf5fa436eb9956576c0f62aa31a4c7d6c5b8a4a/packages/httpcore/_async/http11.py#L75-L79 | |
AlessandroZ/LaZagne | 30623c9138e2387d10f6631007f954f2a4ead06d | Windows/lazagne/config/DPAPI/crypto.py | python | dataDecrypt | (cipherAlgo, hashAlgo, raw, encKey, iv, rounds) | return cleartxt | Internal use. Decrypts data stored in DPAPI structures. | Internal use. Decrypts data stored in DPAPI structures. | [
"Internal",
"use",
".",
"Decrypts",
"data",
"stored",
"in",
"DPAPI",
"structures",
"."
] | def dataDecrypt(cipherAlgo, hashAlgo, raw, encKey, iv, rounds):
"""
Internal use. Decrypts data stored in DPAPI structures.
"""
hname = {"HMAC": "sha1"}.get(hashAlgo.name, hashAlgo.name)
derived = pbkdf2(encKey, iv, cipherAlgo.keyLength + cipherAlgo.ivLength, rounds, hname)
key, iv = derived[:int(cipherAlgo.keyLength)], derived[int(cipherAlgo.keyLength):]
key = key[:int(cipherAlgo.keyLength)]
iv = iv[:int(cipherAlgo.ivLength)]
if "AES" in cipherAlgo.name:
cipher = AESModeOfOperationCBC(key, iv=iv)
cleartxt = b"".join([cipher.decrypt(raw[i:i + AES_BLOCK_SIZE]) for i in range(0, len(raw), AES_BLOCK_SIZE)])
else:
cipher = cipherAlgo.module(key, CBC, iv)
cleartxt = cipher.decrypt(raw)
return cleartxt | [
"def",
"dataDecrypt",
"(",
"cipherAlgo",
",",
"hashAlgo",
",",
"raw",
",",
"encKey",
",",
"iv",
",",
"rounds",
")",
":",
"hname",
"=",
"{",
"\"HMAC\"",
":",
"\"sha1\"",
"}",
".",
"get",
"(",
"hashAlgo",
".",
"name",
",",
"hashAlgo",
".",
"name",
")",... | https://github.com/AlessandroZ/LaZagne/blob/30623c9138e2387d10f6631007f954f2a4ead06d/Windows/lazagne/config/DPAPI/crypto.py#L337-L353 | |
winpython/winpython | 5af92920d1d6b4e12702d1816a1f7bbb95a3d949 | winpython/qthelpers.py | python | file_uri | (fname) | Select the right file uri scheme according to the operating system | Select the right file uri scheme according to the operating system | [
"Select",
"the",
"right",
"file",
"uri",
"scheme",
"according",
"to",
"the",
"operating",
"system"
] | def file_uri(fname):
"""Select the right file uri scheme according to the operating system"""
if os.name == 'nt':
# Local file
if re.search(r'^[a-zA-Z]:', fname):
return 'file:///' + fname
# UNC based path
else:
return 'file://' + fname
else:
return 'file://' + fname | [
"def",
"file_uri",
"(",
"fname",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# Local file",
"if",
"re",
".",
"search",
"(",
"r'^[a-zA-Z]:'",
",",
"fname",
")",
":",
"return",
"'file:///'",
"+",
"fname",
"# UNC based path",
"else",
":",
"return... | https://github.com/winpython/winpython/blob/5af92920d1d6b4e12702d1816a1f7bbb95a3d949/winpython/qthelpers.py#L103-L113 | ||
bdcht/amoco | dac8e00b862eb6d87cc88dddd1e5316c67c1d798 | amoco/sa/lsweep.py | python | lsweep.score | (self, func=None) | return len(sig) | a measure for the *complexity* of the program.
For the moment it is associated only with the
signature length. | a measure for the *complexity* of the program.
For the moment it is associated only with the
signature length. | [
"a",
"measure",
"for",
"the",
"*",
"complexity",
"*",
"of",
"the",
"program",
".",
"For",
"the",
"moment",
"it",
"is",
"associated",
"only",
"with",
"the",
"signature",
"length",
"."
] | def score(self, func=None):
"""a measure for the *complexity* of the program.
For the moment it is associated only with the
signature length.
"""
sig = self.signature(func)
return len(sig) | [
"def",
"score",
"(",
"self",
",",
"func",
"=",
"None",
")",
":",
"sig",
"=",
"self",
".",
"signature",
"(",
"func",
")",
"return",
"len",
"(",
"sig",
")"
] | https://github.com/bdcht/amoco/blob/dac8e00b862eb6d87cc88dddd1e5316c67c1d798/amoco/sa/lsweep.py#L171-L177 | |
inasafe/inasafe | 355eb2ce63f516b9c26af0c86a24f99e53f63f87 | safe/gis/vector/union.py | python | union | (union_a, union_b) | return union_layer | Union of two vector layers.
Issue https://github.com/inasafe/inasafe/issues/3186
:param union_a: The vector layer for the union.
:type union_a: QgsVectorLayer
:param union_b: The vector layer for the union.
:type union_b: QgsVectorLayer
:return: The clip vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0 | Union of two vector layers. | [
"Union",
"of",
"two",
"vector",
"layers",
"."
] | def union(union_a, union_b):
"""Union of two vector layers.
Issue https://github.com/inasafe/inasafe/issues/3186
:param union_a: The vector layer for the union.
:type union_a: QgsVectorLayer
:param union_b: The vector layer for the union.
:type union_b: QgsVectorLayer
:return: The clip vector layer.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = union_steps['output_layer_name']
output_layer_name = output_layer_name % (
union_a.keywords['layer_purpose'],
union_b.keywords['layer_purpose']
)
keywords_union_1 = union_a.keywords
keywords_union_2 = union_b.keywords
inasafe_fields_union_1 = keywords_union_1['inasafe_fields']
inasafe_fields_union_2 = keywords_union_2['inasafe_fields']
inasafe_fields = inasafe_fields_union_1
inasafe_fields.update(inasafe_fields_union_2)
parameters = {'INPUT': union_a,
'OVERLAY': union_b,
'OUTPUT': 'memory:'}
# TODO implement callback through QgsProcessingFeedback object
initialize_processing()
feedback = create_processing_feedback()
context = create_processing_context(feedback=feedback)
result = processing.run('native:union', parameters, context=context)
if result is None:
raise ProcessingInstallationError
union_layer = result['OUTPUT']
union_layer.setName(output_layer_name)
# use to avoid modifying original source
union_layer.keywords = dict(union_a.keywords)
union_layer.keywords['inasafe_fields'] = inasafe_fields
union_layer.keywords['title'] = output_layer_name
union_layer.keywords['layer_purpose'] = 'aggregate_hazard'
union_layer.keywords['hazard_keywords'] = keywords_union_1.copy()
union_layer.keywords['aggregation_keywords'] = keywords_union_2.copy()
fill_hazard_class(union_layer)
check_layer(union_layer)
return union_layer | [
"def",
"union",
"(",
"union_a",
",",
"union_b",
")",
":",
"output_layer_name",
"=",
"union_steps",
"[",
"'output_layer_name'",
"]",
"output_layer_name",
"=",
"output_layer_name",
"%",
"(",
"union_a",
".",
"keywords",
"[",
"'layer_purpose'",
"]",
",",
"union_b",
... | https://github.com/inasafe/inasafe/blob/355eb2ce63f516b9c26af0c86a24f99e53f63f87/safe/gis/vector/union.py#L33-L90 | |
wanggrun/Adaptively-Connected-Neural-Networks | e27066ef52301bdafa5932f43af8feeb23647edb | cnn/pixel-aware/resnet_model.py | python | get_bn | (zero_init=False) | Zero init gamma is good for resnet. See https://arxiv.org/abs/1706.02677. | Zero init gamma is good for resnet. See https://arxiv.org/abs/1706.02677. | [
"Zero",
"init",
"gamma",
"is",
"good",
"for",
"resnet",
".",
"See",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1706",
".",
"02677",
"."
] | def get_bn(zero_init=False):
"""
Zero init gamma is good for resnet. See https://arxiv.org/abs/1706.02677.
"""
if zero_init:
return lambda x, name=None: BatchNorm('bn', x, gamma_init=tf.zeros_initializer())
else:
return lambda x, name=None: BatchNorm('bn', x) | [
"def",
"get_bn",
"(",
"zero_init",
"=",
"False",
")",
":",
"if",
"zero_init",
":",
"return",
"lambda",
"x",
",",
"name",
"=",
"None",
":",
"BatchNorm",
"(",
"'bn'",
",",
"x",
",",
"gamma_init",
"=",
"tf",
".",
"zeros_initializer",
"(",
")",
")",
"els... | https://github.com/wanggrun/Adaptively-Connected-Neural-Networks/blob/e27066ef52301bdafa5932f43af8feeb23647edb/cnn/pixel-aware/resnet_model.py#L44-L51 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/pip/_internal/__init__.py | python | auto_complete_paths | (current, completion_type) | If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(`file`, `path` or `dir`)i
:return: A generator of regular files and/or directories | If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``. | [
"If",
"completion_type",
"is",
"file",
"or",
"path",
"list",
"all",
"regular",
"files",
"and",
"directories",
"starting",
"with",
"current",
";",
"otherwise",
"only",
"list",
"directories",
"starting",
"with",
"current",
"."
] | def auto_complete_paths(current, completion_type):
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(`file`, `path` or `dir`)i
:return: A generator of regular files and/or directories
"""
directory, filename = os.path.split(current)
current_path = os.path.abspath(directory)
# Don't complete paths if they can't be accessed
if not os.access(current_path, os.R_OK):
return
filename = os.path.normcase(filename)
# list all files that start with ``filename``
file_list = (x for x in os.listdir(current_path)
if os.path.normcase(x).startswith(filename))
for f in file_list:
opt = os.path.join(current_path, f)
comp_file = os.path.normcase(os.path.join(directory, f))
# complete regular files when there is not ``<dir>`` after option
# complete directories when there is ``<file>``, ``<path>`` or
# ``<dir>``after option
if completion_type != 'dir' and os.path.isfile(opt):
yield comp_file
elif os.path.isdir(opt):
yield os.path.join(comp_file, '') | [
"def",
"auto_complete_paths",
"(",
"current",
",",
"completion_type",
")",
":",
"directory",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"current",
")",
"current_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"# Don't... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_internal/__init__.py#L174-L201 | ||
havakv/pycox | 69940e0b28c8851cb6a2ca66083f857aee902022 | pycox/models/utils.py | python | log_softplus | (input, threshold=-15.) | return output | Equivalent to 'F.softplus(input).log()', but for 'input < threshold',
we return 'input', as this is approximately the same.
Arguments:
input {torch.tensor} -- Input tensor
Keyword Arguments:
threshold {float} -- Treshold for when to just return input (default: {-15.})
Returns:
torch.tensor -- return log(softplus(input)). | Equivalent to 'F.softplus(input).log()', but for 'input < threshold',
we return 'input', as this is approximately the same. | [
"Equivalent",
"to",
"F",
".",
"softplus",
"(",
"input",
")",
".",
"log",
"()",
"but",
"for",
"input",
"<",
"threshold",
"we",
"return",
"input",
"as",
"this",
"is",
"approximately",
"the",
"same",
"."
] | def log_softplus(input, threshold=-15.):
"""Equivalent to 'F.softplus(input).log()', but for 'input < threshold',
we return 'input', as this is approximately the same.
Arguments:
input {torch.tensor} -- Input tensor
Keyword Arguments:
threshold {float} -- Treshold for when to just return input (default: {-15.})
Returns:
torch.tensor -- return log(softplus(input)).
"""
output = input.clone()
above = input >= threshold
output[above] = F.softplus(input[above]).log()
return output | [
"def",
"log_softplus",
"(",
"input",
",",
"threshold",
"=",
"-",
"15.",
")",
":",
"output",
"=",
"input",
".",
"clone",
"(",
")",
"above",
"=",
"input",
">=",
"threshold",
"output",
"[",
"above",
"]",
"=",
"F",
".",
"softplus",
"(",
"input",
"[",
"... | https://github.com/havakv/pycox/blob/69940e0b28c8851cb6a2ca66083f857aee902022/pycox/models/utils.py#L39-L55 | |
VITA-Group/DeblurGANv2 | 756db7f0b30b5a35afd19347b02c34d595135cf1 | models/senet.py | python | SENet.__init__ | (self, block, layers, groups, reduction, dropout_p=0.2,
inplanes=128, input_3x3=True, downsample_kernel_size=3,
downsample_padding=1, num_classes=1000) | Parameters
----------
block (nn.Module): Bottleneck class.
- For SENet154: SEBottleneck
- For SE-ResNet models: SEResNetBottleneck
- For SE-ResNeXt models: SEResNeXtBottleneck
layers (list of ints): Number of residual blocks for 4 layers of the
network (layer1...layer4).
groups (int): Number of groups for the 3x3 convolution in each
bottleneck block.
- For SENet154: 64
- For SE-ResNet models: 1
- For SE-ResNeXt models: 32
reduction (int): Reduction ratio for Squeeze-and-Excitation modules.
- For all models: 16
dropout_p (float or None): Drop probability for the Dropout layer.
If `None` the Dropout layer is not used.
- For SENet154: 0.2
- For SE-ResNet models: None
- For SE-ResNeXt models: None
inplanes (int): Number of input channels for layer1.
- For SENet154: 128
- For SE-ResNet models: 64
- For SE-ResNeXt models: 64
input_3x3 (bool): If `True`, use three 3x3 convolutions instead of
a single 7x7 convolution in layer0.
- For SENet154: True
- For SE-ResNet models: False
- For SE-ResNeXt models: False
downsample_kernel_size (int): Kernel size for downsampling convolutions
in layer2, layer3 and layer4.
- For SENet154: 3
- For SE-ResNet models: 1
- For SE-ResNeXt models: 1
downsample_padding (int): Padding for downsampling convolutions in
layer2, layer3 and layer4.
- For SENet154: 1
- For SE-ResNet models: 0
- For SE-ResNeXt models: 0
num_classes (int): Number of outputs in `last_linear` layer.
- For all models: 1000 | Parameters
----------
block (nn.Module): Bottleneck class.
- For SENet154: SEBottleneck
- For SE-ResNet models: SEResNetBottleneck
- For SE-ResNeXt models: SEResNeXtBottleneck
layers (list of ints): Number of residual blocks for 4 layers of the
network (layer1...layer4).
groups (int): Number of groups for the 3x3 convolution in each
bottleneck block.
- For SENet154: 64
- For SE-ResNet models: 1
- For SE-ResNeXt models: 32
reduction (int): Reduction ratio for Squeeze-and-Excitation modules.
- For all models: 16
dropout_p (float or None): Drop probability for the Dropout layer.
If `None` the Dropout layer is not used.
- For SENet154: 0.2
- For SE-ResNet models: None
- For SE-ResNeXt models: None
inplanes (int): Number of input channels for layer1.
- For SENet154: 128
- For SE-ResNet models: 64
- For SE-ResNeXt models: 64
input_3x3 (bool): If `True`, use three 3x3 convolutions instead of
a single 7x7 convolution in layer0.
- For SENet154: True
- For SE-ResNet models: False
- For SE-ResNeXt models: False
downsample_kernel_size (int): Kernel size for downsampling convolutions
in layer2, layer3 and layer4.
- For SENet154: 3
- For SE-ResNet models: 1
- For SE-ResNeXt models: 1
downsample_padding (int): Padding for downsampling convolutions in
layer2, layer3 and layer4.
- For SENet154: 1
- For SE-ResNet models: 0
- For SE-ResNeXt models: 0
num_classes (int): Number of outputs in `last_linear` layer.
- For all models: 1000 | [
"Parameters",
"----------",
"block",
"(",
"nn",
".",
"Module",
")",
":",
"Bottleneck",
"class",
".",
"-",
"For",
"SENet154",
":",
"SEBottleneck",
"-",
"For",
"SE",
"-",
"ResNet",
"models",
":",
"SEResNetBottleneck",
"-",
"For",
"SE",
"-",
"ResNeXt",
"model... | def __init__(self, block, layers, groups, reduction, dropout_p=0.2,
inplanes=128, input_3x3=True, downsample_kernel_size=3,
downsample_padding=1, num_classes=1000):
"""
Parameters
----------
block (nn.Module): Bottleneck class.
- For SENet154: SEBottleneck
- For SE-ResNet models: SEResNetBottleneck
- For SE-ResNeXt models: SEResNeXtBottleneck
layers (list of ints): Number of residual blocks for 4 layers of the
network (layer1...layer4).
groups (int): Number of groups for the 3x3 convolution in each
bottleneck block.
- For SENet154: 64
- For SE-ResNet models: 1
- For SE-ResNeXt models: 32
reduction (int): Reduction ratio for Squeeze-and-Excitation modules.
- For all models: 16
dropout_p (float or None): Drop probability for the Dropout layer.
If `None` the Dropout layer is not used.
- For SENet154: 0.2
- For SE-ResNet models: None
- For SE-ResNeXt models: None
inplanes (int): Number of input channels for layer1.
- For SENet154: 128
- For SE-ResNet models: 64
- For SE-ResNeXt models: 64
input_3x3 (bool): If `True`, use three 3x3 convolutions instead of
a single 7x7 convolution in layer0.
- For SENet154: True
- For SE-ResNet models: False
- For SE-ResNeXt models: False
downsample_kernel_size (int): Kernel size for downsampling convolutions
in layer2, layer3 and layer4.
- For SENet154: 3
- For SE-ResNet models: 1
- For SE-ResNeXt models: 1
downsample_padding (int): Padding for downsampling convolutions in
layer2, layer3 and layer4.
- For SENet154: 1
- For SE-ResNet models: 0
- For SE-ResNeXt models: 0
num_classes (int): Number of outputs in `last_linear` layer.
- For all models: 1000
"""
super(SENet, self).__init__()
self.inplanes = inplanes
if input_3x3:
layer0_modules = [
('conv1', nn.Conv2d(3, 64, 3, stride=2, padding=1)),
('bn1', nn.InstanceNorm2d(64, affine=False)),
('relu1', nn.ReLU(inplace=True)),
('conv2', nn.Conv2d(64, 64, 3, stride=1, padding=1)),
('bn2', nn.InstanceNorm2d(64, affine=False)),
('relu2', nn.ReLU(inplace=True)),
('conv3', nn.Conv2d(64, inplanes, 3, stride=1, padding=1)),
('bn3', nn.InstanceNorm2d(inplanes, affine=False)),
('relu3', nn.ReLU(inplace=True)),
]
else:
layer0_modules = [
('conv1', nn.Conv2d(3, inplanes, kernel_size=7, stride=2,
padding=3)),
('bn1', nn.InstanceNorm2d(inplanes, affine=False)),
('relu1', nn.ReLU(inplace=True)),
]
# To preserve compatibility with Caffe weights `ceil_mode=True`
# is used instead of `padding=1`.
layer0_modules.append(('pool', nn.MaxPool2d(3, stride=2,
ceil_mode=True)))
self.layer0 = nn.Sequential(OrderedDict(layer0_modules))
self.layer1 = self._make_layer(
block,
planes=64,
blocks=layers[0],
groups=groups,
reduction=reduction,
downsample_kernel_size=1,
downsample_padding=0
)
self.layer2 = self._make_layer(
block,
planes=128,
blocks=layers[1],
stride=2,
groups=groups,
reduction=reduction,
downsample_kernel_size=downsample_kernel_size,
downsample_padding=downsample_padding
)
self.layer3 = self._make_layer(
block,
planes=256,
blocks=layers[2],
stride=2,
groups=groups,
reduction=reduction,
downsample_kernel_size=downsample_kernel_size,
downsample_padding=downsample_padding
)
self.layer4 = self._make_layer(
block,
planes=512,
blocks=layers[3],
stride=2,
groups=groups,
reduction=reduction,
downsample_kernel_size=downsample_kernel_size,
downsample_padding=downsample_padding
)
self.avg_pool = nn.AvgPool2d(7, stride=1)
self.dropout = nn.Dropout(dropout_p) if dropout_p is not None else None
self.last_linear = nn.Linear(512 * block.expansion, num_classes) | [
"def",
"__init__",
"(",
"self",
",",
"block",
",",
"layers",
",",
"groups",
",",
"reduction",
",",
"dropout_p",
"=",
"0.2",
",",
"inplanes",
"=",
"128",
",",
"input_3x3",
"=",
"True",
",",
"downsample_kernel_size",
"=",
"3",
",",
"downsample_padding",
"=",... | https://github.com/VITA-Group/DeblurGANv2/blob/756db7f0b30b5a35afd19347b02c34d595135cf1/models/senet.py#L203-L316 | ||
IdentityPython/pysaml2 | 6badb32d212257bd83ffcc816f9b625f68281b47 | src/saml2/request.py | python | LogoutRequest.issuer | (self) | return self.message.issuer | [] | def issuer(self):
return self.message.issuer | [
"def",
"issuer",
"(",
"self",
")",
":",
"return",
"self",
".",
"message",
".",
"issuer"
] | https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/request.py#L196-L197 | |||
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/contrib/tensor_forest/python/topn.py | python | TopN.insert | (self, ids, scores) | Insert the ids and scores into the TopN. | Insert the ids and scores into the TopN. | [
"Insert",
"the",
"ids",
"and",
"scores",
"into",
"the",
"TopN",
"."
] | def insert(self, ids, scores):
"""Insert the ids and scores into the TopN."""
with tf.control_dependencies(self.last_ops):
scatter_op = tf.scatter_update(self.id_to_score, ids, scores)
larger_scores = tf.greater(scores, self.sl_scores[0])
def shortlist_insert():
larger_ids = tf.boolean_mask(tf.to_int64(ids), larger_scores)
larger_score_values = tf.boolean_mask(scores, larger_scores)
shortlist_ids, new_ids, new_scores = self.ops.top_n_insert(
self.sl_ids, self.sl_scores, larger_ids, larger_score_values)
u1 = tf.scatter_update(self.sl_ids, shortlist_ids, new_ids)
u2 = tf.scatter_update(self.sl_scores, shortlist_ids, new_scores)
return tf.group(u1, u2)
# We only need to insert into the shortlist if there are any
# scores larger than the threshold.
cond_op = tf.cond(
tf.reduce_any(larger_scores), shortlist_insert, tf.no_op)
with tf.control_dependencies([cond_op]):
self.last_ops = [scatter_op, cond_op] | [
"def",
"insert",
"(",
"self",
",",
"ids",
",",
"scores",
")",
":",
"with",
"tf",
".",
"control_dependencies",
"(",
"self",
".",
"last_ops",
")",
":",
"scatter_op",
"=",
"tf",
".",
"scatter_update",
"(",
"self",
".",
"id_to_score",
",",
"ids",
",",
"sco... | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/tensor_forest/python/topn.py#L81-L101 | ||
cpbotha/nvpy | 844e8e5ad67cbae91603e95703b5fc34e78675ab | nvpy/view.py | python | View.set_search_mode | (self, search_mode, silent=False) | @param search_mode: the search mode, "gstyle" or "regexp"
@param silent: Specify True if you don't want the view to trigger any events.
@return: | [] | def set_search_mode(self, search_mode, silent=False):
"""
@param search_mode: the search mode, "gstyle" or "regexp"
@param silent: Specify True if you don't want the view to trigger any events.
@return:
"""
if silent:
self.mute('change:search_mode')
self.search_mode_var.set(search_mode)
self.unmute('change:search_mode') | [
"def",
"set_search_mode",
"(",
"self",
",",
"search_mode",
",",
"silent",
"=",
"False",
")",
":",
"if",
"silent",
":",
"self",
".",
"mute",
"(",
"'change:search_mode'",
")",
"self",
".",
"search_mode_var",
".",
"set",
"(",
"search_mode",
")",
"self",
".",
... | https://github.com/cpbotha/nvpy/blob/844e8e5ad67cbae91603e95703b5fc34e78675ab/nvpy/view.py#L2018-L2031 | |||
cackharot/suds-py3 | 1d92cc6297efee31bfd94b50b99c431505d7de21 | suds/xsd/sxbase.py | python | SchemaObject.extension | (self) | return False | Get whether the object is an extension of another type.
@return: True if an extension, else False.
@rtype: boolean | Get whether the object is an extension of another type. | [
"Get",
"whether",
"the",
"object",
"is",
"an",
"extension",
"of",
"another",
"type",
"."
] | def extension(self):
"""
Get whether the object is an extension of another type.
@return: True if an extension, else False.
@rtype: boolean
"""
return False | [
"def",
"extension",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/cackharot/suds-py3/blob/1d92cc6297efee31bfd94b50b99c431505d7de21/suds/xsd/sxbase.py#L285-L291 | |
Antergos/Cnchi | 13ac2209da9432d453e0097cf48a107640b563a9 | src/main_window.py | python | MainWindow.on_exit_button_clicked | (self, _widget, _data=None) | Quit Cnchi | Quit Cnchi | [
"Quit",
"Cnchi"
] | def on_exit_button_clicked(self, _widget, _data=None):
""" Quit Cnchi """
try:
misc.remove_temp_files(self.settings.get('temp'))
logging.info("Quiting installer...")
for proc in multiprocessing.active_children():
proc.terminate()
logging.shutdown()
except KeyboardInterrupt:
pass | [
"def",
"on_exit_button_clicked",
"(",
"self",
",",
"_widget",
",",
"_data",
"=",
"None",
")",
":",
"try",
":",
"misc",
".",
"remove_temp_files",
"(",
"self",
".",
"settings",
".",
"get",
"(",
"'temp'",
")",
")",
"logging",
".",
"info",
"(",
"\"Quiting in... | https://github.com/Antergos/Cnchi/blob/13ac2209da9432d453e0097cf48a107640b563a9/src/main_window.py#L434-L443 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.