nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | lastError | () | return Error(_obj=ret) | Get the last global error registered. This is per thread if
compiled with thread support. | Get the last global error registered. This is per thread if
compiled with thread support. | [
"Get",
"the",
"last",
"global",
"error",
"registered",
".",
"This",
"is",
"per",
"thread",
"if",
"compiled",
"with",
"thread",
"support",
"."
] | def lastError():
"""Get the last global error registered. This is per thread if
compiled with thread support. """
ret = libxml2mod.xmlGetLastError()
if ret is None:raise treeError('xmlGetLastError() failed')
return Error(_obj=ret) | [
"def",
"lastError",
"(",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlGetLastError",
"(",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlGetLastError() failed'",
")",
"return",
"Error",
"(",
"_obj",
"=",
"ret",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1139-L1144 | |
intel/llvm | e6d0547e9d99b5a56430c4749f6c7e328bf221ab | lldb/examples/python/diagnose_unwind.py | python | diagnose_unwind | (debugger, command, result, dict) | Gather diagnostic information to help debug incorrect unwind (backtrace)
behavior in lldb. When there is a backtrace that doesn't look
correct, run this command with the correct thread selected and a
large amount of diagnostic information will be printed, it is likely
to be helpful when reporting the problem. | Gather diagnostic information to help debug incorrect unwind (backtrace)
behavior in lldb. When there is a backtrace that doesn't look
correct, run this command with the correct thread selected and a
large amount of diagnostic information will be printed, it is likely
to be helpful when reporting the problem. | [
"Gather",
"diagnostic",
"information",
"to",
"help",
"debug",
"incorrect",
"unwind",
"(",
"backtrace",
")",
"behavior",
"in",
"lldb",
".",
"When",
"there",
"is",
"a",
"backtrace",
"that",
"doesn",
"t",
"look",
"correct",
"run",
"this",
"command",
"with",
"th... | def diagnose_unwind(debugger, command, result, dict):
"""
Gather diagnostic information to help debug incorrect unwind (backtrace)
behavior in lldb. When there is a backtrace that doesn't look
correct, run this command with the correct thread selected and a
large amount of diagnostic information will be printed, it is likely
to be helpful when reporting the problem.
"""
command_args = shlex.split(command)
parser = create_diagnose_unwind_options()
try:
(options, args) = parser.parse_args(command_args)
except:
return
target = debugger.GetSelectedTarget()
if target:
process = target.GetProcess()
if process:
thread = process.GetSelectedThread()
if thread:
lldb_versions_match = re.search(
r'[lL][lL][dD][bB]-(\d+)([.](\d+))?([.](\d+))?',
debugger.GetVersionString())
lldb_version = 0
lldb_minor = 0
if len(lldb_versions_match.groups()
) >= 1 and lldb_versions_match.groups()[0]:
lldb_major = int(lldb_versions_match.groups()[0])
if len(lldb_versions_match.groups()
) >= 5 and lldb_versions_match.groups()[4]:
lldb_minor = int(lldb_versions_match.groups()[4])
modules_seen = []
addresses_seen = []
print('LLDB version %s' % debugger.GetVersionString())
print('Unwind diagnostics for thread %d' % thread.GetIndexID())
print("")
print("=============================================================================================")
print("")
print("OS plugin setting:")
debugger.HandleCommand(
"settings show target.process.python-os-plugin-path")
print("")
print("Live register context:")
thread.SetSelectedFrame(0)
debugger.HandleCommand("register read")
print("")
print("=============================================================================================")
print("")
print("lldb's unwind algorithm:")
print("")
frame_num = 0
for frame in thread.frames:
if not frame.IsInlined():
this_module = backtrace_print_frame(
target, frame_num, frame.GetPC(), frame.GetFP())
print_stack_frame(process, frame.GetFP())
print("")
if this_module is not None:
modules_seen.append(this_module)
addresses_seen.append(frame.GetPC())
frame_num = frame_num + 1
print("")
print("=============================================================================================")
print("")
print("Simple stack walk algorithm:")
print("")
(module_list, address_list) = simple_backtrace(debugger)
if module_list and module_list is not None:
modules_seen += module_list
if address_list and address_list is not None:
addresses_seen = set(addresses_seen)
addresses_seen.update(set(address_list))
print("")
print("=============================================================================================")
print("")
print("Modules seen in stack walks:")
print("")
modules_already_seen = set()
for module in modules_seen:
if module is not None and module.GetFileSpec().GetFilename() is not None:
if not module.GetFileSpec().GetFilename() in modules_already_seen:
debugger.HandleCommand(
'image list %s' %
module.GetFileSpec().GetFilename())
modules_already_seen.add(
module.GetFileSpec().GetFilename())
print("")
print("=============================================================================================")
print("")
print("Disassembly ofaddresses seen in stack walks:")
print("")
additional_addresses_to_disassemble = addresses_seen
for frame in thread.frames:
if not frame.IsInlined():
print("--------------------------------------------------------------------------------------")
print("")
print("Disassembly of %s, frame %d, address 0x%x" % (frame.GetFunctionName(), frame.GetFrameID(), frame.GetPC()))
print("")
if target.triple[
0:6] == "x86_64" or target.triple[
0:4] == "i386":
debugger.HandleCommand(
'disassemble -F att -a 0x%x' % frame.GetPC())
else:
debugger.HandleCommand(
'disassemble -a 0x%x' %
frame.GetPC())
if frame.GetPC() in additional_addresses_to_disassemble:
additional_addresses_to_disassemble.remove(
frame.GetPC())
for address in list(additional_addresses_to_disassemble):
print("--------------------------------------------------------------------------------------")
print("")
print("Disassembly of 0x%x" % address)
print("")
if target.triple[
0:6] == "x86_64" or target.triple[
0:4] == "i386":
debugger.HandleCommand(
'disassemble -F att -a 0x%x' % address)
else:
debugger.HandleCommand('disassemble -a 0x%x' % address)
print("")
print("=============================================================================================")
print("")
additional_addresses_to_show_unwind = addresses_seen
for frame in thread.frames:
if not frame.IsInlined():
print("--------------------------------------------------------------------------------------")
print("")
print("Unwind instructions for %s, frame %d" % (frame.GetFunctionName(), frame.GetFrameID()))
print("")
debugger.HandleCommand(
'image show-unwind -a "0x%x"' % frame.GetPC())
if frame.GetPC() in additional_addresses_to_show_unwind:
additional_addresses_to_show_unwind.remove(
frame.GetPC())
for address in list(additional_addresses_to_show_unwind):
print("--------------------------------------------------------------------------------------")
print("")
print("Unwind instructions for 0x%x" % address)
print("")
debugger.HandleCommand(
'image show-unwind -a "0x%x"' % address) | [
"def",
"diagnose_unwind",
"(",
"debugger",
",",
"command",
",",
"result",
",",
"dict",
")",
":",
"command_args",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"parser",
"=",
"create_diagnose_unwind_options",
"(",
")",
"try",
":",
"(",
"options",
",",
"a... | https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/examples/python/diagnose_unwind.py#L148-L299 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/feature_column/feature_column.py | python | _shape_offsets | (shape) | return offsets | Returns moving offset for each dimension given shape. | Returns moving offset for each dimension given shape. | [
"Returns",
"moving",
"offset",
"for",
"each",
"dimension",
"given",
"shape",
"."
] | def _shape_offsets(shape):
"""Returns moving offset for each dimension given shape."""
offsets = []
for dim in reversed(shape):
if offsets:
offsets.append(dim * offsets[-1])
else:
offsets.append(dim)
offsets.reverse()
return offsets | [
"def",
"_shape_offsets",
"(",
"shape",
")",
":",
"offsets",
"=",
"[",
"]",
"for",
"dim",
"in",
"reversed",
"(",
"shape",
")",
":",
"if",
"offsets",
":",
"offsets",
".",
"append",
"(",
"dim",
"*",
"offsets",
"[",
"-",
"1",
"]",
")",
"else",
":",
"... | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/feature_column/feature_column.py#L1590-L1599 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/utils.py | python | add_dict_to_cookiejar | (cj, cookie_dict) | return cookiejar_from_dict(cookie_dict, cj) | Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:rtype: CookieJar | Returns a CookieJar from a key/value dictionary. | [
"Returns",
"a",
"CookieJar",
"from",
"a",
"key",
"/",
"value",
"dictionary",
"."
] | def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:rtype: CookieJar
"""
return cookiejar_from_dict(cookie_dict, cj) | [
"def",
"add_dict_to_cookiejar",
"(",
"cj",
",",
"cookie_dict",
")",
":",
"return",
"cookiejar_from_dict",
"(",
"cookie_dict",
",",
"cj",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/requests/utils.py#L424-L432 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Environment.py | python | Base.Ignore | (self, target, dependency) | return tlist | Ignore a dependency. | Ignore a dependency. | [
"Ignore",
"a",
"dependency",
"."
] | def Ignore(self, target, dependency):
"""Ignore a dependency."""
tlist = self.arg2nodes(target, self.fs.Entry)
dlist = self.arg2nodes(dependency, self.fs.Entry)
for t in tlist:
t.add_ignore(dlist)
return tlist | [
"def",
"Ignore",
"(",
"self",
",",
"target",
",",
"dependency",
")",
":",
"tlist",
"=",
"self",
".",
"arg2nodes",
"(",
"target",
",",
"self",
".",
"fs",
".",
"Entry",
")",
"dlist",
"=",
"self",
".",
"arg2nodes",
"(",
"dependency",
",",
"self",
".",
... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Environment.py#L2179-L2185 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/polynomial/polyutils.py | python | as_series | (alist, trim=True) | return ret | Return argument as a list of 1-d arrays.
The returned list contains array(s) of dtype double, complex double, or
object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of
size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays
of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array
raises a Value Error if it is not first reshaped into either a 1-d or 2-d
array.
Parameters
----------
a : array_like
A 1- or 2-d array_like
trim : boolean, optional
When True, trailing zeros are removed from the inputs.
When False, the inputs are passed through intact.
Returns
-------
[a1, a2,...] : list of 1d-arrays
A copy of the input data as a list of 1-d arrays.
Raises
------
ValueError :
Raised when `as_series` cannot convert its input to 1-d arrays, or at
least one of the resulting arrays is empty.
Examples
--------
>>> from numpy import polynomial as P
>>> a = np.arange(4)
>>> P.as_series(a)
[array([ 0.]), array([ 1.]), array([ 2.]), array([ 3.])]
>>> b = np.arange(6).reshape((2,3))
>>> P.as_series(b)
[array([ 0., 1., 2.]), array([ 3., 4., 5.])] | Return argument as a list of 1-d arrays. | [
"Return",
"argument",
"as",
"a",
"list",
"of",
"1",
"-",
"d",
"arrays",
"."
] | def as_series(alist, trim=True) :
"""
Return argument as a list of 1-d arrays.
The returned list contains array(s) of dtype double, complex double, or
object. A 1-d argument of shape ``(N,)`` is parsed into ``N`` arrays of
size one; a 2-d argument of shape ``(M,N)`` is parsed into ``M`` arrays
of size ``N`` (i.e., is "parsed by row"); and a higher dimensional array
raises a Value Error if it is not first reshaped into either a 1-d or 2-d
array.
Parameters
----------
a : array_like
A 1- or 2-d array_like
trim : boolean, optional
When True, trailing zeros are removed from the inputs.
When False, the inputs are passed through intact.
Returns
-------
[a1, a2,...] : list of 1d-arrays
A copy of the input data as a list of 1-d arrays.
Raises
------
ValueError :
Raised when `as_series` cannot convert its input to 1-d arrays, or at
least one of the resulting arrays is empty.
Examples
--------
>>> from numpy import polynomial as P
>>> a = np.arange(4)
>>> P.as_series(a)
[array([ 0.]), array([ 1.]), array([ 2.]), array([ 3.])]
>>> b = np.arange(6).reshape((2,3))
>>> P.as_series(b)
[array([ 0., 1., 2.]), array([ 3., 4., 5.])]
"""
arrays = [np.array(a, ndmin=1, copy=0) for a in alist]
if min([a.size for a in arrays]) == 0 :
raise ValueError("Coefficient array is empty")
if any([a.ndim != 1 for a in arrays]) :
raise ValueError("Coefficient array is not 1-d")
if trim :
arrays = [trimseq(a) for a in arrays]
if any([a.dtype == np.dtype(object) for a in arrays]) :
ret = []
for a in arrays :
if a.dtype != np.dtype(object) :
tmp = np.empty(len(a), dtype=np.dtype(object))
tmp[:] = a[:]
ret.append(tmp)
else :
ret.append(a.copy())
else :
try :
dtype = np.common_type(*arrays)
except :
raise ValueError("Coefficient arrays have no common type")
ret = [np.array(a, copy=1, dtype=dtype) for a in arrays]
return ret | [
"def",
"as_series",
"(",
"alist",
",",
"trim",
"=",
"True",
")",
":",
"arrays",
"=",
"[",
"np",
".",
"array",
"(",
"a",
",",
"ndmin",
"=",
"1",
",",
"copy",
"=",
"0",
")",
"for",
"a",
"in",
"alist",
"]",
"if",
"min",
"(",
"[",
"a",
".",
"si... | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/polyutils.py#L115-L179 | |
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py | python | _FindCommandInPath | (command) | return command | If there are no slashes in the command given, this function
searches the PATH env to find the given command, and converts it
to an absolute path. We have to do this because MSVS is looking
for an actual file to launch a debugger on, not just a command
line. Note that this happens at GYP time, so anything needing to
be built needs to have a full path. | If there are no slashes in the command given, this function
searches the PATH env to find the given command, and converts it
to an absolute path. We have to do this because MSVS is looking
for an actual file to launch a debugger on, not just a command
line. Note that this happens at GYP time, so anything needing to
be built needs to have a full path. | [
"If",
"there",
"are",
"no",
"slashes",
"in",
"the",
"command",
"given",
"this",
"function",
"searches",
"the",
"PATH",
"env",
"to",
"find",
"the",
"given",
"command",
"and",
"converts",
"it",
"to",
"an",
"absolute",
"path",
".",
"We",
"have",
"to",
"do",... | def _FindCommandInPath(command):
"""If there are no slashes in the command given, this function
searches the PATH env to find the given command, and converts it
to an absolute path. We have to do this because MSVS is looking
for an actual file to launch a debugger on, not just a command
line. Note that this happens at GYP time, so anything needing to
be built needs to have a full path."""
if '/' in command or '\\' in command:
# If the command already has path elements (either relative or
# absolute), then assume it is constructed properly.
return command
else:
# Search through the path list and find an existing file that
# we can access.
paths = os.environ.get('PATH','').split(os.pathsep)
for path in paths:
item = os.path.join(path, command)
if os.path.isfile(item) and os.access(item, os.X_OK):
return item
return command | [
"def",
"_FindCommandInPath",
"(",
"command",
")",
":",
"if",
"'/'",
"in",
"command",
"or",
"'\\\\'",
"in",
"command",
":",
"# If the command already has path elements (either relative or",
"# absolute), then assume it is constructed properly.",
"return",
"command",
"else",
":... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py#L17-L36 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | GBSizerItem.SetSpan | (*args, **kwargs) | return _core_.GBSizerItem_SetSpan(*args, **kwargs) | SetSpan(self, GBSpan span) -> bool
If the item is already a member of a sizer then first ensure that
there is no other item that would intersect with this one with its new
spanning size, then set the new spanning. Returns True if the change
is successful and after the next Layout() the item will be resized. | SetSpan(self, GBSpan span) -> bool | [
"SetSpan",
"(",
"self",
"GBSpan",
"span",
")",
"-",
">",
"bool"
] | def SetSpan(*args, **kwargs):
"""
SetSpan(self, GBSpan span) -> bool
If the item is already a member of a sizer then first ensure that
there is no other item that would intersect with this one with its new
spanning size, then set the new spanning. Returns True if the change
is successful and after the next Layout() the item will be resized.
"""
return _core_.GBSizerItem_SetSpan(*args, **kwargs) | [
"def",
"SetSpan",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"GBSizerItem_SetSpan",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L15766-L15776 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | VarScrollHelperBase.GetVisibleBegin | (*args, **kwargs) | return _windows_.VarScrollHelperBase_GetVisibleBegin(*args, **kwargs) | GetVisibleBegin(self) -> size_t | GetVisibleBegin(self) -> size_t | [
"GetVisibleBegin",
"(",
"self",
")",
"-",
">",
"size_t"
] | def GetVisibleBegin(*args, **kwargs):
"""GetVisibleBegin(self) -> size_t"""
return _windows_.VarScrollHelperBase_GetVisibleBegin(*args, **kwargs) | [
"def",
"GetVisibleBegin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"VarScrollHelperBase_GetVisibleBegin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L2218-L2220 | |
SoarGroup/Soar | a1c5e249499137a27da60533c72969eef3b8ab6b | scons/scons-local-4.1.0/SCons/Utilities/sconsign.py | python | nodeinfo_raw | (name, ninfo, prefix="") | return name + ': {' + ', '.join(values) + '}' | This just formats the dictionary, which we would normally use str()
to do, except that we want the keys sorted for deterministic output. | This just formats the dictionary, which we would normally use str()
to do, except that we want the keys sorted for deterministic output. | [
"This",
"just",
"formats",
"the",
"dictionary",
"which",
"we",
"would",
"normally",
"use",
"str",
"()",
"to",
"do",
"except",
"that",
"we",
"want",
"the",
"keys",
"sorted",
"for",
"deterministic",
"output",
"."
] | def nodeinfo_raw(name, ninfo, prefix=""):
"""
This just formats the dictionary, which we would normally use str()
to do, except that we want the keys sorted for deterministic output.
"""
d = ninfo.__getstate__()
try:
keys = ninfo.field_list + ['_version_id']
except AttributeError:
keys = sorted(d.keys())
values = []
for key in keys:
values.append('%s: %s' % (repr(key), repr(d.get(key))))
if '\n' in name:
name = repr(name)
return name + ': {' + ', '.join(values) + '}' | [
"def",
"nodeinfo_raw",
"(",
"name",
",",
"ninfo",
",",
"prefix",
"=",
"\"\"",
")",
":",
"d",
"=",
"ninfo",
".",
"__getstate__",
"(",
")",
"try",
":",
"keys",
"=",
"ninfo",
".",
"field_list",
"+",
"[",
"'_version_id'",
"]",
"except",
"AttributeError",
"... | https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Utilities/sconsign.py#L198-L213 | |
eventql/eventql | 7ca0dbb2e683b525620ea30dc40540a22d5eb227 | deps/3rdparty/spidermonkey/mozjs/python/mock-1.0.0/mock.py | python | MagicMock.mock_add_spec | (self, spec, spec_set=False) | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set. | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock. | [
"Add",
"a",
"spec",
"to",
"a",
"mock",
".",
"spec",
"can",
"either",
"be",
"an",
"object",
"or",
"a",
"list",
"of",
"strings",
".",
"Only",
"attributes",
"on",
"the",
"spec",
"can",
"be",
"fetched",
"as",
"attributes",
"from",
"the",
"mock",
"."
] | def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
self._mock_set_magics() | [
"def",
"mock_add_spec",
"(",
"self",
",",
"spec",
",",
"spec_set",
"=",
"False",
")",
":",
"self",
".",
"_mock_add_spec",
"(",
"spec",
",",
"spec_set",
")",
"self",
".",
"_mock_set_magics",
"(",
")"
] | https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/mock-1.0.0/mock.py#L1890-L1897 | ||
google/tink | 59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14 | python/tink/cleartext_keyset_handle.py | python | read | (keyset_reader: tink.KeysetReader) | return tink.KeysetHandle._create(keyset) | Create a KeysetHandle from a keyset_reader. | Create a KeysetHandle from a keyset_reader. | [
"Create",
"a",
"KeysetHandle",
"from",
"a",
"keyset_reader",
"."
] | def read(keyset_reader: tink.KeysetReader) -> tink.KeysetHandle:
"""Create a KeysetHandle from a keyset_reader."""
keyset = keyset_reader.read()
return tink.KeysetHandle._create(keyset) | [
"def",
"read",
"(",
"keyset_reader",
":",
"tink",
".",
"KeysetReader",
")",
"->",
"tink",
".",
"KeysetHandle",
":",
"keyset",
"=",
"keyset_reader",
".",
"read",
"(",
")",
"return",
"tink",
".",
"KeysetHandle",
".",
"_create",
"(",
"keyset",
")"
] | https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/cleartext_keyset_handle.py#L32-L35 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/bisect.py | python | bisect_right | (a, x, lo=0, hi=None) | return lo | Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched. | Return the index where to insert item x in list a, assuming a is sorted. | [
"Return",
"the",
"index",
"where",
"to",
"insert",
"item",
"x",
"in",
"list",
"a",
"assuming",
"a",
"is",
"sorted",
"."
] | def bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted.
The return value i is such that all e in a[:i] have e <= x, and all e in
a[i:] have e > x. So if x already appears in the list, a.insert(x) will
insert just after the rightmost x already there.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo | [
"def",
"bisect_right",
"(",
"a",
",",
"x",
",",
"lo",
"=",
"0",
",",
"hi",
"=",
"None",
")",
":",
"if",
"lo",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'lo must be non-negative'",
")",
"if",
"hi",
"is",
"None",
":",
"hi",
"=",
"len",
"(",
"a",
... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/bisect.py#L24-L43 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_main.py | python | MainWindow.OnMaximizeEditor | (self, evt) | Maximize the editor and hide the other panes. If the editor
is already maximized, it is un-maximized and the other panes are restored
@param evt: CommandEvent instance | Maximize the editor and hide the other panes. If the editor
is already maximized, it is un-maximized and the other panes are restored
@param evt: CommandEvent instance | [
"Maximize",
"the",
"editor",
"and",
"hide",
"the",
"other",
"panes",
".",
"If",
"the",
"editor",
"is",
"already",
"maximized",
"it",
"is",
"un",
"-",
"maximized",
"and",
"the",
"other",
"panes",
"are",
"restored",
"@param",
"evt",
":",
"CommandEvent",
"ins... | def OnMaximizeEditor(self, evt):
"""Maximize the editor and hide the other panes. If the editor
is already maximized, it is un-maximized and the other panes are restored
@param evt: CommandEvent instance
"""
paneInfo = self.PanelMgr.GetPane("EditPane")
if self.PanelMgr.IsEditorMaximized():
self.PanelMgr.RestorePane(paneInfo)
ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_RESTORE, context=self.GetId())
else:
self.PanelMgr.MaximizePane(paneInfo)
self.PanelMgr.Update() | [
"def",
"OnMaximizeEditor",
"(",
"self",
",",
"evt",
")",
":",
"paneInfo",
"=",
"self",
".",
"PanelMgr",
".",
"GetPane",
"(",
"\"EditPane\"",
")",
"if",
"self",
".",
"PanelMgr",
".",
"IsEditorMaximized",
"(",
")",
":",
"self",
".",
"PanelMgr",
".",
"Resto... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_main.py#L1028-L1040 | ||
waymo-research/waymo-open-dataset | 5de359f3429e1496761790770868296140161b66 | waymo_open_dataset/metrics/ops/py_metrics_ops.py | python | detection_metrics | (prediction_bbox,
prediction_type,
prediction_score,
prediction_frame_id,
prediction_overlap_nlz,
ground_truth_bbox,
ground_truth_type,
ground_truth_frame_id,
ground_truth_difficulty,
config,
ground_truth_speed=None) | return metrics_module.detection_metrics(
prediction_bbox=prediction_bbox,
prediction_type=prediction_type,
prediction_score=prediction_score,
prediction_frame_id=prediction_frame_id,
prediction_overlap_nlz=prediction_overlap_nlz,
ground_truth_bbox=ground_truth_bbox,
ground_truth_type=ground_truth_type,
ground_truth_frame_id=ground_truth_frame_id,
ground_truth_difficulty=ground_truth_difficulty,
ground_truth_speed=ground_truth_speed,
config=config) | Wraps detection_metrics. See metrics_ops.cc for full documentation. | Wraps detection_metrics. See metrics_ops.cc for full documentation. | [
"Wraps",
"detection_metrics",
".",
"See",
"metrics_ops",
".",
"cc",
"for",
"full",
"documentation",
"."
] | def detection_metrics(prediction_bbox,
prediction_type,
prediction_score,
prediction_frame_id,
prediction_overlap_nlz,
ground_truth_bbox,
ground_truth_type,
ground_truth_frame_id,
ground_truth_difficulty,
config,
ground_truth_speed=None):
"""Wraps detection_metrics. See metrics_ops.cc for full documentation."""
if ground_truth_speed is None:
num_gt_boxes = tf.shape(ground_truth_bbox)[0]
ground_truth_speed = tf.zeros((num_gt_boxes, 2), dtype=tf.float32)
return metrics_module.detection_metrics(
prediction_bbox=prediction_bbox,
prediction_type=prediction_type,
prediction_score=prediction_score,
prediction_frame_id=prediction_frame_id,
prediction_overlap_nlz=prediction_overlap_nlz,
ground_truth_bbox=ground_truth_bbox,
ground_truth_type=ground_truth_type,
ground_truth_frame_id=ground_truth_frame_id,
ground_truth_difficulty=ground_truth_difficulty,
ground_truth_speed=ground_truth_speed,
config=config) | [
"def",
"detection_metrics",
"(",
"prediction_bbox",
",",
"prediction_type",
",",
"prediction_score",
",",
"prediction_frame_id",
",",
"prediction_overlap_nlz",
",",
"ground_truth_bbox",
",",
"ground_truth_type",
",",
"ground_truth_frame_id",
",",
"ground_truth_difficulty",
",... | https://github.com/waymo-research/waymo-open-dataset/blob/5de359f3429e1496761790770868296140161b66/waymo_open_dataset/metrics/ops/py_metrics_ops.py#L27-L54 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | build/android/android_commands.py | python | GetEmulators | () | return devices | Returns a list of emulators. Does not filter by status (e.g. offline).
Both devices starting with 'emulator' will be returned in below output:
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
027c10494100b4d7 device
emulator-5554 offline
emulator-5558 device | Returns a list of emulators. Does not filter by status (e.g. offline). | [
"Returns",
"a",
"list",
"of",
"emulators",
".",
"Does",
"not",
"filter",
"by",
"status",
"(",
"e",
".",
"g",
".",
"offline",
")",
"."
] | def GetEmulators():
"""Returns a list of emulators. Does not filter by status (e.g. offline).
Both devices starting with 'emulator' will be returned in below output:
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
027c10494100b4d7 device
emulator-5554 offline
emulator-5558 device
"""
re_device = re.compile('^emulator-[0-9]+', re.MULTILINE)
devices = re_device.findall(cmd_helper.GetCmdOutput(['adb', 'devices']))
return devices | [
"def",
"GetEmulators",
"(",
")",
":",
"re_device",
"=",
"re",
".",
"compile",
"(",
"'^emulator-[0-9]+'",
",",
"re",
".",
"MULTILINE",
")",
"devices",
"=",
"re_device",
".",
"findall",
"(",
"cmd_helper",
".",
"GetCmdOutput",
"(",
"[",
"'adb'",
",",
"'device... | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/android_commands.py#L65-L79 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/shape_base.py | python | dsplit | (ary, indices_or_sections) | return split(ary, indices_or_sections, 2) | Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the `split` documentation. `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or equal to 3.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[12., 13., 14., 15.]]])
>>> np.dsplit(x, 2)
[array([[[ 0., 1.],
[ 4., 5.]],
[[ 8., 9.],
[12., 13.]]]), array([[[ 2., 3.],
[ 6., 7.]],
[[10., 11.],
[14., 15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
[[ 8., 9., 10.],
[12., 13., 14.]]]),
array([[[ 3.],
[ 7.]],
[[11.],
[15.]]]),
array([], shape=(2, 2, 0), dtype=float64)] | Split array into multiple sub-arrays along the 3rd axis (depth). | [
"Split",
"array",
"into",
"multiple",
"sub",
"-",
"arrays",
"along",
"the",
"3rd",
"axis",
"(",
"depth",
")",
"."
] | def dsplit(ary, indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the `split` documentation. `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or equal to 3.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[12., 13., 14., 15.]]])
>>> np.dsplit(x, 2)
[array([[[ 0., 1.],
[ 4., 5.]],
[[ 8., 9.],
[12., 13.]]]), array([[[ 2., 3.],
[ 6., 7.]],
[[10., 11.],
[14., 15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
[[ 8., 9., 10.],
[12., 13., 14.]]]),
array([[[ 3.],
[ 7.]],
[[11.],
[15.]]]),
array([], shape=(2, 2, 0), dtype=float64)]
"""
if _nx.ndim(ary) < 3:
raise ValueError('dsplit only works on arrays of 3 or more dimensions')
return split(ary, indices_or_sections, 2) | [
"def",
"dsplit",
"(",
"ary",
",",
"indices_or_sections",
")",
":",
"if",
"_nx",
".",
"ndim",
"(",
"ary",
")",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"'dsplit only works on arrays of 3 or more dimensions'",
")",
"return",
"split",
"(",
"ary",
",",
"indices_... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/shape_base.py#L993-L1034 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/mailbox.py | python | MH.__len__ | (self) | return len(list(self.iterkeys())) | Return a count of messages in the mailbox. | Return a count of messages in the mailbox. | [
"Return",
"a",
"count",
"of",
"messages",
"in",
"the",
"mailbox",
"."
] | def __len__(self):
"""Return a count of messages in the mailbox."""
return len(list(self.iterkeys())) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"list",
"(",
"self",
".",
"iterkeys",
"(",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L1074-L1076 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Pygments/py3/pygments/formatters/img.py | python | ImageFormatter._get_text_color | (self, style) | return fill | Get the correct color for the token from the style. | Get the correct color for the token from the style. | [
"Get",
"the",
"correct",
"color",
"for",
"the",
"token",
"from",
"the",
"style",
"."
] | def _get_text_color(self, style):
"""
Get the correct color for the token from the style.
"""
if style['color'] is not None:
fill = '#' + style['color']
else:
fill = '#000'
return fill | [
"def",
"_get_text_color",
"(",
"self",
",",
"style",
")",
":",
"if",
"style",
"[",
"'color'",
"]",
"is",
"not",
"None",
":",
"fill",
"=",
"'#'",
"+",
"style",
"[",
"'color'",
"]",
"else",
":",
"fill",
"=",
"'#000'",
"return",
"fill"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/formatters/img.py#L445-L453 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/html.py | python | HtmlParser.PushTagHandler | (*args, **kwargs) | return _html.HtmlParser_PushTagHandler(*args, **kwargs) | PushTagHandler(self, HtmlTagHandler handler, String tags) | PushTagHandler(self, HtmlTagHandler handler, String tags) | [
"PushTagHandler",
"(",
"self",
"HtmlTagHandler",
"handler",
"String",
"tags",
")"
] | def PushTagHandler(*args, **kwargs):
"""PushTagHandler(self, HtmlTagHandler handler, String tags)"""
return _html.HtmlParser_PushTagHandler(*args, **kwargs) | [
"def",
"PushTagHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_html",
".",
"HtmlParser_PushTagHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L217-L219 | |
coinapi/coinapi-sdk | 854f21e7f69ea8599ae35c5403565cf299d8b795 | oeml-sdk/python/openapi_client/model/ord_status.py | python | OrdStatus._from_openapi_data | (cls, *args, **kwargs) | return self | OrdStatus - a model defined in OpenAPI
Note that value can be passed either in args or in kwargs, but not in both.
Args:
args[0] (str): Order statuses and the lifecycle are documented in the separate section: <a href=\"#oeml-order-lifecycle\">OEML / Starter Guide / Order Lifecycle</a> ., must be one of ["RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED", ] # noqa: E501
Keyword Args:
value (str): Order statuses and the lifecycle are documented in the separate section: <a href=\"#oeml-order-lifecycle\">OEML / Starter Guide / Order Lifecycle</a> ., must be one of ["RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED", ] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,) | OrdStatus - a model defined in OpenAPI | [
"OrdStatus",
"-",
"a",
"model",
"defined",
"in",
"OpenAPI"
] | def _from_openapi_data(cls, *args, **kwargs):
"""OrdStatus - a model defined in OpenAPI
Note that value can be passed either in args or in kwargs, but not in both.
Args:
args[0] (str): Order statuses and the lifecycle are documented in the separate section: <a href=\"#oeml-order-lifecycle\">OEML / Starter Guide / Order Lifecycle</a> ., must be one of ["RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED", ] # noqa: E501
Keyword Args:
value (str): Order statuses and the lifecycle are documented in the separate section: <a href=\"#oeml-order-lifecycle\">OEML / Starter Guide / Order Lifecycle</a> ., must be one of ["RECEIVED", "ROUTING", "ROUTED", "NEW", "PENDING_CANCEL", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED", ] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
"""
# required up here when default value is not given
_path_to_item = kwargs.pop('_path_to_item', ())
self = super(OpenApiModel, cls).__new__(cls)
if 'value' in kwargs:
value = kwargs.pop('value')
elif args:
args = list(args)
value = args.pop(0)
else:
raise ApiTypeError(
"value is required, but not passed in args or kwargs and doesn't have default",
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.value = value
if kwargs:
raise ApiTypeError(
"Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % (
kwargs,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
return self | [
"def",
"_from_openapi_data",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# required up here when default value is not given",
"_path_to_item",
"=",
"kwargs",
".",
"pop",
"(",
"'_path_to_item'",
",",
"(",
")",
")",
"self",
"=",
"super",
"(... | https://github.com/coinapi/coinapi-sdk/blob/854f21e7f69ea8599ae35c5403565cf299d8b795/oeml-sdk/python/openapi_client/model/ord_status.py#L200-L290 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Rect2D.MoveLeftTopTo | (*args, **kwargs) | return _core_.Rect2D_MoveLeftTopTo(*args, **kwargs) | MoveLeftTopTo(self, Point2D pt) | MoveLeftTopTo(self, Point2D pt) | [
"MoveLeftTopTo",
"(",
"self",
"Point2D",
"pt",
")"
] | def MoveLeftTopTo(*args, **kwargs):
"""MoveLeftTopTo(self, Point2D pt)"""
return _core_.Rect2D_MoveLeftTopTo(*args, **kwargs) | [
"def",
"MoveLeftTopTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect2D_MoveLeftTopTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1911-L1913 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py | python | Menu.invoke | (self, index) | return self.tk.call(self._w, 'invoke', index) | Invoke a menu item identified by INDEX and execute
the associated command. | Invoke a menu item identified by INDEX and execute
the associated command. | [
"Invoke",
"a",
"menu",
"item",
"identified",
"by",
"INDEX",
"and",
"execute",
"the",
"associated",
"command",
"."
] | def invoke(self, index):
"""Invoke a menu item identified by INDEX and execute
the associated command."""
return self.tk.call(self._w, 'invoke', index) | [
"def",
"invoke",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"tk",
".",
"call",
"(",
"self",
".",
"_w",
",",
"'invoke'",
",",
"index",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2736-L2739 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/array_ops.py | python | broadcast_dynamic_shape | (shape_x, shape_y) | return gen_array_ops.broadcast_args(shape_x, shape_y) | Computes the shape of a broadcast given symbolic shapes.
When `shape_x` and `shape_y` are Tensors representing shapes (i.e. the result
of calling tf.shape on another Tensor) this computes a Tensor which is the
shape of the result of a broadcasting op applied in tensors of shapes
`shape_x` and `shape_y`.
This is useful when validating the result of a broadcasting operation when the
tensors do not have statically known shapes.
Example:
>>> shape_x = (1, 2, 3)
>>> shape_y = (5, 1, 3)
>>> tf.broadcast_dynamic_shape(shape_x, shape_y)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([5, 2, 3], ...>
Args:
shape_x: A rank 1 integer `Tensor`, representing the shape of x.
shape_y: A rank 1 integer `Tensor`, representing the shape of y.
Returns:
A rank 1 integer `Tensor` representing the broadcasted shape.
Raises:
InvalidArgumentError: If the two shapes are incompatible for
broadcasting. | Computes the shape of a broadcast given symbolic shapes. | [
"Computes",
"the",
"shape",
"of",
"a",
"broadcast",
"given",
"symbolic",
"shapes",
"."
] | def broadcast_dynamic_shape(shape_x, shape_y):
"""Computes the shape of a broadcast given symbolic shapes.
When `shape_x` and `shape_y` are Tensors representing shapes (i.e. the result
of calling tf.shape on another Tensor) this computes a Tensor which is the
shape of the result of a broadcasting op applied in tensors of shapes
`shape_x` and `shape_y`.
This is useful when validating the result of a broadcasting operation when the
tensors do not have statically known shapes.
Example:
>>> shape_x = (1, 2, 3)
>>> shape_y = (5, 1, 3)
>>> tf.broadcast_dynamic_shape(shape_x, shape_y)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([5, 2, 3], ...>
Args:
shape_x: A rank 1 integer `Tensor`, representing the shape of x.
shape_y: A rank 1 integer `Tensor`, representing the shape of y.
Returns:
A rank 1 integer `Tensor` representing the broadcasted shape.
Raises:
InvalidArgumentError: If the two shapes are incompatible for
broadcasting.
"""
return gen_array_ops.broadcast_args(shape_x, shape_y) | [
"def",
"broadcast_dynamic_shape",
"(",
"shape_x",
",",
"shape_y",
")",
":",
"return",
"gen_array_ops",
".",
"broadcast_args",
"(",
"shape_x",
",",
"shape_y",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/array_ops.py#L513-L542 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/models.py | python | _reverse_seq | (input_seq, lengths) | return result | Reverse a list of Tensors up to specified lengths.
Args:
input_seq: Sequence of seq_len tensors of dimension (batch_size, depth)
lengths: A tensor of dimension batch_size, containing lengths for each
sequence in the batch. If "None" is specified, simply
reverses the list.
Returns:
time-reversed sequence | Reverse a list of Tensors up to specified lengths. | [
"Reverse",
"a",
"list",
"of",
"Tensors",
"up",
"to",
"specified",
"lengths",
"."
] | def _reverse_seq(input_seq, lengths):
"""Reverse a list of Tensors up to specified lengths.
Args:
input_seq: Sequence of seq_len tensors of dimension (batch_size, depth)
lengths: A tensor of dimension batch_size, containing lengths for each
sequence in the batch. If "None" is specified, simply
reverses the list.
Returns:
time-reversed sequence
"""
if lengths is None:
return list(reversed(input_seq))
for input_ in input_seq:
input_.set_shape(input_.get_shape().with_rank(2))
# Join into (time, batch_size, depth)
s_joined = array_ops_.pack(input_seq)
# Reverse along dimension 0
s_reversed = array_ops_.reverse_sequence(s_joined, lengths, 0, 1)
# Split again into list
result = array_ops_.unpack(s_reversed)
return result | [
"def",
"_reverse_seq",
"(",
"input_seq",
",",
"lengths",
")",
":",
"if",
"lengths",
"is",
"None",
":",
"return",
"list",
"(",
"reversed",
"(",
"input_seq",
")",
")",
"for",
"input_",
"in",
"input_seq",
":",
"input_",
".",
"set_shape",
"(",
"input_",
".",... | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/models.py#L238-L263 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | src/mem/slicc/parser.py | python | SLICC.p_expr__localvar | (self, p) | aexpr : type ident | aexpr : type ident | [
"aexpr",
":",
"type",
"ident"
] | def p_expr__localvar(self, p):
"aexpr : type ident"
p[0] = ast.LocalVariableAST(self, p[1], p[2]) | [
"def",
"p_expr__localvar",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"LocalVariableAST",
"(",
"self",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L677-L679 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | Validation/RecoTrack/python/plotting/plotting.py | python | AggregateBins.create | (self, tdirectory) | return result | Create and return the histogram from a TDirectory | Create and return the histogram from a TDirectory | [
"Create",
"and",
"return",
"the",
"histogram",
"from",
"a",
"TDirectory"
] | def create(self, tdirectory):
"""Create and return the histogram from a TDirectory"""
th1 = _getOrCreateObject(tdirectory, self._histoName)
if th1 is None:
return None
binLabels = [""]*len(self._mapping)
binValues = [None]*len(self._mapping)
# TH1 can't really be used as a map/dict, so convert it here:
values = _th1ToOrderedDict(th1, self._renameBin)
binIndexOrder = [] # for reordering bins if self._originalOrder is True
for i, (key, labels) in enumerate(self._mapping.items()):
sumTime = 0.
sumErrorSq = 0.
nsum = 0
for l in labels:
try:
sumTime += values[l][0]
sumErrorSq += values[l][1]**2
nsum += 1
except KeyError:
pass
if nsum > 0:
binValues[i] = (sumTime, math.sqrt(sumErrorSq))
binLabels[i] = key
ivalue = len(values)+1
if len(labels) > 0:
# first label doesn't necessarily exist (especially for
# the iteration timing plots), so let's test them all
for lab in labels:
if lab in values:
ivalue = list(values.keys()).index(lab)
break
binIndexOrder.append( (ivalue, i) )
if self._originalOrder:
binIndexOrder.sort(key=lambda t: t[0])
tmpVal = []
tmpLab = []
for i in range(0, len(binValues)):
fromIndex = binIndexOrder[i][1]
tmpVal.append(binValues[fromIndex])
tmpLab.append(binLabels[fromIndex])
binValues = tmpVal
binLabels = tmpLab
if self._reorder is not None:
order = self._reorder(tdirectory, binLabels)
binValues = [binValues[i] for i in order]
binLabels = [binLabels[i] for i in order]
if self._minExistingBins is not None and (len(binValues)-binValues.count(None)) < self._minExistingBins:
return None
if self._ignoreMissingBins:
for i, val in enumerate(binValues):
if val is None:
binLabels[i] = None
binValues = [v for v in binValues if v is not None]
binLabels = [v for v in binLabels if v is not None]
if len(binValues) == 0:
return None
result = ROOT.TH1F(self._name, self._name, len(binValues), 0, len(binValues))
for i, (value, label) in enumerate(zip(binValues, binLabels)):
if value is not None:
result.SetBinContent(i+1, value[0])
result.SetBinError(i+1, value[1])
result.GetXaxis().SetBinLabel(i+1, label)
if self._normalizeTo is not None:
bin = th1.GetXaxis().FindBin(self._normalizeTo)
if bin <= 0:
print("Trying to normalize {name} to {binlabel}, which does not exist".format(name=self._name, binlabel=self._normalizeTo))
sys.exit(1)
value = th1.GetBinContent(bin)
if value != 0:
result.Scale(1/value)
if self._scale is not None:
result.Scale(self._scale)
return result | [
"def",
"create",
"(",
"self",
",",
"tdirectory",
")",
":",
"th1",
"=",
"_getOrCreateObject",
"(",
"tdirectory",
",",
"self",
".",
"_histoName",
")",
"if",
"th1",
"is",
"None",
":",
"return",
"None",
"binLabels",
"=",
"[",
"\"\"",
"]",
"*",
"len",
"(",
... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/plotting.py#L988-L1073 | |
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/wesnoth/wmldata.py | python | DataSub.set_comment_first | (self, comment) | For the lazy. | For the lazy. | [
"For",
"the",
"lazy",
"."
] | def set_comment_first(self, comment):
"""For the lazy."""
for item in self.get_all("comment"):
if isinstance(item, DataComment):
if item.data == comment: return
self.insert_first(DataComment("comment", comment)) | [
"def",
"set_comment_first",
"(",
"self",
",",
"comment",
")",
":",
"for",
"item",
"in",
"self",
".",
"get_all",
"(",
"\"comment\"",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"DataComment",
")",
":",
"if",
"item",
".",
"data",
"==",
"comment",
":"... | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmldata.py#L565-L571 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py | python | MaskedArray.__radd__ | (self, other) | return add(other, self) | Add other to self, and return a new masked array. | Add other to self, and return a new masked array. | [
"Add",
"other",
"to",
"self",
"and",
"return",
"a",
"new",
"masked",
"array",
"."
] | def __radd__(self, other):
"""
Add other to self, and return a new masked array.
"""
# In analogy with __rsub__ and __rdiv__, use original order:
# we get here from `other + self`.
return add(other, self) | [
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"# In analogy with __rsub__ and __rdiv__, use original order:",
"# we get here from `other + self`.",
"return",
"add",
"(",
"other",
",",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L4101-L4108 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/control/robotinterfaceutils.py | python | RobotInterfaceEmulator.initialize | (self,qsns,vsns,tsns,qcmd,vcmd,tcmd) | Could be called before the emulator starts running to initialize the
commanded joint positions before the emulator takes over. | Could be called before the emulator starts running to initialize the
commanded joint positions before the emulator takes over. | [
"Could",
"be",
"called",
"before",
"the",
"emulator",
"starts",
"running",
"to",
"initialize",
"the",
"commanded",
"joint",
"positions",
"before",
"the",
"emulator",
"takes",
"over",
"."
] | def initialize(self,qsns,vsns,tsns,qcmd,vcmd,tcmd):
"""Could be called before the emulator starts running to initialize the
commanded joint positions before the emulator takes over.
"""
assert qcmd is None or len(qcmd) == len(self.jointData)
assert vcmd is None or len(vcmd) == len(self.jointData)
assert tcmd is None or len(tcmd) == len(self.jointData)
self.numUpdates = 0
for i,j in enumerate(self.jointData):
j.sensedPosition = qsns[i]
j.sensedVelocity = 0 if vsns is None else vsns[i]
#j.sensedTorque = None if tsns is None else tsns[i]
if qcmd is not None:
j.commandedPosition = qcmd[i]
else:
j.commandedPosition = qsns[i]
if vcmd is not None:
j.commandedVelocity = vcmd[i]
else:
j.commandedVelocity = 0
if tcmd is not None and tcmd[i] is not None:
j.commandedTorque = tcmd[i]
else:
j.commandedTorque = 0 | [
"def",
"initialize",
"(",
"self",
",",
"qsns",
",",
"vsns",
",",
"tsns",
",",
"qcmd",
",",
"vcmd",
",",
"tcmd",
")",
":",
"assert",
"qcmd",
"is",
"None",
"or",
"len",
"(",
"qcmd",
")",
"==",
"len",
"(",
"self",
".",
"jointData",
")",
"assert",
"v... | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterfaceutils.py#L4225-L4248 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/session.py | python | PipSession.__init__ | (self, *args, **kwargs) | :param trusted_hosts: Domains not to emit warnings for when not using
HTTPS. | :param trusted_hosts: Domains not to emit warnings for when not using
HTTPS. | [
":",
"param",
"trusted_hosts",
":",
"Domains",
"not",
"to",
"emit",
"warnings",
"for",
"when",
"not",
"using",
"HTTPS",
"."
] | def __init__(self, *args, **kwargs):
"""
:param trusted_hosts: Domains not to emit warnings for when not using
HTTPS.
"""
retries = kwargs.pop("retries", 0)
cache = kwargs.pop("cache", None)
trusted_hosts = kwargs.pop("trusted_hosts", []) # type: List[str]
index_urls = kwargs.pop("index_urls", None)
super().__init__(*args, **kwargs)
# Namespace the attribute with "pip_" just in case to prevent
# possible conflicts with the base class.
self.pip_trusted_origins = [] # type: List[Tuple[str, Optional[int]]]
# Attach our User Agent to the request
self.headers["User-Agent"] = user_agent()
# Attach our Authentication handler to the session
self.auth = MultiDomainBasicAuth(index_urls=index_urls)
# Create our urllib3.Retry instance which will allow us to customize
# how we handle retries.
retries = urllib3.Retry(
# Set the total number of retries that a particular request can
# have.
total=retries,
# A 503 error from PyPI typically means that the Fastly -> Origin
# connection got interrupted in some way. A 503 error in general
# is typically considered a transient error so we'll go ahead and
# retry it.
# A 500 may indicate transient error in Amazon S3
# A 520 or 527 - may indicate transient error in CloudFlare
status_forcelist=[500, 503, 520, 527],
# Add a small amount of back off between failed requests in
# order to prevent hammering the service.
backoff_factor=0.25,
)
# Our Insecure HTTPAdapter disables HTTPS validation. It does not
# support caching so we'll use it for all http:// URLs.
# If caching is disabled, we will also use it for
# https:// hosts that we've marked as ignoring
# TLS errors for (trusted-hosts).
insecure_adapter = InsecureHTTPAdapter(max_retries=retries)
# We want to _only_ cache responses on securely fetched origins or when
# the host is specified as trusted. We do this because
# we can't validate the response of an insecurely/untrusted fetched
# origin, and we don't want someone to be able to poison the cache and
# require manual eviction from the cache to fix it.
if cache:
secure_adapter = CacheControlAdapter(
cache=SafeFileCache(cache),
max_retries=retries,
)
self._trusted_host_adapter = InsecureCacheControlAdapter(
cache=SafeFileCache(cache),
max_retries=retries,
)
else:
secure_adapter = HTTPAdapter(max_retries=retries)
self._trusted_host_adapter = insecure_adapter
self.mount("https://", secure_adapter)
self.mount("http://", insecure_adapter)
# Enable file:// urls
self.mount("file://", LocalFSAdapter())
for host in trusted_hosts:
self.add_trusted_host(host, suppress_logging=True) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"retries",
"=",
"kwargs",
".",
"pop",
"(",
"\"retries\"",
",",
"0",
")",
"cache",
"=",
"kwargs",
".",
"pop",
"(",
"\"cache\"",
",",
"None",
")",
"trusted_hosts",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/network/session.py#L228-L302 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/nn/functional/pooling.py | python | adaptive_avg_pool1d | (x, output_size, name=None) | return squeeze(pool_out, [2]) | This API implements adaptive average pooling 1d operation.
See more details in :ref:`api_nn_pooling_AdaptiveAvgPool1d` .
Args:
x (Tensor): The input tensor of pooling operator, which is a 3-D tensor
with shape [N, C, L]. The format of input tensor is NCL,
where N is batch size, C is the number of channels, L is the
length of the feature. The data type is float32 or float64.
output_size (int): The target output size. It must be an integer.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tensor: The output tensor of adaptive average pooling result. The data type is same
as input tensor.
Raises:
ValueError: 'output_size' should be an integer.
Examples:
.. code-block:: python
# average adaptive pool1d
# suppose input data in shape of [N, C, L], `output_size` is m or [m],
# output shape is [N, C, m], adaptive pool divide L dimension
# of input data into m grids averagely and performs poolings in each
# grid to get output.
# adaptive max pool performs calculations as follow:
#
# for i in range(m):
# lstart = floor(i * L / m)
# lend = ceil((i + 1) * L / m)
# output[:, :, i] = sum(input[:, :, lstart: lend])/(lstart - lend)
#
import paddle
import paddle.nn.functional as F
import numpy as np
data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32))
pool_out = F.adaptive_average_pool1d(data, output_size=16)
# pool_out shape: [1, 3, 16]) | This API implements adaptive average pooling 1d operation.
See more details in :ref:`api_nn_pooling_AdaptiveAvgPool1d` . | [
"This",
"API",
"implements",
"adaptive",
"average",
"pooling",
"1d",
"operation",
".",
"See",
"more",
"details",
"in",
":",
"ref",
":",
"api_nn_pooling_AdaptiveAvgPool1d",
"."
] | def adaptive_avg_pool1d(x, output_size, name=None):
"""
This API implements adaptive average pooling 1d operation.
See more details in :ref:`api_nn_pooling_AdaptiveAvgPool1d` .
Args:
x (Tensor): The input tensor of pooling operator, which is a 3-D tensor
with shape [N, C, L]. The format of input tensor is NCL,
where N is batch size, C is the number of channels, L is the
length of the feature. The data type is float32 or float64.
output_size (int): The target output size. It must be an integer.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tensor: The output tensor of adaptive average pooling result. The data type is same
as input tensor.
Raises:
ValueError: 'output_size' should be an integer.
Examples:
.. code-block:: python
# average adaptive pool1d
# suppose input data in shape of [N, C, L], `output_size` is m or [m],
# output shape is [N, C, m], adaptive pool divide L dimension
# of input data into m grids averagely and performs poolings in each
# grid to get output.
# adaptive max pool performs calculations as follow:
#
# for i in range(m):
# lstart = floor(i * L / m)
# lend = ceil((i + 1) * L / m)
# output[:, :, i] = sum(input[:, :, lstart: lend])/(lstart - lend)
#
import paddle
import paddle.nn.functional as F
import numpy as np
data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32))
pool_out = F.adaptive_average_pool1d(data, output_size=16)
# pool_out shape: [1, 3, 16])
"""
pool_type = 'avg'
if not in_dygraph_mode():
check_variable_and_dtype(x, 'x', ['float16', 'float32', 'float64'],
'adaptive_pool2d')
check_type(output_size, 'pool_size', (int), 'adaptive_pool1d')
_check_input(x, 3)
pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size')
x = unsqueeze(x, [2])
if in_dygraph_mode():
pool_out = _C_ops.pool2d(x, 'pooling_type', pool_type, 'ksize',
pool_size, 'adaptive', True)
return squeeze(pool_out, [2])
l_type = "pool2d"
helper = LayerHelper(l_type, **locals())
dtype = helper.input_dtype(input_param_name='x')
pool_out = helper.create_variable_for_type_inference(dtype)
outputs = {"Out": pool_out}
helper.append_op(
type=l_type,
inputs={"X": x},
outputs=outputs,
attrs={
"pooling_type": pool_type,
"ksize": pool_size,
"adaptive": True,
})
return squeeze(pool_out, [2]) | [
"def",
"adaptive_avg_pool1d",
"(",
"x",
",",
"output_size",
",",
"name",
"=",
"None",
")",
":",
"pool_type",
"=",
"'avg'",
"if",
"not",
"in_dygraph_mode",
"(",
")",
":",
"check_variable_and_dtype",
"(",
"x",
",",
"'x'",
",",
"[",
"'float16'",
",",
"'float3... | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/functional/pooling.py#L1210-L1283 | |
sigmaai/self-driving-golf-cart | 8d891600af3d851add27a10ae45cf3c2108bb87c | ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/collision_sensor.py | python | CollisionSensor.__init__ | (self, carla_actor, parent, communication, synchronous_mode) | Constructor
:param carla_actor: carla actor object
:type carla_actor: carla.Actor
:param parent: the parent of this
:type parent: carla_ros_bridge.Parent
:param communication: communication-handle
:type communication: carla_ros_bridge.communication
:param synchronous_mode: use in synchronous mode?
:type synchronous_mode: bool | Constructor | [
"Constructor"
] | def __init__(self, carla_actor, parent, communication, synchronous_mode):
"""
Constructor
:param carla_actor: carla actor object
:type carla_actor: carla.Actor
:param parent: the parent of this
:type parent: carla_ros_bridge.Parent
:param communication: communication-handle
:type communication: carla_ros_bridge.communication
:param synchronous_mode: use in synchronous mode?
:type synchronous_mode: bool
"""
super(CollisionSensor, self).__init__(carla_actor=carla_actor,
parent=parent,
communication=communication,
synchronous_mode=synchronous_mode,
is_event_sensor=True,
prefix="collision") | [
"def",
"__init__",
"(",
"self",
",",
"carla_actor",
",",
"parent",
",",
"communication",
",",
"synchronous_mode",
")",
":",
"super",
"(",
"CollisionSensor",
",",
"self",
")",
".",
"__init__",
"(",
"carla_actor",
"=",
"carla_actor",
",",
"parent",
"=",
"paren... | https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/collision_sensor.py#L23-L41 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/jedi/jedi/refactoring.py | python | Refactoring.__init__ | (self, change_dct) | :param change_dct: dict(old_path=(new_path, old_lines, new_lines)) | :param change_dct: dict(old_path=(new_path, old_lines, new_lines)) | [
":",
"param",
"change_dct",
":",
"dict",
"(",
"old_path",
"=",
"(",
"new_path",
"old_lines",
"new_lines",
"))"
] | def __init__(self, change_dct):
"""
:param change_dct: dict(old_path=(new_path, old_lines, new_lines))
"""
self.change_dct = change_dct | [
"def",
"__init__",
"(",
"self",
",",
"change_dct",
")",
":",
"self",
".",
"change_dct",
"=",
"change_dct"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/jedi/jedi/refactoring.py#L25-L29 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | build/win/reorder-imports.py | python | reorder_imports | (input_dir, output_dir, architecture) | return 0 | Run swapimports.exe on the initial chrome.exe, and write to the output
directory. Also copy over any related files that might be needed
(pdbs, manifests etc.). | Run swapimports.exe on the initial chrome.exe, and write to the output
directory. Also copy over any related files that might be needed
(pdbs, manifests etc.). | [
"Run",
"swapimports",
".",
"exe",
"on",
"the",
"initial",
"chrome",
".",
"exe",
"and",
"write",
"to",
"the",
"output",
"directory",
".",
"Also",
"copy",
"over",
"any",
"related",
"files",
"that",
"might",
"be",
"needed",
"(",
"pdbs",
"manifests",
"etc",
... | def reorder_imports(input_dir, output_dir, architecture):
"""Run swapimports.exe on the initial chrome.exe, and write to the output
directory. Also copy over any related files that might be needed
(pdbs, manifests etc.).
"""
input_image = os.path.join(input_dir, 'chrome.exe')
output_image = os.path.join(output_dir, 'chrome.exe')
swap_exe = os.path.join(
__file__,
'..\\..\\..\\third_party\\syzygy\\binaries\\exe\\swapimport.exe')
args = [swap_exe, '--input-image=%s' % input_image,
'--output-image=%s' % output_image, '--overwrite', '--no-logo']
if architecture == 'x64':
args.append('--x64');
args.append('chrome_elf.dll');
subprocess.call(args)
for fname in glob.iglob(os.path.join(input_dir, 'chrome.exe.*')):
shutil.copy(fname, os.path.join(output_dir, os.path.basename(fname)))
return 0 | [
"def",
"reorder_imports",
"(",
"input_dir",
",",
"output_dir",
",",
"architecture",
")",
":",
"input_image",
"=",
"os",
".",
"path",
".",
"join",
"(",
"input_dir",
",",
"'chrome.exe'",
")",
"output_image",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_... | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/win/reorder-imports.py#L13-L38 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/chunk.py | python | Chunk.getsize | (self) | return self.chunksize | Return the size of the current chunk. | Return the size of the current chunk. | [
"Return",
"the",
"size",
"of",
"the",
"current",
"chunk",
"."
] | def getsize(self):
"""Return the size of the current chunk."""
return self.chunksize | [
"def",
"getsize",
"(",
"self",
")",
":",
"return",
"self",
".",
"chunksize"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/chunk.py#L82-L84 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/rfc822.py | python | unquote | (s) | return s | Remove quotes from a string. | Remove quotes from a string. | [
"Remove",
"quotes",
"from",
"a",
"string",
"."
] | def unquote(s):
"""Remove quotes from a string."""
if len(s) > 1:
if s.startswith('"') and s.endswith('"'):
return s[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if s.startswith('<') and s.endswith('>'):
return s[1:-1]
return s | [
"def",
"unquote",
"(",
"s",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"1",
":",
"if",
"s",
".",
"startswith",
"(",
"'\"'",
")",
"and",
"s",
".",
"endswith",
"(",
"'\"'",
")",
":",
"return",
"s",
"[",
"1",
":",
"-",
"1",
"]",
".",
"replace"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/rfc822.py#L477-L484 | |
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | buildscripts/eslint.py | python | get_files_to_check_from_patch | (patches) | return valid_files | Take a patch file generated by git diff, and scan the patch for a list of files to check. | Take a patch file generated by git diff, and scan the patch for a list of files to check. | [
"Take",
"a",
"patch",
"file",
"generated",
"by",
"git",
"diff",
"and",
"scan",
"the",
"patch",
"for",
"a",
"list",
"of",
"files",
"to",
"check",
"."
] | def get_files_to_check_from_patch(patches):
"""Take a patch file generated by git diff, and scan the patch for a list of files to check.
"""
candidates = []
# Get a list of candidate_files
check = re.compile(r"^diff --git a\/([a-z\/\.\-_0-9]+) b\/[a-z\/\.\-_0-9]+")
lines = []
for patch in patches:
with open(patch, "rb") as infile:
lines += infile.readlines()
candidates = [check.match(line).group(1) for line in lines if check.match(line)]
repos = get_repos()
valid_files = list(itertools.chain.from_iterable([r.get_candidates(candidates) for r in repos]))
return valid_files | [
"def",
"get_files_to_check_from_patch",
"(",
"patches",
")",
":",
"candidates",
"=",
"[",
"]",
"# Get a list of candidate_files",
"check",
"=",
"re",
".",
"compile",
"(",
"r\"^diff --git a\\/([a-z\\/\\.\\-_0-9]+) b\\/[a-z\\/\\.\\-_0-9]+\"",
")",
"lines",
"=",
"[",
"]",
... | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/buildscripts/eslint.py#L431-L450 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/probability/distribution/exponential.py | python | Exponential._cdf | (self, value, rate=None) | return self.select(comp, zeros, cdf) | r"""
Cumulative distribution function (cdf) of Exponential distributions.
Args:
value (Tensor): The value to be evaluated.
rate (Tensor): The rate of the distribution. Default: self.rate.
Note:
`value` must be greater or equal to zero.
.. math::
cdf(x) = 1.0 - \exp(-1 * \lambda * x) if x >= 0 else 0 | r"""
Cumulative distribution function (cdf) of Exponential distributions. | [
"r",
"Cumulative",
"distribution",
"function",
"(",
"cdf",
")",
"of",
"Exponential",
"distributions",
"."
] | def _cdf(self, value, rate=None):
r"""
Cumulative distribution function (cdf) of Exponential distributions.
Args:
value (Tensor): The value to be evaluated.
rate (Tensor): The rate of the distribution. Default: self.rate.
Note:
`value` must be greater or equal to zero.
.. math::
cdf(x) = 1.0 - \exp(-1 * \lambda * x) if x >= 0 else 0
"""
value = self._check_value(value, 'value')
value = self.cast(value, self.dtype)
rate = self._check_param_type(rate)
cdf = 1.0 - self.exp(-1. * rate * value)
zeros = self.fill(self.dtypeop(cdf), self.shape(cdf), 0.0)
comp = self.less(value, zeros)
return self.select(comp, zeros, cdf) | [
"def",
"_cdf",
"(",
"self",
",",
"value",
",",
"rate",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_check_value",
"(",
"value",
",",
"'value'",
")",
"value",
"=",
"self",
".",
"cast",
"(",
"value",
",",
"self",
".",
"dtype",
")",
"rate",
"... | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/exponential.py#L278-L298 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Utils.py | python | destos_to_binfmt | (key) | return 'elf' | Return the binary format based on the unversioned platform name.
:param key: platform name
:type key: string
:return: string representing the binary format | Return the binary format based on the unversioned platform name. | [
"Return",
"the",
"binary",
"format",
"based",
"on",
"the",
"unversioned",
"platform",
"name",
"."
] | def destos_to_binfmt(key):
"""
Return the binary format based on the unversioned platform name.
:param key: platform name
:type key: string
:return: string representing the binary format
"""
if key == 'darwin':
return 'mac-o'
elif key in ('win32', 'cygwin', 'uwin', 'msys'):
return 'pe'
return 'elf' | [
"def",
"destos_to_binfmt",
"(",
"key",
")",
":",
"if",
"key",
"==",
"'darwin'",
":",
"return",
"'mac-o'",
"elif",
"key",
"in",
"(",
"'win32'",
",",
"'cygwin'",
",",
"'uwin'",
",",
"'msys'",
")",
":",
"return",
"'pe'",
"return",
"'elf'"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Utils.py#L557-L569 | |
telefonicaid/fiware-orion | 27c3202b9ddcfb9e3635a0af8d373f76e89b1d24 | scripts/pdi-pep8.py | python | expand_indent | (line) | return result | Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
16 | Return the amount of indentation.
Tabs are expanded to the next multiple of 8. | [
"Return",
"the",
"amount",
"of",
"indentation",
".",
"Tabs",
"are",
"expanded",
"to",
"the",
"next",
"multiple",
"of",
"8",
"."
] | def expand_indent(line):
"""
Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
16
"""
result = 0
for char in line:
if char == '\t':
result = result // 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result | [
"def",
"expand_indent",
"(",
"line",
")",
":",
"result",
"=",
"0",
"for",
"char",
"in",
"line",
":",
"if",
"char",
"==",
"'\\t'",
":",
"result",
"=",
"result",
"//",
"8",
"*",
"8",
"+",
"8",
"elif",
"char",
"==",
"' '",
":",
"result",
"+=",
"1",
... | https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/pdi-pep8.py#L734-L758 | |
Qihoo360/mongosync | 55b647e81c072ebe91daaa3b9dc1a953c3c22e19 | dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py | python | FindNextMultiLineCommentStart | (lines, lineix) | return len(lines) | Find the beginning marker for a multiline comment. | Find the beginning marker for a multiline comment. | [
"Find",
"the",
"beginning",
"marker",
"for",
"a",
"multiline",
"comment",
"."
] | def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines) | [
"def",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
":",
"while",
"lineix",
"<",
"len",
"(",
"lines",
")",
":",
"if",
"lines",
"[",
"lineix",
"]",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'/*'",
")",
":",
"# Only return this... | https://github.com/Qihoo360/mongosync/blob/55b647e81c072ebe91daaa3b9dc1a953c3c22e19/dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py#L863-L871 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/analysis.py | python | rewrite_semantic_constants | (func_ir, called_args) | This rewrites values known to be constant by their semantics as ir.Const
nodes, this is to give branch pruning the best chance possible of killing
branches. An example might be rewriting len(tuple) as the literal length.
func_ir is the IR
called_args are the actual arguments with which the function is called | This rewrites values known to be constant by their semantics as ir.Const
nodes, this is to give branch pruning the best chance possible of killing
branches. An example might be rewriting len(tuple) as the literal length. | [
"This",
"rewrites",
"values",
"known",
"to",
"be",
"constant",
"by",
"their",
"semantics",
"as",
"ir",
".",
"Const",
"nodes",
"this",
"is",
"to",
"give",
"branch",
"pruning",
"the",
"best",
"chance",
"possible",
"of",
"killing",
"branches",
".",
"An",
"exa... | def rewrite_semantic_constants(func_ir, called_args):
"""
This rewrites values known to be constant by their semantics as ir.Const
nodes, this is to give branch pruning the best chance possible of killing
branches. An example might be rewriting len(tuple) as the literal length.
func_ir is the IR
called_args are the actual arguments with which the function is called
"""
DEBUG = 0
if DEBUG > 1:
print(("rewrite_semantic_constants: " +
func_ir.func_id.func_name).center(80, '-'))
print("before".center(80, '*'))
func_ir.dump()
def rewrite_statement(func_ir, stmt, new_val):
"""
Rewrites the stmt as a ir.Const new_val and fixes up the entries in
func_ir._definitions
"""
stmt.value = ir.Const(new_val, stmt.loc)
defns = func_ir._definitions[stmt.target.name]
repl_idx = defns.index(val)
defns[repl_idx] = stmt.value
def rewrite_array_ndim(val, func_ir, called_args):
# rewrite Array.ndim as const(ndim)
if getattr(val, 'op', None) == 'getattr':
if val.attr == 'ndim':
arg_def = guard(get_definition, func_ir, val.value)
if isinstance(arg_def, ir.Arg):
argty = called_args[arg_def.index]
if isinstance(argty, types.Array):
rewrite_statement(func_ir, stmt, argty.ndim)
def rewrite_tuple_len(val, func_ir, called_args):
# rewrite len(tuple) as const(len(tuple))
if getattr(val, 'op', None) == 'call':
func = guard(get_definition, func_ir, val.func)
if (func is not None and isinstance(func, ir.Global) and
getattr(func, 'value', None) is len):
(arg,) = val.args
arg_def = guard(get_definition, func_ir, arg)
if isinstance(arg_def, ir.Arg):
argty = called_args[arg_def.index]
if isinstance(argty, types.BaseTuple):
rewrite_statement(func_ir, stmt, argty.count)
from .ir_utils import get_definition, guard
for blk in func_ir.blocks.values():
for stmt in blk.body:
if isinstance(stmt, ir.Assign):
val = stmt.value
if isinstance(val, ir.Expr):
rewrite_array_ndim(val, func_ir, called_args)
rewrite_tuple_len(val, func_ir, called_args)
if DEBUG > 1:
print("after".center(80, '*'))
func_ir.dump()
print('-' * 80) | [
"def",
"rewrite_semantic_constants",
"(",
"func_ir",
",",
"called_args",
")",
":",
"DEBUG",
"=",
"0",
"if",
"DEBUG",
">",
"1",
":",
"print",
"(",
"(",
"\"rewrite_semantic_constants: \"",
"+",
"func_ir",
".",
"func_id",
".",
"func_name",
")",
".",
"center",
"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/analysis.py#L459-L522 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py | python | _deconstruct_sparse_tensor_seq | (input_sequence, shared_name=None) | return transformed_input_seq, sparse_tensor_keys, tensor_op_list | Converts `SparseTensor` values into `Tensors` of IDs and meta data.
Given a dict of keys -> `Tensor` or `SparseTensor` transforms the
`SparseTensor` values into `Tensor` values of IDs by calling `_store_sparse`.
The IDs are pointers into and underlying `SparseTensorsMap` that is being
constructed. Additional meta data is returned in order to be able to
reconstruct `SparseTensor` values after batching and segmenting the IDs
`Tensor`.
Args:
input_sequence: dictionary with `Tensor` or `SparseTensor` values.
shared_name: The shared name for the underlying `SparseTensorsMap`
(optional, defaults to the name of the newly created op).
Returns:
A tuple `(sequence, sparse_tensor_keys, tensor_list)` where `sequence` is
dictionary with the same keys as `input_sequence` but only `Tensor` values,
`sparse_tensor_keys` is a list of the keys of the `SparseTensor` values that
were converted, and `tensor_list` is a list of the same length with
`Tensor` objects. | Converts `SparseTensor` values into `Tensors` of IDs and meta data. | [
"Converts",
"SparseTensor",
"values",
"into",
"Tensors",
"of",
"IDs",
"and",
"meta",
"data",
"."
] | def _deconstruct_sparse_tensor_seq(input_sequence, shared_name=None):
"""Converts `SparseTensor` values into `Tensors` of IDs and meta data.
Given a dict of keys -> `Tensor` or `SparseTensor` transforms the
`SparseTensor` values into `Tensor` values of IDs by calling `_store_sparse`.
The IDs are pointers into and underlying `SparseTensorsMap` that is being
constructed. Additional meta data is returned in order to be able to
reconstruct `SparseTensor` values after batching and segmenting the IDs
`Tensor`.
Args:
input_sequence: dictionary with `Tensor` or `SparseTensor` values.
shared_name: The shared name for the underlying `SparseTensorsMap`
(optional, defaults to the name of the newly created op).
Returns:
A tuple `(sequence, sparse_tensor_keys, tensor_list)` where `sequence` is
dictionary with the same keys as `input_sequence` but only `Tensor` values,
`sparse_tensor_keys` is a list of the keys of the `SparseTensor` values that
were converted, and `tensor_list` is a list of the same length with
`Tensor` objects.
"""
sparse_tensor_keys = [
k for k in sorted(input_sequence.keys())
if (isinstance(input_sequence[k], sparse_tensor.SparseTensor) or
isinstance(input_sequence[k], sparse_tensor.SparseTensorValue))]
if not sparse_tensor_keys:
return input_sequence, None, sparse_tensor_keys
sparse_tensor_list = [input_sequence[k] for k in sparse_tensor_keys]
tensor_list = [_store_sparse(sp_tensor, shared_name=shared_name)
for sp_tensor in sparse_tensor_list]
transformed_input_seq = dict(input_sequence)
tensor_op_list = []
for i, k in enumerate(sparse_tensor_keys):
transformed_input_seq[k] = tensor_list[i]
tensor_op_list += [tensor_list[i].op]
return transformed_input_seq, sparse_tensor_keys, tensor_op_list | [
"def",
"_deconstruct_sparse_tensor_seq",
"(",
"input_sequence",
",",
"shared_name",
"=",
"None",
")",
":",
"sparse_tensor_keys",
"=",
"[",
"k",
"for",
"k",
"in",
"sorted",
"(",
"input_sequence",
".",
"keys",
"(",
")",
")",
"if",
"(",
"isinstance",
"(",
"inpu... | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L1738-L1773 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ed_log.py | python | LogBuffer.SetFilter | (self, src) | Set the level of what is shown in the display
@param src: Only show messages from src
@return: bool | Set the level of what is shown in the display
@param src: Only show messages from src
@return: bool | [
"Set",
"the",
"level",
"of",
"what",
"is",
"shown",
"in",
"the",
"display",
"@param",
"src",
":",
"Only",
"show",
"messages",
"from",
"src",
"@return",
":",
"bool"
] | def SetFilter(self, src):
"""Set the level of what is shown in the display
@param src: Only show messages from src
@return: bool
"""
if src in self._srcs:
self._filter = src
return True
elif src == _("All"):
self._filter = SHOW_ALL_MSG
return True
else:
return False | [
"def",
"SetFilter",
"(",
"self",
",",
"src",
")",
":",
"if",
"src",
"in",
"self",
".",
"_srcs",
":",
"self",
".",
"_filter",
"=",
"src",
"return",
"True",
"elif",
"src",
"==",
"_",
"(",
"\"All\"",
")",
":",
"self",
".",
"_filter",
"=",
"SHOW_ALL_MS... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_log.py#L235-L248 | ||
google/mozc | 7329757e1ad30e327c1ae823a8302c79482d6b9c | src/build_mozc.py | python | CleanMain | (options, unused_args) | The main function for the 'clean' command. | The main function for the 'clean' command. | [
"The",
"main",
"function",
"for",
"the",
"clean",
"command",
"."
] | def CleanMain(options, unused_args):
"""The main function for the 'clean' command."""
# File and directory names to be removed.
file_names = []
directory_names = []
# Collect stuff in the gyp directories.
gyp_directory_names = [os.path.dirname(f) for f in GetGypFileNames(options)]
for gyp_directory_name in gyp_directory_names:
if IsWindows():
for pattern in ['*.ncb', '*.rules', '*.props', '*.sdf', '*.sln', '*.suo',
'*.targets', '*.vcproj', '*.vcproj.*.user', '*.vcxproj',
'*.vcxproj.filters', '*.vcxproj.user', 'gen_*_files.xml']:
file_names.extend(glob.glob(os.path.join(gyp_directory_name,
pattern)))
for build_type in ['Debug', 'Release']:
directory_names.append(os.path.join(gyp_directory_name,
build_type))
elif IsMac():
directory_names.extend(glob.glob(os.path.join(gyp_directory_name,
'*.xcodeproj')))
# mozc_version.txt does not always exist.
version_file = '%s/mozc_version.txt' % SRC_DIR
if os.path.exists(version_file):
file_names.append(version_file)
build_base = GetBuildBaseName(GetMozcVersion().GetTargetPlatform())
if build_base:
directory_names.append(build_base)
# Remove files.
for file_name in file_names:
RemoveFile(file_name)
# Remove directories.
for directory_name in directory_names:
RemoveDirectoryRecursively(directory_name) | [
"def",
"CleanMain",
"(",
"options",
",",
"unused_args",
")",
":",
"# File and directory names to be removed.",
"file_names",
"=",
"[",
"]",
"directory_names",
"=",
"[",
"]",
"# Collect stuff in the gyp directories.",
"gyp_directory_names",
"=",
"[",
"os",
".",
"path",
... | https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/build_mozc.py#L796-L832 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/eager/tape.py | python | Tape.should_record | (self, tensors) | return pywrap_tensorflow.TFE_Py_TapeShouldRecord(
self._tape, [x._id for x in tensors]) | Returns true if any tensor should be recorded.
Args:
tensors: some tensors.
Returns:
True if any of the tensors is in the tape. | Returns true if any tensor should be recorded. | [
"Returns",
"true",
"if",
"any",
"tensor",
"should",
"be",
"recorded",
"."
] | def should_record(self, tensors):
"""Returns true if any tensor should be recorded.
Args:
tensors: some tensors.
Returns:
True if any of the tensors is in the tape.
"""
return pywrap_tensorflow.TFE_Py_TapeShouldRecord(
self._tape, [x._id for x in tensors]) | [
"def",
"should_record",
"(",
"self",
",",
"tensors",
")",
":",
"return",
"pywrap_tensorflow",
".",
"TFE_Py_TapeShouldRecord",
"(",
"self",
".",
"_tape",
",",
"[",
"x",
".",
"_id",
"for",
"x",
"in",
"tensors",
"]",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/eager/tape.py#L65-L75 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/distribute/multi_process_runner.py | python | MultiProcessRunner.start_in_process_as | (self, as_task_type, as_task_id) | Start the processes, with the specified task run in main process.
This is similar to `start()` except that the task with task_type
`as_task_type` and task_id `as_task_id` is run in the main process.
This method is particularly useful when debugging tool such as `pdb` is
needed in some specific task. Note that since this method is blocking until
that specific task exits, additional actions would need a thread to be
called:
```python
def fn():
# user code to be run
import pdb; pdb.set_trace()
def follow_ups():
time.sleep(5)
mpr.start_single_process(
task_type='evaluator',
task_id=0)
mpr = multi_process_runner.MultiProcessRunner(
fn,
multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=1))
threading.Thread(target=follow_ups).start()
mpr.start_in_process_as(as_task_type='chief', as_task_id=0)
mpr.join()
```
Note that if `return_output=True`, the logs/stdout by task
run by the main process is not available in result.stdout.
Args:
as_task_type: The task type to be run in the main process.
as_task_id: The task id to be run in the main process. | Start the processes, with the specified task run in main process. | [
"Start",
"the",
"processes",
"with",
"the",
"specified",
"task",
"run",
"in",
"main",
"process",
"."
] | def start_in_process_as(self, as_task_type, as_task_id):
"""Start the processes, with the specified task run in main process.
This is similar to `start()` except that the task with task_type
`as_task_type` and task_id `as_task_id` is run in the main process.
This method is particularly useful when debugging tool such as `pdb` is
needed in some specific task. Note that since this method is blocking until
that specific task exits, additional actions would need a thread to be
called:
```python
def fn():
# user code to be run
import pdb; pdb.set_trace()
def follow_ups():
time.sleep(5)
mpr.start_single_process(
task_type='evaluator',
task_id=0)
mpr = multi_process_runner.MultiProcessRunner(
fn,
multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=1))
threading.Thread(target=follow_ups).start()
mpr.start_in_process_as(as_task_type='chief', as_task_id=0)
mpr.join()
```
Note that if `return_output=True`, the logs/stdout by task
run by the main process is not available in result.stdout.
Args:
as_task_type: The task type to be run in the main process.
as_task_id: The task id to be run in the main process.
"""
if self._processes:
raise ValueError('MultiProcessRunner already started.')
with self._process_lock:
if self._joined:
raise ValueError('cannot start new processes after'
'MultiProcessRunner.join() is called')
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
if not (task_type == as_task_type and task_id == as_task_id):
self._start_subprocess_and_reading_thread(task_type, task_id)
_set_tf_config(as_task_type, as_task_id, self._cluster_spec,
self._rpc_layer)
self._fn(*self._args, **self._kwargs) | [
"def",
"start_in_process_as",
"(",
"self",
",",
"as_task_type",
",",
"as_task_id",
")",
":",
"if",
"self",
".",
"_processes",
":",
"raise",
"ValueError",
"(",
"'MultiProcessRunner already started.'",
")",
"with",
"self",
".",
"_process_lock",
":",
"if",
"self",
... | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/multi_process_runner.py#L366-L416 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | python/mxnet/kvstore.py | python | KVStore._set_updater | (self, updater) | Sets a push updater into the store.
This function only changes the local store. When running on multiple machines one must
use `set_optimizer`.
Parameters
----------
updater : function
The updater function.
Examples
--------
>>> def update(key, input, stored):
... print "update on key: %d" % key
... stored += input * 2
>>> kv._set_updater(update)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> kv.push('3', mx.nd.ones(shape))
update on key: 3
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 6. 6. 6.]
[ 6. 6. 6.]] | Sets a push updater into the store. | [
"Sets",
"a",
"push",
"updater",
"into",
"the",
"store",
"."
] | def _set_updater(self, updater):
"""Sets a push updater into the store.
This function only changes the local store. When running on multiple machines one must
use `set_optimizer`.
Parameters
----------
updater : function
The updater function.
Examples
--------
>>> def update(key, input, stored):
... print "update on key: %d" % key
... stored += input * 2
>>> kv._set_updater(update)
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 4. 4. 4.]
[ 4. 4. 4.]]
>>> kv.push('3', mx.nd.ones(shape))
update on key: 3
>>> kv.pull('3', out=a)
>>> print a.asnumpy()
[[ 6. 6. 6.]
[ 6. 6. 6.]]
"""
self._updater = updater
# set updater with int keys
_updater_proto = ctypes.CFUNCTYPE(
None, ctypes.c_int, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
self._updater_func = _updater_proto(_updater_wrapper(updater))
# set updater with str keys
_str_updater_proto = ctypes.CFUNCTYPE(
None, ctypes.c_char_p, NDArrayHandle, NDArrayHandle, ctypes.c_void_p)
self._str_updater_func = _str_updater_proto(_updater_wrapper(updater))
check_call(_LIB.MXKVStoreSetUpdaterEx(self.handle, self._updater_func,
self._str_updater_func, None)) | [
"def",
"_set_updater",
"(",
"self",
",",
"updater",
")",
":",
"self",
".",
"_updater",
"=",
"updater",
"# set updater with int keys",
"_updater_proto",
"=",
"ctypes",
".",
"CFUNCTYPE",
"(",
"None",
",",
"ctypes",
".",
"c_int",
",",
"NDArrayHandle",
",",
"NDArr... | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/kvstore.py#L530-L568 | ||
apache/kudu | 90895ce76590f10730ad7aac3613b69d89ff5422 | build-support/dep_extract.py | python | DependencyExtractor.extract_deps | (self, exe) | return deps | Runs 'ldd' on the provided 'exe' path, returning a list of
any libraries it depends on. Blacklisted libraries are
removed from this list.
If the provided 'exe' is not a binary executable, returns
an empty list. | Runs 'ldd' on the provided 'exe' path, returning a list of
any libraries it depends on. Blacklisted libraries are
removed from this list. | [
"Runs",
"ldd",
"on",
"the",
"provided",
"exe",
"path",
"returning",
"a",
"list",
"of",
"any",
"libraries",
"it",
"depends",
"on",
".",
"Blacklisted",
"libraries",
"are",
"removed",
"from",
"this",
"list",
"."
] | def extract_deps(self, exe):
"""
Runs 'ldd' on the provided 'exe' path, returning a list of
any libraries it depends on. Blacklisted libraries are
removed from this list.
If the provided 'exe' is not a binary executable, returns
an empty list.
"""
if (exe.endswith(".jar") or
exe.endswith(".pl") or
exe.endswith(".py") or
exe.endswith(".sh") or
exe.endswith(".txt") or
os.path.isdir(exe)):
return []
if exe not in self.deps_cache:
p = subprocess.Popen(["ldd", exe], stdout=subprocess.PIPE)
out, err = p.communicate()
self.deps_cache[exe] = (out, err, p.returncode)
out, err, rc = self.deps_cache[exe]
if rc != 0:
logging.warning("failed to run ldd on %s", exe)
return []
deps = []
for line in out.splitlines():
match = LDD_RE.match(line)
if not match:
continue
dep = match.group(1)
# Apply the provided predicate.
if not self.lib_allowed_filter(dep):
continue
deps.append(dep)
if self.enable_expand_symlinks:
deps = self.expand_symlinks(deps)
return deps | [
"def",
"extract_deps",
"(",
"self",
",",
"exe",
")",
":",
"if",
"(",
"exe",
".",
"endswith",
"(",
"\".jar\"",
")",
"or",
"exe",
".",
"endswith",
"(",
"\".pl\"",
")",
"or",
"exe",
".",
"endswith",
"(",
"\".py\"",
")",
"or",
"exe",
".",
"endswith",
"... | https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/dep_extract.py#L79-L119 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | Region.UnionRegion | (*args, **kwargs) | return _gdi_.Region_UnionRegion(*args, **kwargs) | UnionRegion(self, Region region) -> bool | UnionRegion(self, Region region) -> bool | [
"UnionRegion",
"(",
"self",
"Region",
"region",
")",
"-",
">",
"bool"
] | def UnionRegion(*args, **kwargs):
"""UnionRegion(self, Region region) -> bool"""
return _gdi_.Region_UnionRegion(*args, **kwargs) | [
"def",
"UnionRegion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Region_UnionRegion",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L1603-L1605 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.GetSelectedTextUTF8 | (self) | return text | Retrieve the selected text as UTF8. In an ansi build of wxPython
the text retrieved from the document is assumed to be in the
current default encoding. | Retrieve the selected text as UTF8. In an ansi build of wxPython
the text retrieved from the document is assumed to be in the
current default encoding. | [
"Retrieve",
"the",
"selected",
"text",
"as",
"UTF8",
".",
"In",
"an",
"ansi",
"build",
"of",
"wxPython",
"the",
"text",
"retrieved",
"from",
"the",
"document",
"is",
"assumed",
"to",
"be",
"in",
"the",
"current",
"default",
"encoding",
"."
] | def GetSelectedTextUTF8(self):
"""
Retrieve the selected text as UTF8. In an ansi build of wxPython
the text retrieved from the document is assumed to be in the
current default encoding.
"""
text = self.GetSelectedTextRaw()
if not wx.USE_UNICODE:
u = text.decode(wx.GetDefaultPyEncoding())
text = u.encode('utf-8')
return text | [
"def",
"GetSelectedTextUTF8",
"(",
"self",
")",
":",
"text",
"=",
"self",
".",
"GetSelectedTextRaw",
"(",
")",
"if",
"not",
"wx",
".",
"USE_UNICODE",
":",
"u",
"=",
"text",
".",
"decode",
"(",
"wx",
".",
"GetDefaultPyEncoding",
"(",
")",
")",
"text",
"... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L6830-L6840 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/mapmatching/wxgui.py | python | WxGui.on_create_cyclists_database | (self, event=None) | Analyze attributes of persons and create an elaborated trips database. | Analyze attributes of persons and create an elaborated trips database. | [
"Analyze",
"attributes",
"of",
"persons",
"and",
"create",
"an",
"elaborated",
"trips",
"database",
"."
] | def on_create_cyclists_database(self, event=None):
"""
Analyze attributes of persons and create an elaborated trips database.
"""
p = mapmatching.CyclistsDatabaseAnalyzer('cyclistsdatabase', self._mapmatching,
results=self._results,
logger=self._mainframe.get_logger())
dlg = ProcessDialog(self._mainframe, p, immediate_apply=True)
dlg.CenterOnScreen()
# this does not return until the dialog is closed.
val = dlg.ShowModal()
# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
# print ' status =',dlg.get_status()
if dlg.get_status() != 'success': # val == wx.ID_CANCEL:
# print ">>>>>>>>>Unsuccessful\n"
dlg.Destroy()
if dlg.get_status() == 'success':
# print ">>>>>>>>>successful\n"
# apply current widget values to scenario instance
dlg.apply()
dlg.Destroy()
self._mainframe.browse_obj(self._results.cyclistsdatabase)
self._is_needs_refresh = True
self.refresh_widgets() | [
"def",
"on_create_cyclists_database",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"p",
"=",
"mapmatching",
".",
"CyclistsDatabaseAnalyzer",
"(",
"'cyclistsdatabase'",
",",
"self",
".",
"_mapmatching",
",",
"results",
"=",
"self",
".",
"_results",
",",
"l... | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/mapmatching/wxgui.py#L1777-L1805 | ||
SpenceKonde/megaTinyCore | 1c4a70b18a149fe6bcb551dfa6db11ca50b8997b | megaavr/tools/libs/pymcuprog/avr8target.py | python | TinyXAvrTarget.breakpoint_clear | (self) | return self.protocol.check_response(resp) | Clears the hardware breakpoint
:return: | Clears the hardware breakpoint | [
"Clears",
"the",
"hardware",
"breakpoint"
] | def breakpoint_clear(self):
"""
Clears the hardware breakpoint
:return:
"""
resp = self.protocol.jtagice3_command_response(
bytearray([Avr8Protocol.CMD_AVR8_HW_BREAK_CLEAR, Avr8Protocol.CMD_VERSION0, 1]))
return self.protocol.check_response(resp) | [
"def",
"breakpoint_clear",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"protocol",
".",
"jtagice3_command_response",
"(",
"bytearray",
"(",
"[",
"Avr8Protocol",
".",
"CMD_AVR8_HW_BREAK_CLEAR",
",",
"Avr8Protocol",
".",
"CMD_VERSION0",
",",
"1",
"]",
")",
... | https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/avr8target.py#L317-L325 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | FileTypeInfo.GetMimeType | (*args, **kwargs) | return _misc_.FileTypeInfo_GetMimeType(*args, **kwargs) | GetMimeType(self) -> String | GetMimeType(self) -> String | [
"GetMimeType",
"(",
"self",
")",
"-",
">",
"String"
] | def GetMimeType(*args, **kwargs):
"""GetMimeType(self) -> String"""
return _misc_.FileTypeInfo_GetMimeType(*args, **kwargs) | [
"def",
"GetMimeType",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"FileTypeInfo_GetMimeType",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2515-L2517 | |
s5z/zsim | fb4d6e0475a25cffd23f0687ede2d43d96b4a99f | misc/cpplint.py | python | RemoveMultiLineCommentsFromRange | (lines, begin, end) | Clears a range of lines for multi-line comments. | Clears a range of lines for multi-line comments. | [
"Clears",
"a",
"range",
"of",
"lines",
"for",
"multi",
"-",
"line",
"comments",
"."
] | def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '// dummy' | [
"def",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"begin",
",",
"end",
")",
":",
"# Having // dummy comments makes the lines non-empty, so we will not get",
"# unnecessary blank line warnings later in the code.",
"for",
"i",
"in",
"range",
"(",
"begin",
",",
"end",
... | https://github.com/s5z/zsim/blob/fb4d6e0475a25cffd23f0687ede2d43d96b4a99f/misc/cpplint.py#L944-L949 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/rpc.py | python | SocketIO.exithook | (self) | override for specific exit action | override for specific exit action | [
"override",
"for",
"specific",
"exit",
"action"
] | def exithook(self):
"override for specific exit action"
os._exit(0) | [
"def",
"exithook",
"(",
"self",
")",
":",
"os",
".",
"_exit",
"(",
"0",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/rpc.py#L145-L147 | ||
VowpalWabbit/vowpal_wabbit | 866b8fa88ff85a957c7eb72065ea44518b9ba416 | python/vowpalwabbit/pyvw.py | python | Example.push_hashed_feature | (
self, ns: Union[NamespaceId, str, int], f: int, v: float = 1.0
) | Add a hashed feature to a given namespace.
Args:
ns : namespace
namespace in which the feature is to be pushed
f : integer
feature
v : float
The value of the feature, be default is 1.0 | Add a hashed feature to a given namespace. | [
"Add",
"a",
"hashed",
"feature",
"to",
"a",
"given",
"namespace",
"."
] | def push_hashed_feature(
self, ns: Union[NamespaceId, str, int], f: int, v: float = 1.0
) -> None:
"""Add a hashed feature to a given namespace.
Args:
ns : namespace
namespace in which the feature is to be pushed
f : integer
feature
v : float
The value of the feature, be default is 1.0
"""
if self.setup_done:
self.unsetup_example()
pylibvw.example.push_hashed_feature(self, self.get_ns(ns).ord_ns, f, v) | [
"def",
"push_hashed_feature",
"(",
"self",
",",
"ns",
":",
"Union",
"[",
"NamespaceId",
",",
"str",
",",
"int",
"]",
",",
"f",
":",
"int",
",",
"v",
":",
"float",
"=",
"1.0",
")",
"->",
"None",
":",
"if",
"self",
".",
"setup_done",
":",
"self",
"... | https://github.com/VowpalWabbit/vowpal_wabbit/blob/866b8fa88ff85a957c7eb72065ea44518b9ba416/python/vowpalwabbit/pyvw.py#L1651-L1666 | ||
daijifeng001/caffe-rfcn | 543f8f6a4b7c88256ea1445ae951a12d1ad9cffd | scripts/cpp_lint.py | python | _CppLintState.SetOutputFormat | (self, output_format) | Sets the output format for errors. | Sets the output format for errors. | [
"Sets",
"the",
"output",
"format",
"for",
"errors",
"."
] | def SetOutputFormat(self, output_format):
"""Sets the output format for errors."""
self.output_format = output_format | [
"def",
"SetOutputFormat",
"(",
"self",
",",
"output_format",
")",
":",
"self",
".",
"output_format",
"=",
"output_format"
] | https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/scripts/cpp_lint.py#L703-L705 | ||
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | CondCore/Utilities/python/tier0.py | python | Tier0Handler.getFirstSafeRun | ( self ) | return int(safeRunDict['result'][0]) | Queries Tier0DataSvc to get the first condition safe run.
Parameters:
@returns: integer, the run number.
Raises if connection error, bad response, timeout after retries occur, or if the run number is not available. | Queries Tier0DataSvc to get the first condition safe run.
Parameters: | [
"Queries",
"Tier0DataSvc",
"to",
"get",
"the",
"first",
"condition",
"safe",
"run",
".",
"Parameters",
":"
] | def getFirstSafeRun( self ):
"""
Queries Tier0DataSvc to get the first condition safe run.
Parameters:
@returns: integer, the run number.
Raises if connection error, bad response, timeout after retries occur, or if the run number is not available.
"""
firstConditionSafeRunAPI = "firstconditionsaferun"
safeRunDict = self._queryTier0DataSvc( os.path.join( self._uri, firstConditionSafeRunAPI ) )
if safeRunDict is None:
errStr = """First condition safe run is not available in Tier0DataSvc from URL \"%s\"""" %( os.path.join( self._uri, firstConditionSafeRunAPI ), )
if self._proxy:
errStr += """ using proxy \"%s\".""" %( str( self._proxy ), )
raise Tier0Error( errStr )
return int(safeRunDict['result'][0]) | [
"def",
"getFirstSafeRun",
"(",
"self",
")",
":",
"firstConditionSafeRunAPI",
"=",
"\"firstconditionsaferun\"",
"safeRunDict",
"=",
"self",
".",
"_queryTier0DataSvc",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_uri",
",",
"firstConditionSafeRunAPI",
")... | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CondCore/Utilities/python/tier0.py#L142-L156 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | FlexGridSizer.AddGrowableRow | (*args, **kwargs) | return _core_.FlexGridSizer_AddGrowableRow(*args, **kwargs) | AddGrowableRow(self, size_t idx, int proportion=0)
Specifies that row *idx* (starting from zero) should be grown if there
is extra space available to the sizer.
The *proportion* parameter has the same meaning as the stretch factor
for the box sizers except that if all proportions are 0, then all
columns are resized equally (instead of not being resized at all). | AddGrowableRow(self, size_t idx, int proportion=0) | [
"AddGrowableRow",
"(",
"self",
"size_t",
"idx",
"int",
"proportion",
"=",
"0",
")"
] | def AddGrowableRow(*args, **kwargs):
"""
AddGrowableRow(self, size_t idx, int proportion=0)
Specifies that row *idx* (starting from zero) should be grown if there
is extra space available to the sizer.
The *proportion* parameter has the same meaning as the stretch factor
for the box sizers except that if all proportions are 0, then all
columns are resized equally (instead of not being resized at all).
"""
return _core_.FlexGridSizer_AddGrowableRow(*args, **kwargs) | [
"def",
"AddGrowableRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"FlexGridSizer_AddGrowableRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L15340-L15351 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/ssl.py | python | SSLObject.selected_npn_protocol | (self) | Return the currently selected NPN protocol as a string, or ``None``
if a next protocol was not negotiated or if NPN is not supported by one
of the peers. | Return the currently selected NPN protocol as a string, or ``None``
if a next protocol was not negotiated or if NPN is not supported by one
of the peers. | [
"Return",
"the",
"currently",
"selected",
"NPN",
"protocol",
"as",
"a",
"string",
"or",
"None",
"if",
"a",
"next",
"protocol",
"was",
"not",
"negotiated",
"or",
"if",
"NPN",
"is",
"not",
"supported",
"by",
"one",
"of",
"the",
"peers",
"."
] | def selected_npn_protocol(self):
"""Return the currently selected NPN protocol as a string, or ``None``
if a next protocol was not negotiated or if NPN is not supported by one
of the peers."""
if _ssl.HAS_NPN:
return self._sslobj.selected_npn_protocol() | [
"def",
"selected_npn_protocol",
"(",
"self",
")",
":",
"if",
"_ssl",
".",
"HAS_NPN",
":",
"return",
"self",
".",
"_sslobj",
".",
"selected_npn_protocol",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ssl.py#L926-L931 | ||
kushview/Element | 1cc16380caa2ab79461246ba758b9de1f46db2a5 | waflib/Tools/ldc2.py | python | configure | (conf) | Configuration for *ldc2* | Configuration for *ldc2* | [
"Configuration",
"for",
"*",
"ldc2",
"*"
] | def configure(conf):
"""
Configuration for *ldc2*
"""
conf.find_ldc2()
conf.load('ar')
conf.load('d')
conf.common_flags_ldc2()
conf.d_platform_flags() | [
"def",
"configure",
"(",
"conf",
")",
":",
"conf",
".",
"find_ldc2",
"(",
")",
"conf",
".",
"load",
"(",
"'ar'",
")",
"conf",
".",
"load",
"(",
"'d'",
")",
"conf",
".",
"common_flags_ldc2",
"(",
")",
"conf",
".",
"d_platform_flags",
"(",
")"
] | https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/ldc2.py#L47-L55 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/tools/inspector_protocol/jinja2/filters.py | python | do_upper | (s) | return soft_unicode(s).upper() | Convert a value to uppercase. | Convert a value to uppercase. | [
"Convert",
"a",
"value",
"to",
"uppercase",
"."
] | def do_upper(s):
"""Convert a value to uppercase."""
return soft_unicode(s).upper() | [
"def",
"do_upper",
"(",
"s",
")",
":",
"return",
"soft_unicode",
"(",
"s",
")",
".",
"upper",
"(",
")"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/filters.py#L143-L145 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/numbers.py | python | Integral.__ror__ | (self, other) | other | self | other | self | [
"other",
"|",
"self"
] | def __ror__(self, other):
"""other | self"""
raise NotImplementedError | [
"def",
"__ror__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/numbers.py#L366-L368 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/compatibility/ngraph/opset1/ops.py | python | logical_xor | (
left_node: NodeInput,
right_node: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) | return _get_node_factory_opset1().create(
"LogicalXor", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
) | Return node which performs logical XOR operation on input nodes element-wise.
:param left_node: The first input node providing data.
:param right_node: The second input node providing data.
:param auto_broadcast: The type of broadcasting that specifies mapping of input tensor axes
to output shape axes. Range of values: numpy, explicit.
:param name: The optional new name for output node.
:return: The node performing logical or operation on input nodes corresponding elements. | Return node which performs logical XOR operation on input nodes element-wise. | [
"Return",
"node",
"which",
"performs",
"logical",
"XOR",
"operation",
"on",
"input",
"nodes",
"element",
"-",
"wise",
"."
] | def logical_xor(
left_node: NodeInput,
right_node: NodeInput,
auto_broadcast: str = "NUMPY",
name: Optional[str] = None,
) -> Node:
"""Return node which performs logical XOR operation on input nodes element-wise.
:param left_node: The first input node providing data.
:param right_node: The second input node providing data.
:param auto_broadcast: The type of broadcasting that specifies mapping of input tensor axes
to output shape axes. Range of values: numpy, explicit.
:param name: The optional new name for output node.
:return: The node performing logical or operation on input nodes corresponding elements.
"""
return _get_node_factory_opset1().create(
"LogicalXor", [left_node, right_node], {"auto_broadcast": auto_broadcast.upper()}
) | [
"def",
"logical_xor",
"(",
"left_node",
":",
"NodeInput",
",",
"right_node",
":",
"NodeInput",
",",
"auto_broadcast",
":",
"str",
"=",
"\"NUMPY\"",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Node",
":",
"return",
"_get_n... | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/opset1/ops.py#L1357-L1374 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/Jinja2/py3/jinja2/lexer.py | python | TokenStream.look | (self) | return result | Look at the next token. | Look at the next token. | [
"Look",
"at",
"the",
"next",
"token",
"."
] | def look(self) -> Token:
"""Look at the next token."""
old_token = next(self)
result = self.current
self.push(result)
self.current = old_token
return result | [
"def",
"look",
"(",
"self",
")",
"->",
"Token",
":",
"old_token",
"=",
"next",
"(",
"self",
")",
"result",
"=",
"self",
".",
"current",
"self",
".",
"push",
"(",
"result",
")",
"self",
".",
"current",
"=",
"old_token",
"return",
"result"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/lexer.py#L352-L358 | |
xhzdeng/crpn | a5aef0f80dbe486103123f740c634fb01e6cc9a1 | tools/train_faster_rcnn_alt_opt.py | python | train_fast_rcnn | (queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None, rpn_file=None) | Train a Fast R-CNN using proposals generated by an RPN. | Train a Fast R-CNN using proposals generated by an RPN. | [
"Train",
"a",
"Fast",
"R",
"-",
"CNN",
"using",
"proposals",
"generated",
"by",
"an",
"RPN",
"."
] | def train_fast_rcnn(queue=None, imdb_name=None, init_model=None, solver=None,
max_iters=None, cfg=None, rpn_file=None):
"""Train a Fast R-CNN using proposals generated by an RPN.
"""
cfg.TRAIN.HAS_RPN = False # not generating prosals on-the-fly
cfg.TRAIN.PROPOSAL_METHOD = 'rpn' # use pre-computed RPN proposals instead
cfg.TRAIN.IMS_PER_BATCH = 2
print 'Init model: {}'.format(init_model)
print 'RPN proposals: {}'.format(rpn_file)
print('Using config:')
pprint.pprint(cfg)
import caffe
_init_caffe(cfg)
roidb, imdb = get_roidb(imdb_name, rpn_file=rpn_file)
output_dir = get_output_dir(imdb)
print 'Output will be saved to `{:s}`'.format(output_dir)
# Train Fast R-CNN
model_paths = train_net(solver, roidb, output_dir,
pretrained_model=init_model,
max_iters=max_iters)
# Cleanup all but the final model
for i in model_paths[:-1]:
os.remove(i)
fast_rcnn_model_path = model_paths[-1]
# Send Fast R-CNN model path over the multiprocessing queue
queue.put({'model_path': fast_rcnn_model_path}) | [
"def",
"train_fast_rcnn",
"(",
"queue",
"=",
"None",
",",
"imdb_name",
"=",
"None",
",",
"init_model",
"=",
"None",
",",
"solver",
"=",
"None",
",",
"max_iters",
"=",
"None",
",",
"cfg",
"=",
"None",
",",
"rpn_file",
"=",
"None",
")",
":",
"cfg",
"."... | https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/tools/train_faster_rcnn_alt_opt.py#L173-L201 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TextAttr.SetLineSpacing | (*args, **kwargs) | return _controls_.TextAttr_SetLineSpacing(*args, **kwargs) | SetLineSpacing(self, int spacing) | SetLineSpacing(self, int spacing) | [
"SetLineSpacing",
"(",
"self",
"int",
"spacing",
")"
] | def SetLineSpacing(*args, **kwargs):
"""SetLineSpacing(self, int spacing)"""
return _controls_.TextAttr_SetLineSpacing(*args, **kwargs) | [
"def",
"SetLineSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_SetLineSpacing",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1595-L1597 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/manifold/_locally_linear.py | python | barycenter_kneighbors_graph | (X, n_neighbors, reg=1e-3, n_jobs=None) | return csr_matrix((data.ravel(), ind.ravel(), indptr),
shape=(n_samples, n_samples)) | Computes the barycenter weighted graph of k-Neighbors for points in X
Parameters
----------
X : {array-like, NearestNeighbors}
Sample data, shape = (n_samples, n_features), in the form of a
numpy array or a NearestNeighbors object.
n_neighbors : int
Number of neighbors for each sample.
reg : float, optional
Amount of regularization when solving the least-squares
problem. Only relevant if mode='barycenter'. If None, use the
default.
n_jobs : int or None, optional (default=None)
The number of parallel jobs to run for neighbors search.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
Returns
-------
A : sparse matrix in CSR format, shape = [n_samples, n_samples]
A[i, j] is assigned the weight of edge that connects i to j.
See also
--------
sklearn.neighbors.kneighbors_graph
sklearn.neighbors.radius_neighbors_graph | Computes the barycenter weighted graph of k-Neighbors for points in X | [
"Computes",
"the",
"barycenter",
"weighted",
"graph",
"of",
"k",
"-",
"Neighbors",
"for",
"points",
"in",
"X"
] | def barycenter_kneighbors_graph(X, n_neighbors, reg=1e-3, n_jobs=None):
"""Computes the barycenter weighted graph of k-Neighbors for points in X
Parameters
----------
X : {array-like, NearestNeighbors}
Sample data, shape = (n_samples, n_features), in the form of a
numpy array or a NearestNeighbors object.
n_neighbors : int
Number of neighbors for each sample.
reg : float, optional
Amount of regularization when solving the least-squares
problem. Only relevant if mode='barycenter'. If None, use the
default.
n_jobs : int or None, optional (default=None)
The number of parallel jobs to run for neighbors search.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
Returns
-------
A : sparse matrix in CSR format, shape = [n_samples, n_samples]
A[i, j] is assigned the weight of edge that connects i to j.
See also
--------
sklearn.neighbors.kneighbors_graph
sklearn.neighbors.radius_neighbors_graph
"""
knn = NearestNeighbors(n_neighbors + 1, n_jobs=n_jobs).fit(X)
X = knn._fit_X
n_samples = knn.n_samples_fit_
ind = knn.kneighbors(X, return_distance=False)[:, 1:]
data = barycenter_weights(X, X[ind], reg=reg)
indptr = np.arange(0, n_samples * n_neighbors + 1, n_neighbors)
return csr_matrix((data.ravel(), ind.ravel(), indptr),
shape=(n_samples, n_samples)) | [
"def",
"barycenter_kneighbors_graph",
"(",
"X",
",",
"n_neighbors",
",",
"reg",
"=",
"1e-3",
",",
"n_jobs",
"=",
"None",
")",
":",
"knn",
"=",
"NearestNeighbors",
"(",
"n_neighbors",
"+",
"1",
",",
"n_jobs",
"=",
"n_jobs",
")",
".",
"fit",
"(",
"X",
")... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/manifold/_locally_linear.py#L67-L107 | |
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | utils/grid.py | python | TimelinesRenderer.draw_ranges | (self, ctx, ranges, x, y, width, height) | ! Draw Ranges
@param self this object
@param ctx ctx
@param ranges ranges
@param x x
@param y y
@param width width
@param height height
@return none | ! Draw Ranges | [
"!",
"Draw",
"Ranges"
] | def draw_ranges(self, ctx, ranges, x, y, width, height):
"""! Draw Ranges
@param self this object
@param ctx ctx
@param ranges ranges
@param x x
@param y y
@param width width
@param height height
@return none
"""
if (self.grey_background % 2) == 0:
ctx.rectangle(x, y - self.padding / 2,
width, height + self.padding)
ctx.set_source_rgb(0.9, 0.9, 0.9)
ctx.fill()
last_x_drawn = int(x - 1)
(lo, hi) = ranges.get_ranges_bounds(self.start, self.end)
for data_range in ranges.ranges[lo:hi]:
s = max(data_range.start, self.start)
e = min(data_range.end, self.end)
x_start = int(x + (s - self.start) * width / (self.end - self.start))
x_end = int(x + (e - self.start) * width / (self.end - self.start))
if x_end > last_x_drawn:
ctx.rectangle(x_start, y, x_end - x_start, 10)
ctx.set_source_rgb(0, 0, 0)
ctx.stroke_preserve()
color = self.colors.lookup(data_range.value)
ctx.set_source_rgb(color.r, color.g, color.b)
ctx.fill()
last_x_drawn = x_end
self.grey_background += 1 | [
"def",
"draw_ranges",
"(",
"self",
",",
"ctx",
",",
"ranges",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"if",
"(",
"self",
".",
"grey_background",
"%",
"2",
")",
"==",
"0",
":",
"ctx",
".",
"rectangle",
"(",
"x",
",",
"y",
"-",... | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/grid.py#L757-L789 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBDebugger.GetScriptingLanguage | (self, *args) | return _lldb.SBDebugger_GetScriptingLanguage(self, *args) | GetScriptingLanguage(self, str script_language_name) -> ScriptLanguage | GetScriptingLanguage(self, str script_language_name) -> ScriptLanguage | [
"GetScriptingLanguage",
"(",
"self",
"str",
"script_language_name",
")",
"-",
">",
"ScriptLanguage"
] | def GetScriptingLanguage(self, *args):
"""GetScriptingLanguage(self, str script_language_name) -> ScriptLanguage"""
return _lldb.SBDebugger_GetScriptingLanguage(self, *args) | [
"def",
"GetScriptingLanguage",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBDebugger_GetScriptingLanguage",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3370-L3372 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/stc.py | python | StyledTextCtrl.DescribeKeyWordSets | (*args, **kwargs) | return _stc.StyledTextCtrl_DescribeKeyWordSets(*args, **kwargs) | DescribeKeyWordSets(self) -> String | DescribeKeyWordSets(self) -> String | [
"DescribeKeyWordSets",
"(",
"self",
")",
"-",
">",
"String"
] | def DescribeKeyWordSets(*args, **kwargs):
"""DescribeKeyWordSets(self) -> String"""
return _stc.StyledTextCtrl_DescribeKeyWordSets(*args, **kwargs) | [
"def",
"DescribeKeyWordSets",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_DescribeKeyWordSets",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L6511-L6513 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/symbol/numpy/_symbol.py | python | equal | (x1, x2, out=None) | return _ufunc_helper(x1, x2, _npi.equal, _np.equal, _npi.equal_scalar, None, out) | Return (x1 == x2) element-wise.
Parameters
----------
x1, x2 : _Symbol or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : Dummy parameter, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : _Symbol or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
not_equal, greater_equal, less_equal, greater, less
Examples
--------
>>> np.equal(np.ones(2, 1)), np.zeros(1, 3))
array([[False, False, False],
[False, False, False]])
>>> np.equal(1, np.ones(1))
array([ True]) | Return (x1 == x2) element-wise.
Parameters
----------
x1, x2 : _Symbol or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : Dummy parameter, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : _Symbol or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
not_equal, greater_equal, less_equal, greater, less
Examples
--------
>>> np.equal(np.ones(2, 1)), np.zeros(1, 3))
array([[False, False, False],
[False, False, False]])
>>> np.equal(1, np.ones(1))
array([ True]) | [
"Return",
"(",
"x1",
"==",
"x2",
")",
"element",
"-",
"wise",
".",
"Parameters",
"----------",
"x1",
"x2",
":",
"_Symbol",
"or",
"scalars",
"Input",
"arrays",
".",
"If",
"x1",
".",
"shape",
"!",
"=",
"x2",
".",
"shape",
"they",
"must",
"be",
"broadca... | def equal(x1, x2, out=None):
"""
Return (x1 == x2) element-wise.
Parameters
----------
x1, x2 : _Symbol or scalars
Input arrays. If ``x1.shape != x2.shape``, they must be broadcastable to
a common shape (which becomes the shape of the output).
out : Dummy parameter, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned.
Returns
-------
out : _Symbol or scalar
Output array of type bool, element-wise comparison of `x1` and `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
not_equal, greater_equal, less_equal, greater, less
Examples
--------
>>> np.equal(np.ones(2, 1)), np.zeros(1, 3))
array([[False, False, False],
[False, False, False]])
>>> np.equal(1, np.ones(1))
array([ True])
"""
return _ufunc_helper(x1, x2, _npi.equal, _np.equal, _npi.equal_scalar, None, out) | [
"def",
"equal",
"(",
"x1",
",",
"x2",
",",
"out",
"=",
"None",
")",
":",
"return",
"_ufunc_helper",
"(",
"x1",
",",
"x2",
",",
"_npi",
".",
"equal",
",",
"_np",
".",
"equal",
",",
"_npi",
".",
"equal_scalar",
",",
"None",
",",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L6341-L6369 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/optimize/_trustregion_constr/qp_subproblem.py | python | projected_cg | (H, c, Z, Y, b, trust_radius=np.inf,
lb=None, ub=None, tol=None,
max_iter=None, max_infeasible_iter=None,
return_all=False) | return x, info | Solve EQP problem with projected CG method.
Solve equality-constrained quadratic programming problem
``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` and,
possibly, to trust region constraints ``||x|| < trust_radius``
and box constraints ``lb <= x <= ub``.
Parameters
----------
H : LinearOperator (or sparse matrix or ndarray), shape (n, n)
Operator for computing ``H v``.
c : array_like, shape (n,)
Gradient of the quadratic objective function.
Z : LinearOperator (or sparse matrix or ndarray), shape (n, n)
Operator for projecting ``x`` into the null space of A.
Y : LinearOperator, sparse matrix, ndarray, shape (n, m)
Operator that, for a given a vector ``b``, compute smallest
norm solution of ``A x + b = 0``.
b : array_like, shape (m,)
Right-hand side of the constraint equation.
trust_radius : float, optional
Trust radius to be considered. By default uses ``trust_radius=inf``,
which means no trust radius at all.
lb : array_like, shape (n,), optional
Lower bounds to each one of the components of ``x``.
If ``lb[i] = -Inf`` the lower bound for the i-th
component is just ignored (default).
ub : array_like, shape (n, ), optional
Upper bounds to each one of the components of ``x``.
If ``ub[i] = Inf`` the upper bound for the i-th
component is just ignored (default).
tol : float, optional
Tolerance used to interrupt the algorithm.
max_iter : int, optional
Maximum algorithm iterations. Where ``max_inter <= n-m``.
By default uses ``max_iter = n-m``.
max_infeasible_iter : int, optional
Maximum infeasible (regarding box constraints) iterations the
algorithm is allowed to take.
By default uses ``max_infeasible_iter = n-m``.
return_all : bool, optional
When ``true`` return the list of all vectors through the iterations.
Returns
-------
x : array_like, shape (n,)
Solution of the EQP problem.
info : Dict
Dictionary containing the following:
- niter : Number of iterations.
- stop_cond : Reason for algorithm termination:
1. Iteration limit was reached;
2. Reached the trust-region boundary;
3. Negative curvature detected;
4. Tolerance was satisfied.
- allvecs : List containing all intermediary vectors (optional).
- hits_boundary : True if the proposed step is on the boundary
of the trust region.
Notes
-----
Implementation of Algorithm 6.2 on [1]_.
In the absence of spherical and box constraints, for sufficient
iterations, the method returns a truly optimal result.
In the presence of those constraints the value returned is only
a inexpensive approximation of the optimal value.
References
----------
.. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
"On the solution of equality constrained quadratic
programming problems arising in optimization."
SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395. | Solve EQP problem with projected CG method. | [
"Solve",
"EQP",
"problem",
"with",
"projected",
"CG",
"method",
"."
] | def projected_cg(H, c, Z, Y, b, trust_radius=np.inf,
lb=None, ub=None, tol=None,
max_iter=None, max_infeasible_iter=None,
return_all=False):
"""Solve EQP problem with projected CG method.
Solve equality-constrained quadratic programming problem
``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` and,
possibly, to trust region constraints ``||x|| < trust_radius``
and box constraints ``lb <= x <= ub``.
Parameters
----------
H : LinearOperator (or sparse matrix or ndarray), shape (n, n)
Operator for computing ``H v``.
c : array_like, shape (n,)
Gradient of the quadratic objective function.
Z : LinearOperator (or sparse matrix or ndarray), shape (n, n)
Operator for projecting ``x`` into the null space of A.
Y : LinearOperator, sparse matrix, ndarray, shape (n, m)
Operator that, for a given a vector ``b``, compute smallest
norm solution of ``A x + b = 0``.
b : array_like, shape (m,)
Right-hand side of the constraint equation.
trust_radius : float, optional
Trust radius to be considered. By default uses ``trust_radius=inf``,
which means no trust radius at all.
lb : array_like, shape (n,), optional
Lower bounds to each one of the components of ``x``.
If ``lb[i] = -Inf`` the lower bound for the i-th
component is just ignored (default).
ub : array_like, shape (n, ), optional
Upper bounds to each one of the components of ``x``.
If ``ub[i] = Inf`` the upper bound for the i-th
component is just ignored (default).
tol : float, optional
Tolerance used to interrupt the algorithm.
max_iter : int, optional
Maximum algorithm iterations. Where ``max_inter <= n-m``.
By default uses ``max_iter = n-m``.
max_infeasible_iter : int, optional
Maximum infeasible (regarding box constraints) iterations the
algorithm is allowed to take.
By default uses ``max_infeasible_iter = n-m``.
return_all : bool, optional
When ``true`` return the list of all vectors through the iterations.
Returns
-------
x : array_like, shape (n,)
Solution of the EQP problem.
info : Dict
Dictionary containing the following:
- niter : Number of iterations.
- stop_cond : Reason for algorithm termination:
1. Iteration limit was reached;
2. Reached the trust-region boundary;
3. Negative curvature detected;
4. Tolerance was satisfied.
- allvecs : List containing all intermediary vectors (optional).
- hits_boundary : True if the proposed step is on the boundary
of the trust region.
Notes
-----
Implementation of Algorithm 6.2 on [1]_.
In the absence of spherical and box constraints, for sufficient
iterations, the method returns a truly optimal result.
In the presence of those constraints the value returned is only
a inexpensive approximation of the optimal value.
References
----------
.. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
"On the solution of equality constrained quadratic
programming problems arising in optimization."
SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
"""
CLOSE_TO_ZERO = 1e-25
n, = np.shape(c) # Number of parameters
m, = np.shape(b) # Number of constraints
# Initial Values
x = Y.dot(-b)
r = Z.dot(H.dot(x) + c)
g = Z.dot(r)
p = -g
# Store ``x`` value
if return_all:
allvecs = [x]
# Values for the first iteration
H_p = H.dot(p)
rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
# If x > trust-region the problem does not have a solution.
tr_distance = trust_radius - norm(x)
if tr_distance < 0:
raise ValueError("Trust region problem does not have a solution.")
# If x == trust_radius, then x is the solution
# to the optimization problem, since x is the
# minimum norm solution to Ax=b.
elif tr_distance < CLOSE_TO_ZERO:
info = {'niter': 0, 'stop_cond': 2, 'hits_boundary': True}
if return_all:
allvecs.append(x)
info['allvecs'] = allvecs
return x, info
# Set default tolerance
if tol is None:
tol = max(min(0.01 * np.sqrt(rt_g), 0.1 * rt_g), CLOSE_TO_ZERO)
# Set default lower and upper bounds
if lb is None:
lb = np.full(n, -np.inf)
if ub is None:
ub = np.full(n, np.inf)
# Set maximum iterations
if max_iter is None:
max_iter = n-m
max_iter = min(max_iter, n-m)
# Set maximum infeasible iterations
if max_infeasible_iter is None:
max_infeasible_iter = n-m
hits_boundary = False
stop_cond = 1
counter = 0
last_feasible_x = np.zeros_like(x)
k = 0
for i in range(max_iter):
# Stop criteria - Tolerance : r.T g < tol
if rt_g < tol:
stop_cond = 4
break
k += 1
# Compute curvature
pt_H_p = H_p.dot(p)
# Stop criteria - Negative curvature
if pt_H_p <= 0:
if np.isinf(trust_radius):
raise ValueError("Negative curvature not "
"allowed for unrestrited "
"problems.")
else:
# Find intersection with constraints
_, alpha, intersect = box_sphere_intersections(
x, p, lb, ub, trust_radius, entire_line=True)
# Update solution
if intersect:
x = x + alpha*p
# Reinforce variables are inside box constraints.
# This is only necessary because of roundoff errors.
x = reinforce_box_boundaries(x, lb, ub)
# Attribute information
stop_cond = 3
hits_boundary = True
break
# Get next step
alpha = rt_g / pt_H_p
x_next = x + alpha*p
# Stop criteria - Hits boundary
if np.linalg.norm(x_next) >= trust_radius:
# Find intersection with box constraints
_, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
trust_radius)
# Update solution
if intersect:
x = x + theta*alpha*p
# Reinforce variables are inside box constraints.
# This is only necessary because of roundoff errors.
x = reinforce_box_boundaries(x, lb, ub)
# Attribute information
stop_cond = 2
hits_boundary = True
break
# Check if ``x`` is inside the box and start counter if it is not.
if inside_box_boundaries(x_next, lb, ub):
counter = 0
else:
counter += 1
# Whenever outside box constraints keep looking for intersections.
if counter > 0:
_, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
trust_radius)
if intersect:
last_feasible_x = x + theta*alpha*p
# Reinforce variables are inside box constraints.
# This is only necessary because of roundoff errors.
last_feasible_x = reinforce_box_boundaries(last_feasible_x,
lb, ub)
counter = 0
# Stop after too many infeasible (regarding box constraints) iteration.
if counter > max_infeasible_iter:
break
# Store ``x_next`` value
if return_all:
allvecs.append(x_next)
# Update residual
r_next = r + alpha*H_p
# Project residual g+ = Z r+
g_next = Z.dot(r_next)
# Compute conjugate direction step d
rt_g_next = norm(g_next)**2 # g.T g = r.T g (ref [1]_ p.1389)
beta = rt_g_next / rt_g
p = - g_next + beta*p
# Prepare for next iteration
x = x_next
g = g_next
r = g_next
rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
H_p = H.dot(p)
if not inside_box_boundaries(x, lb, ub):
x = last_feasible_x
hits_boundary = True
info = {'niter': k, 'stop_cond': stop_cond,
'hits_boundary': hits_boundary}
if return_all:
info['allvecs'] = allvecs
return x, info | [
"def",
"projected_cg",
"(",
"H",
",",
"c",
",",
"Z",
",",
"Y",
",",
"b",
",",
"trust_radius",
"=",
"np",
".",
"inf",
",",
"lb",
"=",
"None",
",",
"ub",
"=",
"None",
",",
"tol",
"=",
"None",
",",
"max_iter",
"=",
"None",
",",
"max_infeasible_iter"... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/_trustregion_constr/qp_subproblem.py#L412-L639 | |
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | src/python/gem5/components/boards/riscv_board.py | python | RiscvBoard._setup_pma | (self) | Set the PMA devices on each core | Set the PMA devices on each core | [
"Set",
"the",
"PMA",
"devices",
"on",
"each",
"core"
] | def _setup_pma(self) -> None:
"""Set the PMA devices on each core"""
uncacheable_range = [
AddrRange(dev.pio_addr, size=dev.pio_size)
for dev in self._on_chip_devices + self._off_chip_devices
]
# TODO: Not sure if this should be done per-core like in the example
for cpu in self.get_processor().get_cores():
cpu.get_mmu().pma_checker = PMAChecker(
uncacheable=uncacheable_range
) | [
"def",
"_setup_pma",
"(",
"self",
")",
"->",
"None",
":",
"uncacheable_range",
"=",
"[",
"AddrRange",
"(",
"dev",
".",
"pio_addr",
",",
"size",
"=",
"dev",
".",
"pio_size",
")",
"for",
"dev",
"in",
"self",
".",
"_on_chip_devices",
"+",
"self",
".",
"_o... | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/gem5/components/boards/riscv_board.py#L159-L171 | ||
Z3Prover/z3 | d745d03afdfdf638d66093e2bfbacaf87187f35b | src/api/python/z3/z3.py | python | FloatSingle | (ctx=None) | return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx) | Floating-point 32-bit (single) sort. | Floating-point 32-bit (single) sort. | [
"Floating",
"-",
"point",
"32",
"-",
"bit",
"(",
"single",
")",
"sort",
"."
] | def FloatSingle(ctx=None):
"""Floating-point 32-bit (single) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx) | [
"def",
"FloatSingle",
"(",
"ctx",
"=",
"None",
")",
":",
"ctx",
"=",
"_get_ctx",
"(",
"ctx",
")",
"return",
"FPSortRef",
"(",
"Z3_mk_fpa_sort_single",
"(",
"ctx",
".",
"ref",
"(",
")",
")",
",",
"ctx",
")"
] | https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L9292-L9295 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/heapq.py | python | heapreplace | (heap, item) | return returnitem | Pop and return the current smallest value, and add the new item.
This is more efficient than heappop() followed by heappush(), and can be
more appropriate when using a fixed-size heap. Note that the value
returned may be larger than item! That constrains reasonable uses of
this routine unless written as part of a conditional replacement:
if item > heap[0]:
item = heapreplace(heap, item) | Pop and return the current smallest value, and add the new item. | [
"Pop",
"and",
"return",
"the",
"current",
"smallest",
"value",
"and",
"add",
"the",
"new",
"item",
"."
] | def heapreplace(heap, item):
"""Pop and return the current smallest value, and add the new item.
This is more efficient than heappop() followed by heappush(), and can be
more appropriate when using a fixed-size heap. Note that the value
returned may be larger than item! That constrains reasonable uses of
this routine unless written as part of a conditional replacement:
if item > heap[0]:
item = heapreplace(heap, item)
"""
returnitem = heap[0] # raises appropriate IndexError if heap is empty
heap[0] = item
_siftup(heap, 0)
return returnitem | [
"def",
"heapreplace",
"(",
"heap",
",",
"item",
")",
":",
"returnitem",
"=",
"heap",
"[",
"0",
"]",
"# raises appropriate IndexError if heap is empty",
"heap",
"[",
"0",
"]",
"=",
"item",
"_siftup",
"(",
"heap",
",",
"0",
")",
"return",
"returnitem"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/heapq.py#L145-L159 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/stc.py | python | StyledTextCtrl.SetScrollWidth | (*args, **kwargs) | return _stc.StyledTextCtrl_SetScrollWidth(*args, **kwargs) | SetScrollWidth(self, int pixelWidth)
Sets the document width assumed for scrolling. | SetScrollWidth(self, int pixelWidth) | [
"SetScrollWidth",
"(",
"self",
"int",
"pixelWidth",
")"
] | def SetScrollWidth(*args, **kwargs):
"""
SetScrollWidth(self, int pixelWidth)
Sets the document width assumed for scrolling.
"""
return _stc.StyledTextCtrl_SetScrollWidth(*args, **kwargs) | [
"def",
"SetScrollWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_SetScrollWidth",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L4167-L4173 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/indexes/base.py | python | Index.hasnans | (self) | Return if I have any nans; enables various perf speedups. | Return if I have any nans; enables various perf speedups. | [
"Return",
"if",
"I",
"have",
"any",
"nans",
";",
"enables",
"various",
"perf",
"speedups",
"."
] | def hasnans(self) -> bool:
"""
Return if I have any nans; enables various perf speedups.
"""
if self._can_hold_na:
return bool(self._isnan.any())
else:
return False | [
"def",
"hasnans",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_can_hold_na",
":",
"return",
"bool",
"(",
"self",
".",
"_isnan",
".",
"any",
"(",
")",
")",
"else",
":",
"return",
"False"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L2445-L2452 | ||
nickgillian/grt | 4d4cab1999a349b00d8924da769ff3f0c29d3176 | build/python/examples/PreProcessingModulesExamples/median_filter_example.py | python | main | () | GRT MedianFilter Example
This example demonstrates how to create and use the GRT MedianFilter PreProcessing Module.
The MedianFilter implements a simple median filter, this will give the value seperating the higher
half of the most recent data from the lower half. The filter will automatically store the most
recent input data for you, the size of the buffer that stores the M most recent samples is controlled
by the MedianFilter's 'window size' parameter.
In this example we create an instance of a MedianFilter and use this to filter some dummy data. The test
signal and filtered signals are then printed to std::cout.
This example shows you how to:
- Create a new MedianFilter instance with a specific window size for a 1 dimensional signal
- Filter some data using the MedianFilter
- Save the MedianFilter settings to a file
- Load the MedianFilter settings from a file | GRT MedianFilter Example
This example demonstrates how to create and use the GRT MedianFilter PreProcessing Module. | [
"GRT",
"MedianFilter",
"Example",
"This",
"example",
"demonstrates",
"how",
"to",
"create",
"and",
"use",
"the",
"GRT",
"MedianFilter",
"PreProcessing",
"Module",
"."
] | def main():
"""GRT MedianFilter Example
This example demonstrates how to create and use the GRT MedianFilter PreProcessing Module.
The MedianFilter implements a simple median filter, this will give the value seperating the higher
half of the most recent data from the lower half. The filter will automatically store the most
recent input data for you, the size of the buffer that stores the M most recent samples is controlled
by the MedianFilter's 'window size' parameter.
In this example we create an instance of a MedianFilter and use this to filter some dummy data. The test
signal and filtered signals are then printed to std::cout.
This example shows you how to:
- Create a new MedianFilter instance with a specific window size for a 1 dimensional signal
- Filter some data using the MedianFilter
- Save the MedianFilter settings to a file
- Load the MedianFilter settings from a file"""
# Create a new instance of a median average filter with a window size of 5 for a 1 dimensional signal
filter = GRT.MedianFilter(10, 1)
# Generate some data (basic counter) and filter it
for i in range(100):
# Filter the current value
filtered_value = filter.filter(i)
# Get the current data in the circular buffer
data = filter.getDataBuffer()
# Print the results
print("input value: %d \t filtered value: %.3f\t data: %s" % (i, filtered_value, data))
# Save the filter settings to a file
filter.save("MedianFilterSettings.grt")
# We can then load the settings later if needed
filter.load("MedianFilterSettings.grt") | [
"def",
"main",
"(",
")",
":",
"# Create a new instance of a median average filter with a window size of 5 for a 1 dimensional signal",
"filter",
"=",
"GRT",
".",
"MedianFilter",
"(",
"10",
",",
"1",
")",
"# Generate some data (basic counter) and filter it",
"for",
"i",
"in",
... | https://github.com/nickgillian/grt/blob/4d4cab1999a349b00d8924da769ff3f0c29d3176/build/python/examples/PreProcessingModulesExamples/median_filter_example.py#L7-L42 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/algorithms.py | python | mode | (values, dropna=True) | return Series(result) | Returns the mode(s) of an array.
Parameters
----------
values : array-like
Array over which to check for duplicate values.
dropna : boolean, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
Returns
-------
mode : Series | Returns the mode(s) of an array. | [
"Returns",
"the",
"mode",
"(",
"s",
")",
"of",
"an",
"array",
"."
] | def mode(values, dropna=True):
"""
Returns the mode(s) of an array.
Parameters
----------
values : array-like
Array over which to check for duplicate values.
dropna : boolean, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
Returns
-------
mode : Series
"""
from pandas import Series
values = _ensure_arraylike(values)
original = values
# categorical is a fast-path
if is_categorical_dtype(values):
if isinstance(values, Series):
return Series(values.values.mode(dropna=dropna), name=values.name)
return values.mode(dropna=dropna)
if dropna and is_datetimelike(values):
mask = values.isnull()
values = values[~mask]
values, dtype, ndtype = _ensure_data(values)
f = getattr(htable, "mode_{dtype}".format(dtype=ndtype))
result = f(values, dropna=dropna)
try:
result = np.sort(result)
except TypeError as e:
warn("Unable to sort modes: {error}".format(error=e))
result = _reconstruct_data(result, original.dtype, original)
return Series(result) | [
"def",
"mode",
"(",
"values",
",",
"dropna",
"=",
"True",
")",
":",
"from",
"pandas",
"import",
"Series",
"values",
"=",
"_ensure_arraylike",
"(",
"values",
")",
"original",
"=",
"values",
"# categorical is a fast-path",
"if",
"is_categorical_dtype",
"(",
"value... | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/algorithms.py#L790-L832 | |
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/cpplint_1.4.5/cpplint.py | python | GetPreviousNonBlankLine | (clean_lines, linenum) | return ('', -1) | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line. | Return the most recent non-blank line and its line number. | [
"Return",
"the",
"most",
"recent",
"non",
"-",
"blank",
"line",
"and",
"its",
"line",
"number",
"."
] | def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1) | [
"def",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"prevlinenum",
"=",
"linenum",
"-",
"1",
"while",
"prevlinenum",
">=",
"0",
":",
"prevline",
"=",
"clean_lines",
".",
"elided",
"[",
"prevlinenum",
"]",
"if",
"not",
"IsBlankLine",... | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/cpplint_1.4.5/cpplint.py#L3949-L3969 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/ccompiler.py | python | CCompiler.detect_language | (self, sources) | return lang | Detect the language of a given file, or list of files. Uses
language_map, and language_order to do the job. | Detect the language of a given file, or list of files. Uses
language_map, and language_order to do the job. | [
"Detect",
"the",
"language",
"of",
"a",
"given",
"file",
"or",
"list",
"of",
"files",
".",
"Uses",
"language_map",
"and",
"language_order",
"to",
"do",
"the",
"job",
"."
] | def detect_language(self, sources):
"""Detect the language of a given file, or list of files. Uses
language_map, and language_order to do the job.
"""
if not isinstance(sources, list):
sources = [sources]
lang = None
index = len(self.language_order)
for source in sources:
base, ext = os.path.splitext(source)
extlang = self.language_map.get(ext)
try:
extindex = self.language_order.index(extlang)
if extindex < index:
lang = extlang
index = extindex
except ValueError:
pass
return lang | [
"def",
"detect_language",
"(",
"self",
",",
"sources",
")",
":",
"if",
"not",
"isinstance",
"(",
"sources",
",",
"list",
")",
":",
"sources",
"=",
"[",
"sources",
"]",
"lang",
"=",
"None",
"index",
"=",
"len",
"(",
"self",
".",
"language_order",
")",
... | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/distutils/ccompiler.py#L474-L492 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py | python | PreParforPass.run | (self) | Run pre-parfor processing pass. | Run pre-parfor processing pass. | [
"Run",
"pre",
"-",
"parfor",
"processing",
"pass",
"."
] | def run(self):
"""Run pre-parfor processing pass.
"""
# e.g. convert A.sum() to np.sum(A) for easier match and optimization
canonicalize_array_math(self.func_ir, self.typemap,
self.calltypes, self.typingctx)
if self.options.numpy:
self._replace_parallel_functions(self.func_ir.blocks)
self.func_ir.blocks = simplify_CFG(self.func_ir.blocks) | [
"def",
"run",
"(",
"self",
")",
":",
"# e.g. convert A.sum() to np.sum(A) for easier match and optimization",
"canonicalize_array_math",
"(",
"self",
".",
"func_ir",
",",
"self",
".",
"typemap",
",",
"self",
".",
"calltypes",
",",
"self",
".",
"typingctx",
")",
"if"... | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py#L1330-L1338 | ||
Manu343726/siplasplas | 9fae7559f87087cf8ef34f04bd1e774b84b2ea9c | reference/cindex.py | python | Cursor.mangled_name | (self) | return self._mangled_name | Return the mangled name for the entity referenced by this cursor. | Return the mangled name for the entity referenced by this cursor. | [
"Return",
"the",
"mangled",
"name",
"for",
"the",
"entity",
"referenced",
"by",
"this",
"cursor",
"."
] | def mangled_name(self):
"""Return the mangled name for the entity referenced by this cursor."""
if not hasattr(self, '_mangled_name'):
self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
return self._mangled_name | [
"def",
"mangled_name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_mangled_name'",
")",
":",
"self",
".",
"_mangled_name",
"=",
"conf",
".",
"lib",
".",
"clang_Cursor_getMangling",
"(",
"self",
")",
"return",
"self",
".",
"_mangled_... | https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1276-L1281 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/globe_cutter_app.py | python | GlobeBuilder.PackageGlobeForDownload | (self, make_copy, is_map=False) | Packages globe or map as a single-file globe. | Packages globe or map as a single-file globe. | [
"Packages",
"globe",
"or",
"map",
"as",
"a",
"single",
"-",
"file",
"globe",
"."
] | def PackageGlobeForDownload(self, make_copy, is_map=False):
"""Packages globe or map as a single-file globe."""
if is_map:
self.Status("Packaging map for download ...")
is_2d_str = "--is_2d"
out_file = self.map_file
else:
self.Status("Packaging globe for download ...")
is_2d_str = ""
out_file = self.globe_file
# Remove old globe or map.
try:
os.remove(out_file)
except OSError:
pass # Globe or map may not exist.
make_copy_str = ""
if make_copy:
make_copy_str = "--make_copy"
os_cmd = ("%s/geportableglobepacker --globe_directory=\"%s\" "
"--output=\"%s\" %s %s"
% (COMMAND_DIR, self.globe_dir, out_file,
make_copy_str, is_2d_str))
new_globe_size = common.utils.DirectorySize(self.globe_env_dir)
globe_dir_space = common.utils.DiskSpace(os.path.dirname(out_file))
if globe_dir_space < new_globe_size:
self.StatusWarning(
("Not enough room to create %s. %s required."
"<br>Did not execute:<br>%s")
% (out_file, common.utils.SizeAsString(new_globe_size),
os_cmd))
raise DiskFullError("Disk is full at %s"
% os.path.dirname(out_file))
common.utils.ExecuteCmd(os_cmd, self.logger)
os_cmd = ("chmod a+r \"%s\"" % out_file)
common.utils.ExecuteCmd(os_cmd, self.logger)
self.Status("%s %s" % (out_file,
common.utils.FileSizeAsString(out_file))) | [
"def",
"PackageGlobeForDownload",
"(",
"self",
",",
"make_copy",
",",
"is_map",
"=",
"False",
")",
":",
"if",
"is_map",
":",
"self",
".",
"Status",
"(",
"\"Packaging map for download ...\"",
")",
"is_2d_str",
"=",
"\"--is_2d\"",
"out_file",
"=",
"self",
".",
"... | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/globe_cutter_app.py#L662-L704 | ||
echronos/echronos | c996f1d2c8af6c6536205eb319c1bf1d4d84569c | external_tools/ply_info/example/calcdebug/calc.py | python | p_expression_binop | (p) | expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression | expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression | [
"expression",
":",
"expression",
"+",
"expression",
"|",
"expression",
"-",
"expression",
"|",
"expression",
"*",
"expression",
"|",
"expression",
"/",
"expression"
] | def p_expression_binop(p):
'''expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression'''
if p[2] == '+' : p[0] = p[1] + p[3]
elif p[2] == '-': p[0] = p[1] - p[3]
elif p[2] == '*': p[0] = p[1] * p[3]
elif p[2] == '/': p[0] = p[1] / p[3] | [
"def",
"p_expression_binop",
"(",
"p",
")",
":",
"if",
"p",
"[",
"2",
"]",
"==",
"'+'",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"p",
"[",
"3",
"]",
"elif",
"p",
"[",
"2",
"]",
"==",
"'-'",
":",
"p",
"[",
"0",
"]",
"=",
... | https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/calcdebug/calc.py#L62-L70 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py | python | PyShell._close | (self) | Extend EditorWindow._close(), shut down debugger and execution server | Extend EditorWindow._close(), shut down debugger and execution server | [
"Extend",
"EditorWindow",
".",
"_close",
"()",
"shut",
"down",
"debugger",
"and",
"execution",
"server"
] | def _close(self):
"Extend EditorWindow._close(), shut down debugger and execution server"
self.close_debugger()
if use_subprocess:
self.interp.kill_subprocess()
# Restore std streams
sys.stdout = self.save_stdout
sys.stderr = self.save_stderr
sys.stdin = self.save_stdin
# Break cycles
self.interp = None
self.console = None
self.flist.pyshell = None
self.history = None
EditorWindow._close(self) | [
"def",
"_close",
"(",
"self",
")",
":",
"self",
".",
"close_debugger",
"(",
")",
"if",
"use_subprocess",
":",
"self",
".",
"interp",
".",
"kill_subprocess",
"(",
")",
"# Restore std streams",
"sys",
".",
"stdout",
"=",
"self",
".",
"save_stdout",
"sys",
".... | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/PyShell.py#L997-L1011 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/framemanager.py | python | AuiPaneInfo.ResetButtons | (self) | Resets all the buttons and recreates them from scratch depending on the
:class:`AuiManager` flags. | Resets all the buttons and recreates them from scratch depending on the
:class:`AuiManager` flags. | [
"Resets",
"all",
"the",
"buttons",
"and",
"recreates",
"them",
"from",
"scratch",
"depending",
"on",
"the",
":",
"class",
":",
"AuiManager",
"flags",
"."
] | def ResetButtons(self):
"""
Resets all the buttons and recreates them from scratch depending on the
:class:`AuiManager` flags.
"""
floating = self.HasFlag(self.optionFloating)
self.buttons = []
if not floating and self.HasMinimizeButton():
button = AuiPaneButton(AUI_BUTTON_MINIMIZE)
self.buttons.append(button)
if not floating and self.HasMaximizeButton():
button = AuiPaneButton(AUI_BUTTON_MAXIMIZE_RESTORE)
self.buttons.append(button)
if not floating and self.HasPinButton():
button = AuiPaneButton(AUI_BUTTON_PIN)
self.buttons.append(button)
if self.HasCloseButton():
button = AuiPaneButton(AUI_BUTTON_CLOSE)
self.buttons.append(button) | [
"def",
"ResetButtons",
"(",
"self",
")",
":",
"floating",
"=",
"self",
".",
"HasFlag",
"(",
"self",
".",
"optionFloating",
")",
"self",
".",
"buttons",
"=",
"[",
"]",
"if",
"not",
"floating",
"and",
"self",
".",
"HasMinimizeButton",
"(",
")",
":",
"but... | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L1807-L1830 | ||
jsupancic/deep_hand_pose | 22cbeae1a8410ff5d37c060c7315719d0a5d608f | scripts/cpp_lint.py | python | CheckInvalidIncrement | (filename, clean_lines, linenum, error) | Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Checks for invalid increment *count++. | [
"Checks",
"for",
"invalid",
"increment",
"*",
"count",
"++",
"."
] | def CheckInvalidIncrement(filename, clean_lines, linenum, error):
"""Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if _RE_PATTERN_INVALID_INCREMENT.match(line):
error(filename, linenum, 'runtime/invalid_increment', 5,
'Changing pointer instead of value (or unused value of operator*).') | [
"def",
"CheckInvalidIncrement",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"_RE_PATTERN_INVALID_INCREMENT",
".",
"match",
"(",
"line",
")",
":",
"error",
... | https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/scripts/cpp_lint.py#L1733-L1752 | ||
rbgirshick/caffe-fast-rcnn | 28a579eaf0668850705598b3075b8969f22226d9 | scripts/cpp_lint.py | python | ReplaceAll | (pattern, rep, s) | return _regexp_compile_cache[pattern].sub(rep, s) | Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements) | Replaces instances of pattern in a string with a replacement. | [
"Replaces",
"instances",
"of",
"pattern",
"in",
"a",
"string",
"with",
"a",
"replacement",
"."
] | def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s) | [
"def",
"ReplaceAll",
"(",
"pattern",
",",
"rep",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_c... | https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L525-L540 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/stc.py | python | StyledTextEvent.SetMargin | (*args, **kwargs) | return _stc.StyledTextEvent_SetMargin(*args, **kwargs) | SetMargin(self, int val) | SetMargin(self, int val) | [
"SetMargin",
"(",
"self",
"int",
"val",
")"
] | def SetMargin(*args, **kwargs):
"""SetMargin(self, int val)"""
return _stc.StyledTextEvent_SetMargin(*args, **kwargs) | [
"def",
"SetMargin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextEvent_SetMargin",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L7066-L7068 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/platform.py | python | release | () | return uname()[2] | Returns the system's release, e.g. '2.2.0' or 'NT'
An empty string is returned if the value cannot be determined. | Returns the system's release, e.g. '2.2.0' or 'NT' | [
"Returns",
"the",
"system",
"s",
"release",
"e",
".",
"g",
".",
"2",
".",
"2",
".",
"0",
"or",
"NT"
] | def release():
""" Returns the system's release, e.g. '2.2.0' or 'NT'
An empty string is returned if the value cannot be determined.
"""
return uname()[2] | [
"def",
"release",
"(",
")",
":",
"return",
"uname",
"(",
")",
"[",
"2",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/platform.py#L1322-L1329 | |
ApolloAuto/apollo | 463fb82f9e979d02dcb25044e60931293ab2dba0 | modules/tools/routing/road_show.py | python | draw_arc | (arc) | :param arc: proto obj
:return: none | :param arc: proto obj
:return: none | [
":",
"param",
"arc",
":",
"proto",
"obj",
":",
"return",
":",
"none"
] | def draw_arc(arc):
"""
:param arc: proto obj
:return: none
"""
xy = (arc.center.x, arc.center.y)
start = 0
end = 0
if arc.start_angle < arc.end_angle:
start = arc.start_angle / math.pi * 180
end = arc.end_angle / math.pi * 180
else:
end = arc.start_angle / math.pi * 180
start = arc.end_angle / math.pi * 180
pac = mpatches.Arc(
xy, arc.radius * 2, arc.radius * 2, angle=0, theta1=start, theta2=end)
plt.gca().add_patch(pac) | [
"def",
"draw_arc",
"(",
"arc",
")",
":",
"xy",
"=",
"(",
"arc",
".",
"center",
".",
"x",
",",
"arc",
".",
"center",
".",
"y",
")",
"start",
"=",
"0",
"end",
"=",
"0",
"if",
"arc",
".",
"start_angle",
"<",
"arc",
".",
"end_angle",
":",
"start",
... | https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/routing/road_show.py#L45-L63 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings._GetAndMunge | (self, field, path, default, prefix, append, map) | return _AppendOrReturn(append, result) | Retrieve a value from |field| at |path| or return |default|. If
|append| is specified, and the item is found, it will be appended to that
object instead of returned. If |map| is specified, results will be
remapped through |map| before being returned or appended. | Retrieve a value from |field| at |path| or return |default|. If
|append| is specified, and the item is found, it will be appended to that
object instead of returned. If |map| is specified, results will be
remapped through |map| before being returned or appended. | [
"Retrieve",
"a",
"value",
"from",
"|field|",
"at",
"|path|",
"or",
"return",
"|default|",
".",
"If",
"|append|",
"is",
"specified",
"and",
"the",
"item",
"is",
"found",
"it",
"will",
"be",
"appended",
"to",
"that",
"object",
"instead",
"of",
"returned",
".... | def _GetAndMunge(self, field, path, default, prefix, append, map):
"""Retrieve a value from |field| at |path| or return |default|. If
|append| is specified, and the item is found, it will be appended to that
object instead of returned. If |map| is specified, results will be
remapped through |map| before being returned or appended."""
result = _GenericRetrieve(field, default, path)
result = _DoRemapping(result, map)
result = _AddPrefix(result, prefix)
return _AppendOrReturn(append, result) | [
"def",
"_GetAndMunge",
"(",
"self",
",",
"field",
",",
"path",
",",
"default",
",",
"prefix",
",",
"append",
",",
"map",
")",
":",
"result",
"=",
"_GenericRetrieve",
"(",
"field",
",",
"default",
",",
"path",
")",
"result",
"=",
"_DoRemapping",
"(",
"r... | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/msvs_emulation.py#L279-L287 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/mailbox.py | python | MH.__contains__ | (self, key) | return os.path.exists(os.path.join(self._path, str(key))) | Return True if the keyed message exists, False otherwise. | Return True if the keyed message exists, False otherwise. | [
"Return",
"True",
"if",
"the",
"keyed",
"message",
"exists",
"False",
"otherwise",
"."
] | def __contains__(self, key):
"""Return True if the keyed message exists, False otherwise."""
return os.path.exists(os.path.join(self._path, str(key))) | [
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"str",
"(",
"key",
")",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mailbox.py#L1081-L1083 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.scroll_constrain | (self) | This keeps the scroll region within the screen region. | This keeps the scroll region within the screen region. | [
"This",
"keeps",
"the",
"scroll",
"region",
"within",
"the",
"screen",
"region",
"."
] | def scroll_constrain (self):
'''This keeps the scroll region within the screen region.'''
if self.scroll_row_start <= 0:
self.scroll_row_start = 1
if self.scroll_row_end > self.rows:
self.scroll_row_end = self.rows | [
"def",
"scroll_constrain",
"(",
"self",
")",
":",
"if",
"self",
".",
"scroll_row_start",
"<=",
"0",
":",
"self",
".",
"scroll_row_start",
"=",
"1",
"if",
"self",
".",
"scroll_row_end",
">",
"self",
".",
"rows",
":",
"self",
".",
"scroll_row_end",
"=",
"s... | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L339-L345 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | media/webrtc/trunk/build/android/adb_logcat_printer.py | python | FindLogFiles | (base_dir) | return file_map | Search a directory for logcat files.
Args:
base_dir: directory to search
Returns:
Mapping of device_id to a sorted list of file paths for a given device | Search a directory for logcat files. | [
"Search",
"a",
"directory",
"for",
"logcat",
"files",
"."
] | def FindLogFiles(base_dir):
"""Search a directory for logcat files.
Args:
base_dir: directory to search
Returns:
Mapping of device_id to a sorted list of file paths for a given device
"""
logcat_filter = re.compile('^logcat_(\w+)_(\d+)$')
# list of tuples (<device_id>, <seq num>, <full file path>)
filtered_list = []
for cur_file in os.listdir(base_dir):
matcher = logcat_filter.match(cur_file)
if matcher:
filtered_list += [(matcher.group(1), int(matcher.group(2)),
os.path.join(base_dir, cur_file))]
filtered_list.sort()
file_map = {}
for device_id, _, cur_file in filtered_list:
if not device_id in file_map:
file_map[device_id] = []
file_map[device_id] += [cur_file]
return file_map | [
"def",
"FindLogFiles",
"(",
"base_dir",
")",
":",
"logcat_filter",
"=",
"re",
".",
"compile",
"(",
"'^logcat_(\\w+)_(\\d+)$'",
")",
"# list of tuples (<device_id>, <seq num>, <full file path>)",
"filtered_list",
"=",
"[",
"]",
"for",
"cur_file",
"in",
"os",
".",
"list... | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/build/android/adb_logcat_printer.py#L70-L94 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/ShowBase.py | python | ShowBase.wxRun | (self) | This method replaces `run()` after we have called `spawnWxLoop()`.
Since at this point wxPython now owns the main loop, this method is a
call to wxApp.MainLoop(). | This method replaces `run()` after we have called `spawnWxLoop()`.
Since at this point wxPython now owns the main loop, this method is a
call to wxApp.MainLoop(). | [
"This",
"method",
"replaces",
"run",
"()",
"after",
"we",
"have",
"called",
"spawnWxLoop",
"()",
".",
"Since",
"at",
"this",
"point",
"wxPython",
"now",
"owns",
"the",
"main",
"loop",
"this",
"method",
"is",
"a",
"call",
"to",
"wxApp",
".",
"MainLoop",
"... | def wxRun(self):
""" This method replaces `run()` after we have called `spawnWxLoop()`.
Since at this point wxPython now owns the main loop, this method is a
call to wxApp.MainLoop(). """
if Thread.getCurrentThread().getCurrentTask():
# This happens in the p3d environment during startup.
# Ignore it.
return
self.wxApp.MainLoop() | [
"def",
"wxRun",
"(",
"self",
")",
":",
"if",
"Thread",
".",
"getCurrentThread",
"(",
")",
".",
"getCurrentTask",
"(",
")",
":",
"# This happens in the p3d environment during startup.",
"# Ignore it.",
"return",
"self",
".",
"wxApp",
".",
"MainLoop",
"(",
")"
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/ShowBase.py#L3174-L3184 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.