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
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
cppsrc/fmt-5.3.0/support/docopt.py
python
transform
(pattern)
return Either(*[Required(*e) for e in result])
Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a)
Expand pattern into an (almost) equivalent one, but with single Either.
[ "Expand", "pattern", "into", "an", "(", "almost", ")", "equivalent", "one", "but", "with", "single", "Either", "." ]
def transform(pattern): """Expand pattern into an (almost) equivalent one, but with single Either. Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d) Quirks: [-a] => (-a), (-a...) => (-a -a) """ result = [] groups = [[pattern]] while groups: children = groups.pop(0) parents = [Required, Optional, OptionsShortcut, Either, OneOrMore] if any(t in map(type, children) for t in parents): child = [c for c in children if type(c) in parents][0] children.remove(child) if type(child) is Either: for c in child.children: groups.append([c] + children) elif type(child) is OneOrMore: groups.append(child.children * 2 + children) else: groups.append(child.children + children) else: result.append(children) return Either(*[Required(*e) for e in result])
[ "def", "transform", "(", "pattern", ")", ":", "result", "=", "[", "]", "groups", "=", "[", "[", "pattern", "]", "]", "while", "groups", ":", "children", "=", "groups", ".", "pop", "(", "0", ")", "parents", "=", "[", "Required", ",", "Optional", ",", "OptionsShortcut", ",", "Either", ",", "OneOrMore", "]", "if", "any", "(", "t", "in", "map", "(", "type", ",", "children", ")", "for", "t", "in", "parents", ")", ":", "child", "=", "[", "c", "for", "c", "in", "children", "if", "type", "(", "c", ")", "in", "parents", "]", "[", "0", "]", "children", ".", "remove", "(", "child", ")", "if", "type", "(", "child", ")", "is", "Either", ":", "for", "c", "in", "child", ".", "children", ":", "groups", ".", "append", "(", "[", "c", "]", "+", "children", ")", "elif", "type", "(", "child", ")", "is", "OneOrMore", ":", "groups", ".", "append", "(", "child", ".", "children", "*", "2", "+", "children", ")", "else", ":", "groups", ".", "append", "(", "child", ".", "children", "+", "children", ")", "else", ":", "result", ".", "append", "(", "children", ")", "return", "Either", "(", "*", "[", "Required", "(", "*", "e", ")", "for", "e", "in", "result", "]", ")" ]
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/cppsrc/fmt-5.3.0/support/docopt.py#L72-L96
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/smtplib.py
python
SMTP.quit
(self)
return res
Terminate the SMTP session.
Terminate the SMTP session.
[ "Terminate", "the", "SMTP", "session", "." ]
def quit(self): """Terminate the SMTP session.""" res = self.docmd("quit") self.close() return res
[ "def", "quit", "(", "self", ")", ":", "res", "=", "self", ".", "docmd", "(", "\"quit\"", ")", "self", ".", "close", "(", ")", "return", "res" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/smtplib.py#L728-L732
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/encoder.py
python
_SignedVarintSize
(value)
return 10
Compute the size of a signed varint value.
Compute the size of a signed varint value.
[ "Compute", "the", "size", "of", "a", "signed", "varint", "value", "." ]
def _SignedVarintSize(value): """Compute the size of a signed varint value.""" if value < 0: return 10 if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return 4 if value <= 0x7ffffffff: return 5 if value <= 0x3ffffffffff: return 6 if value <= 0x1ffffffffffff: return 7 if value <= 0xffffffffffffff: return 8 if value <= 0x7fffffffffffffff: return 9 return 10
[ "def", "_SignedVarintSize", "(", "value", ")", ":", "if", "value", "<", "0", ":", "return", "10", "if", "value", "<=", "0x7f", ":", "return", "1", "if", "value", "<=", "0x3fff", ":", "return", "2", "if", "value", "<=", "0x1fffff", ":", "return", "3", "if", "value", "<=", "0xfffffff", ":", "return", "4", "if", "value", "<=", "0x7ffffffff", ":", "return", "5", "if", "value", "<=", "0x3ffffffffff", ":", "return", "6", "if", "value", "<=", "0x1ffffffffffff", ":", "return", "7", "if", "value", "<=", "0xffffffffffffff", ":", "return", "8", "if", "value", "<=", "0x7fffffffffffffff", ":", "return", "9", "return", "10" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/encoder.py#L93-L105
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/include/PRESUBMIT.py
python
PostUploadHook
(cl, change, output_api)
return output_api.EnsureCQIncludeTrybotsAreAdded( cl, [ 'master.tryserver.chromium.linux:linux_chromium_rel_ng' ], 'Automatically added layout test trybots to run tests on CQ.')
git cl upload will call this hook after the issue is created/modified. This hook adds extra try bots to the CL description in order to run layout tests in addition to CQ try bots.
git cl upload will call this hook after the issue is created/modified.
[ "git", "cl", "upload", "will", "call", "this", "hook", "after", "the", "issue", "is", "created", "/", "modified", "." ]
def PostUploadHook(cl, change, output_api): """git cl upload will call this hook after the issue is created/modified. This hook adds extra try bots to the CL description in order to run layout tests in addition to CQ try bots. """ def header_filter(f): return '.h' in os.path.split(f.LocalPath())[1] if not change.AffectedFiles(file_filter=header_filter): return [] return output_api.EnsureCQIncludeTrybotsAreAdded( cl, [ 'master.tryserver.chromium.linux:linux_chromium_rel_ng' ], 'Automatically added layout test trybots to run tests on CQ.')
[ "def", "PostUploadHook", "(", "cl", ",", "change", ",", "output_api", ")", ":", "def", "header_filter", "(", "f", ")", ":", "return", "'.h'", "in", "os", ".", "path", ".", "split", "(", "f", ".", "LocalPath", "(", ")", ")", "[", "1", "]", "if", "not", "change", ".", "AffectedFiles", "(", "file_filter", "=", "header_filter", ")", ":", "return", "[", "]", "return", "output_api", ".", "EnsureCQIncludeTrybotsAreAdded", "(", "cl", ",", "[", "'master.tryserver.chromium.linux:linux_chromium_rel_ng'", "]", ",", "'Automatically added layout test trybots to run tests on CQ.'", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/include/PRESUBMIT.py#L14-L29
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosmaster/src/rosmaster/threadpool.py
python
MarkedThreadPool.__init__
(self, numThreads)
Initialize the thread pool with numThreads workers.
Initialize the thread pool with numThreads workers.
[ "Initialize", "the", "thread", "pool", "with", "numThreads", "workers", "." ]
def __init__(self, numThreads): """Initialize the thread pool with numThreads workers.""" self.__threads = [] self.__resizeLock = threading.Condition(threading.Lock()) self.__taskLock = threading.Condition(threading.Lock()) self.__tasks = [] self.__markers = set() self.__isJoining = False self.set_thread_count(numThreads)
[ "def", "__init__", "(", "self", ",", "numThreads", ")", ":", "self", ".", "__threads", "=", "[", "]", "self", ".", "__resizeLock", "=", "threading", ".", "Condition", "(", "threading", ".", "Lock", "(", ")", ")", "self", ".", "__taskLock", "=", "threading", ".", "Condition", "(", "threading", ".", "Lock", "(", ")", ")", "self", ".", "__tasks", "=", "[", "]", "self", ".", "__markers", "=", "set", "(", ")", "self", ".", "__isJoining", "=", "False", "self", ".", "set_thread_count", "(", "numThreads", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosmaster/src/rosmaster/threadpool.py#L55-L65
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/optimizer/clip_grad.py
python
clip_grad_norm
( tensors: Union[Tensor, Iterable[Tensor]], max_norm: float, ord: float = 2.0, )
return norm_
r"""Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Args: tensors: an iterable of Tensors or a single Tensor. max_norm: max norm of the gradients. ord: type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: total norm of the parameters (viewed as a single vector).
r"""Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place.
[ "r", "Clips", "gradient", "norm", "of", "an", "iterable", "of", "parameters", ".", "The", "norm", "is", "computed", "over", "all", "gradients", "together", "as", "if", "they", "were", "concatenated", "into", "a", "single", "vector", ".", "Gradients", "are", "modified", "in", "-", "place", "." ]
def clip_grad_norm( tensors: Union[Tensor, Iterable[Tensor]], max_norm: float, ord: float = 2.0, ): r"""Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Args: tensors: an iterable of Tensors or a single Tensor. max_norm: max norm of the gradients. ord: type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: total norm of the parameters (viewed as a single vector). """ push_scope("clip_grad_norm") if isinstance(tensors, Tensor): tensors = [tensors] tensors = [t for t in tensors if t.grad is not None] if len(tensors) == 0: pop_scope("clip_grad_norm") return Tensor(0.0) norm_ = [norm(t.grad.flatten(), ord=ord) for t in tensors] if len(norm_) > 1: norm_ = norm(concat(norm_), ord=ord) else: norm_ = norm_[0] scale = max_norm / (norm_ + 1e-6) scale = minimum(scale, 1) for tensor in tensors: tensor.grad._reset(tensor.grad * scale) pop_scope("clip_grad_norm") return norm_
[ "def", "clip_grad_norm", "(", "tensors", ":", "Union", "[", "Tensor", ",", "Iterable", "[", "Tensor", "]", "]", ",", "max_norm", ":", "float", ",", "ord", ":", "float", "=", "2.0", ",", ")", ":", "push_scope", "(", "\"clip_grad_norm\"", ")", "if", "isinstance", "(", "tensors", ",", "Tensor", ")", ":", "tensors", "=", "[", "tensors", "]", "tensors", "=", "[", "t", "for", "t", "in", "tensors", "if", "t", ".", "grad", "is", "not", "None", "]", "if", "len", "(", "tensors", ")", "==", "0", ":", "pop_scope", "(", "\"clip_grad_norm\"", ")", "return", "Tensor", "(", "0.0", ")", "norm_", "=", "[", "norm", "(", "t", ".", "grad", ".", "flatten", "(", ")", ",", "ord", "=", "ord", ")", "for", "t", "in", "tensors", "]", "if", "len", "(", "norm_", ")", ">", "1", ":", "norm_", "=", "norm", "(", "concat", "(", "norm_", ")", ",", "ord", "=", "ord", ")", "else", ":", "norm_", "=", "norm_", "[", "0", "]", "scale", "=", "max_norm", "/", "(", "norm_", "+", "1e-6", ")", "scale", "=", "minimum", "(", "scale", ",", "1", ")", "for", "tensor", "in", "tensors", ":", "tensor", ".", "grad", ".", "_reset", "(", "tensor", ".", "grad", "*", "scale", ")", "pop_scope", "(", "\"clip_grad_norm\"", ")", "return", "norm_" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/optimizer/clip_grad.py#L19-L51
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/completer.py
python
expand_user
(path:str)
return newpath, tilde_expand, tilde_val
Expand ``~``-style usernames in strings. This is similar to :func:`os.path.expanduser`, but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original '~' instead of its expanded value. Parameters ---------- path : str String to be expanded. If no ~ is present, the output is the same as the input. Returns ------- newpath : str Result of ~ expansion in the input path. tilde_expand : bool Whether any expansion was performed or not. tilde_val : str The value that ~ was replaced with.
Expand ``~``-style usernames in strings.
[ "Expand", "~", "-", "style", "usernames", "in", "strings", "." ]
def expand_user(path:str) -> Tuple[str, bool, str]: """Expand ``~``-style usernames in strings. This is similar to :func:`os.path.expanduser`, but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original '~' instead of its expanded value. Parameters ---------- path : str String to be expanded. If no ~ is present, the output is the same as the input. Returns ------- newpath : str Result of ~ expansion in the input path. tilde_expand : bool Whether any expansion was performed or not. tilde_val : str The value that ~ was replaced with. """ # Default values tilde_expand = False tilde_val = '' newpath = path if path.startswith('~'): tilde_expand = True rest = len(path)-1 newpath = os.path.expanduser(path) if rest: tilde_val = newpath[:-rest] else: tilde_val = newpath return newpath, tilde_expand, tilde_val
[ "def", "expand_user", "(", "path", ":", "str", ")", "->", "Tuple", "[", "str", ",", "bool", ",", "str", "]", ":", "# Default values", "tilde_expand", "=", "False", "tilde_val", "=", "''", "newpath", "=", "path", "if", "path", ".", "startswith", "(", "'~'", ")", ":", "tilde_expand", "=", "True", "rest", "=", "len", "(", "path", ")", "-", "1", "newpath", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "rest", ":", "tilde_val", "=", "newpath", "[", ":", "-", "rest", "]", "else", ":", "tilde_val", "=", "newpath", "return", "newpath", ",", "tilde_expand", ",", "tilde_val" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/completer.py#L252-L289
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/urllib.py
python
FancyURLopener.http_error_407
(self, url, fp, errcode, errmsg, headers, data=None)
Error 407 -- proxy authentication required. This function supports Basic authentication only.
Error 407 -- proxy authentication required. This function supports Basic authentication only.
[ "Error", "407", "--", "proxy", "authentication", "required", ".", "This", "function", "supports", "Basic", "authentication", "only", "." ]
def http_error_407(self, url, fp, errcode, errmsg, headers, data=None): """Error 407 -- proxy authentication required. This function supports Basic authentication only.""" if not 'proxy-authenticate' in headers: URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) stuff = headers['proxy-authenticate'] import re match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff) if not match: URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) scheme, realm = match.groups() if scheme.lower() != 'basic': URLopener.http_error_default(self, url, fp, errcode, errmsg, headers) name = 'retry_proxy_' + self.type + '_basic_auth' if data is None: return getattr(self,name)(url, realm) else: return getattr(self,name)(url, realm, data)
[ "def", "http_error_407", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "if", "not", "'proxy-authenticate'", "in", "headers", ":", "URLopener", ".", "http_error_default", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ")", "stuff", "=", "headers", "[", "'proxy-authenticate'", "]", "import", "re", "match", "=", "re", ".", "match", "(", "'[ \\t]*([^ \\t]+)[ \\t]+realm=\"([^\"]*)\"'", ",", "stuff", ")", "if", "not", "match", ":", "URLopener", ".", "http_error_default", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ")", "scheme", ",", "realm", "=", "match", ".", "groups", "(", ")", "if", "scheme", ".", "lower", "(", ")", "!=", "'basic'", ":", "URLopener", ".", "http_error_default", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ")", "name", "=", "'retry_proxy_'", "+", "self", ".", "type", "+", "'_basic_auth'", "if", "data", "is", "None", ":", "return", "getattr", "(", "self", ",", "name", ")", "(", "url", ",", "realm", ")", "else", ":", "return", "getattr", "(", "self", ",", "name", ")", "(", "url", ",", "realm", ",", "data", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/urllib.py#L692-L712
VelsonWang/HmiFuncDesigner
439265da17bd3424e678932cbfbc0237b52630f3
HmiFuncDesigner/libs/qscintilla/Python/configure.py
python
ModuleConfiguration.get_mac_wrapped_library_file
(target_configuration)
return os.path.join(lib_dir, 'libqscintilla2_qt%s%s.%s.dylib' % ( target_configuration.qt_version_str[0], debug, QSCI_API_MAJOR))
Return the full pathname of the file that implements the library being wrapped by the module as it would be called on OS/X so that the module will reference it explicitly without DYLD_LIBRARY_PATH being set. If it is None or an empty string then the default is used. target_configuration is the target configuration.
Return the full pathname of the file that implements the library being wrapped by the module as it would be called on OS/X so that the module will reference it explicitly without DYLD_LIBRARY_PATH being set. If it is None or an empty string then the default is used. target_configuration is the target configuration.
[ "Return", "the", "full", "pathname", "of", "the", "file", "that", "implements", "the", "library", "being", "wrapped", "by", "the", "module", "as", "it", "would", "be", "called", "on", "OS", "/", "X", "so", "that", "the", "module", "will", "reference", "it", "explicitly", "without", "DYLD_LIBRARY_PATH", "being", "set", ".", "If", "it", "is", "None", "or", "an", "empty", "string", "then", "the", "default", "is", "used", ".", "target_configuration", "is", "the", "target", "configuration", "." ]
def get_mac_wrapped_library_file(target_configuration): """ Return the full pathname of the file that implements the library being wrapped by the module as it would be called on OS/X so that the module will reference it explicitly without DYLD_LIBRARY_PATH being set. If it is None or an empty string then the default is used. target_configuration is the target configuration. """ lib_dir = target_configuration.qsci_lib_dir if lib_dir is None: lib_dir = target_configuration.qt_lib_dir debug = '_debug' if target_configuration.debug else '' return os.path.join(lib_dir, 'libqscintilla2_qt%s%s.%s.dylib' % ( target_configuration.qt_version_str[0], debug, QSCI_API_MAJOR))
[ "def", "get_mac_wrapped_library_file", "(", "target_configuration", ")", ":", "lib_dir", "=", "target_configuration", ".", "qsci_lib_dir", "if", "lib_dir", "is", "None", ":", "lib_dir", "=", "target_configuration", ".", "qt_lib_dir", "debug", "=", "'_debug'", "if", "target_configuration", ".", "debug", "else", "''", "return", "os", ".", "path", ".", "join", "(", "lib_dir", ",", "'libqscintilla2_qt%s%s.%s.dylib'", "%", "(", "target_configuration", ".", "qt_version_str", "[", "0", "]", ",", "debug", ",", "QSCI_API_MAJOR", ")", ")" ]
https://github.com/VelsonWang/HmiFuncDesigner/blob/439265da17bd3424e678932cbfbc0237b52630f3/HmiFuncDesigner/libs/qscintilla/Python/configure.py#L320-L337
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/shutil.py
python
_ensure_directory
(path)
Ensure that the parent directory of `path` exists
Ensure that the parent directory of `path` exists
[ "Ensure", "that", "the", "parent", "directory", "of", "path", "exists" ]
def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
[ "def", "_ensure_directory", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/shutil.py#L654-L658
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
ColourDatabase.Append
(*args, **kwargs)
return _gdi_.ColourDatabase_Append(*args, **kwargs)
Append(self, String name, int red, int green, int blue)
Append(self, String name, int red, int green, int blue)
[ "Append", "(", "self", "String", "name", "int", "red", "int", "green", "int", "blue", ")" ]
def Append(*args, **kwargs): """Append(self, String name, int red, int green, int blue)""" return _gdi_.ColourDatabase_Append(*args, **kwargs)
[ "def", "Append", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "ColourDatabase_Append", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L7095-L7097
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/autocomplete.py
python
AutoComplete.force_open_completions_event
(self, event)
return "break"
(^space) Open completion list, even if a function call is needed.
(^space) Open completion list, even if a function call is needed.
[ "(", "^space", ")", "Open", "completion", "list", "even", "if", "a", "function", "call", "is", "needed", "." ]
def force_open_completions_event(self, event): "(^space) Open completion list, even if a function call is needed." self.open_completions(FORCE) return "break"
[ "def", "force_open_completions_event", "(", "self", ",", "event", ")", ":", "self", ".", "open_completions", "(", "FORCE", ")", "return", "\"break\"" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/autocomplete.py#L57-L60
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/cluster/hierarchy.py
python
single
(y)
return linkage(y, method='single', metric='euclidean')
Performs single/min/nearest linkage on the condensed distance matrix ``y`` Parameters ---------- y : ndarray The upper triangular of the distance matrix. The result of ``pdist`` is returned in this form. Returns ------- Z : ndarray The linkage matrix. See Also -------- linkage: for advanced creation of hierarchical clusterings.
Performs single/min/nearest linkage on the condensed distance matrix ``y``
[ "Performs", "single", "/", "min", "/", "nearest", "linkage", "on", "the", "condensed", "distance", "matrix", "y" ]
def single(y): """ Performs single/min/nearest linkage on the condensed distance matrix ``y`` Parameters ---------- y : ndarray The upper triangular of the distance matrix. The result of ``pdist`` is returned in this form. Returns ------- Z : ndarray The linkage matrix. See Also -------- linkage: for advanced creation of hierarchical clusterings. """ return linkage(y, method='single', metric='euclidean')
[ "def", "single", "(", "y", ")", ":", "return", "linkage", "(", "y", ",", "method", "=", "'single'", ",", "metric", "=", "'euclidean'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/cluster/hierarchy.py#L241-L261
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_3_5_0.py
python
MiroInterpreter.do_mythtv_update_autodownload
(self, line)
Update feeds and auto-download
Update feeds and auto-download
[ "Update", "feeds", "and", "auto", "-", "download" ]
def do_mythtv_update_autodownload(self, line): """Update feeds and auto-download""" logging.info("Starting auto downloader...") autodler.start_downloader() feed.expire_items() logging.info("Starting video data updates") #item.update_incomplete_movie_data() # Miro Bridge ignores this data anyway moviedata.movie_data_updater.start_thread() commandline.startup() #autoupdate.check_for_updates() # I think this is autoupdate for the Miro code not videos # Wait a bit before starting the downloader daemon. It can cause a bunch # of disk/CPU load, so try to avoid it slowing other stuff down. eventloop.add_timeout(5, downloader.startup_downloader, "start downloader daemon") # ditto for feed updates eventloop.add_timeout(30, feed.start_updates, "start feed updates") # ditto for clearing stale icon cache files, except it's the very lowest # priority eventloop.add_timeout(10, clear_icon_cache_orphans, "clear orphans")
[ "def", "do_mythtv_update_autodownload", "(", "self", ",", "line", ")", ":", "logging", ".", "info", "(", "\"Starting auto downloader...\"", ")", "autodler", ".", "start_downloader", "(", ")", "feed", ".", "expire_items", "(", ")", "logging", ".", "info", "(", "\"Starting video data updates\"", ")", "#item.update_incomplete_movie_data() # Miro Bridge ignores this data anyway", "moviedata", ".", "movie_data_updater", ".", "start_thread", "(", ")", "commandline", ".", "startup", "(", ")", "#autoupdate.check_for_updates() # I think this is autoupdate for the Miro code not videos", "# Wait a bit before starting the downloader daemon. It can cause a bunch", "# of disk/CPU load, so try to avoid it slowing other stuff down.", "eventloop", ".", "add_timeout", "(", "5", ",", "downloader", ".", "startup_downloader", ",", "\"start downloader daemon\"", ")", "# ditto for feed updates", "eventloop", ".", "add_timeout", "(", "30", ",", "feed", ".", "start_updates", ",", "\"start feed updates\"", ")", "# ditto for clearing stale icon cache files, except it's the very lowest", "# priority", "eventloop", ".", "add_timeout", "(", "10", ",", "clear_icon_cache_orphans", ",", "\"clear orphans\"", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/contrib/imports/mirobridge/mirobridge/mirobridge_interpreter_3_5_0.py#L218-L237
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.AddImplicitPostbuilds
( self, configname, output, output_binary, postbuilds=[], quiet=False )
return pre + postbuilds + post
Returns a list of shell commands that should run before and after |postbuilds|.
Returns a list of shell commands that should run before and after |postbuilds|.
[ "Returns", "a", "list", "of", "shell", "commands", "that", "should", "run", "before", "and", "after", "|postbuilds|", "." ]
def AddImplicitPostbuilds( self, configname, output, output_binary, postbuilds=[], quiet=False ): """Returns a list of shell commands that should run before and after |postbuilds|.""" assert output_binary is not None pre = self._GetTargetPostbuilds(configname, output, output_binary, quiet) post = self._GetIOSPostbuilds(configname, output_binary) return pre + postbuilds + post
[ "def", "AddImplicitPostbuilds", "(", "self", ",", "configname", ",", "output", ",", "output_binary", ",", "postbuilds", "=", "[", "]", ",", "quiet", "=", "False", ")", ":", "assert", "output_binary", "is", "not", "None", "pre", "=", "self", ".", "_GetTargetPostbuilds", "(", "configname", ",", "output", ",", "output_binary", ",", "quiet", ")", "post", "=", "self", ".", "_GetIOSPostbuilds", "(", "configname", ",", "output_binary", ")", "return", "pre", "+", "postbuilds", "+", "post" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/xcode_emulation.py#L1236-L1244
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
python
CalculateVariables
(default_variables, params)
Calculate additional variables for use in the build (called by gyp).
Calculate additional variables for use in the build (called by gyp).
[ "Calculate", "additional", "variables", "for", "use", "in", "the", "build", "(", "called", "by", "gyp", ")", "." ]
def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) elif flavor == 'win': exts = gyp.MSVSUtil.TARGET_TYPE_EXT default_variables.setdefault('OS', 'win') default_variables['EXECUTABLE_SUFFIX'] = '.' + exts['executable'] default_variables['STATIC_LIB_PREFIX'] = '' default_variables['STATIC_LIB_SUFFIX'] = '.' + exts['static_library'] default_variables['SHARED_LIB_PREFIX'] = '' default_variables['SHARED_LIB_SUFFIX'] = '.' + exts['shared_library'] # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR', os.path.join('$!PRODUCT_DIR', 'lib')) default_variables.setdefault('LIB_DIR', os.path.join('$!PRODUCT_DIR', 'obj'))
[ "def", "CalculateVariables", "(", "default_variables", ",", "params", ")", ":", "global", "generator_additional_non_configuration_keys", "global", "generator_additional_path_sections", "flavor", "=", "gyp", ".", "common", ".", "GetFlavor", "(", "params", ")", "if", "flavor", "==", "'mac'", ":", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'mac'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.dylib'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "# Copy additional generator configuration data from Xcode, which is shared", "# by the Mac Ninja generator.", "import", "gyp", ".", "generator", ".", "xcode", "as", "xcode_generator", "generator_additional_non_configuration_keys", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "generator_additional_path_sections", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "global", "generator_extra_sources_for_rules", "generator_extra_sources_for_rules", "=", "getattr", "(", "xcode_generator", ",", "'generator_extra_sources_for_rules'", ",", "[", "]", ")", "elif", "flavor", "==", "'win'", ":", "exts", "=", "gyp", ".", "MSVSUtil", ".", "TARGET_TYPE_EXT", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'win'", ")", "default_variables", "[", "'EXECUTABLE_SUFFIX'", "]", "=", "'.'", "+", "exts", "[", "'executable'", "]", "default_variables", "[", "'STATIC_LIB_PREFIX'", "]", "=", "''", "default_variables", "[", "'STATIC_LIB_SUFFIX'", "]", "=", "'.'", "+", "exts", "[", "'static_library'", "]", "default_variables", "[", "'SHARED_LIB_PREFIX'", "]", "=", "''", "default_variables", "[", "'SHARED_LIB_SUFFIX'", "]", "=", "'.'", "+", "exts", "[", "'shared_library'", "]", "# Copy additional generator configuration data from VS, which is shared", "# by the Windows Ninja generator.", "import", "gyp", ".", "generator", ".", "msvs", "as", "msvs_generator", "generator_additional_non_configuration_keys", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "generator_additional_path_sections", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "gyp", ".", "msvs_emulation", ".", "CalculateCommonVariables", "(", "default_variables", ",", "params", ")", "else", ":", "operating_system", "=", "flavor", "if", "flavor", "==", "'android'", ":", "operating_system", "=", "'linux'", "# Keep this legacy behavior for now.", "default_variables", ".", "setdefault", "(", "'OS'", ",", "operating_system", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.so'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "os", ".", "path", ".", "join", "(", "'$!PRODUCT_DIR'", ",", "'lib'", ")", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "os", ".", "path", ".", "join", "(", "'$!PRODUCT_DIR'", ",", "'obj'", ")", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L1594-L1644
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlPrintout.SetFooter
(*args, **kwargs)
return _html.HtmlPrintout_SetFooter(*args, **kwargs)
SetFooter(self, String footer, int pg=PAGE_ALL)
SetFooter(self, String footer, int pg=PAGE_ALL)
[ "SetFooter", "(", "self", "String", "footer", "int", "pg", "=", "PAGE_ALL", ")" ]
def SetFooter(*args, **kwargs): """SetFooter(self, String footer, int pg=PAGE_ALL)""" return _html.HtmlPrintout_SetFooter(*args, **kwargs)
[ "def", "SetFooter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlPrintout_SetFooter", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L1288-L1290
yuxng/DA-RNN
77fbb50b4272514588a10a9f90b7d5f8d46974fb
lib/datasets/gmu_scene.py
python
gmu_scene.label_path_at
(self, i)
return self.label_path_from_index(self.image_index[i])
Return the absolute path to metadata i in the image sequence.
Return the absolute path to metadata i in the image sequence.
[ "Return", "the", "absolute", "path", "to", "metadata", "i", "in", "the", "image", "sequence", "." ]
def label_path_at(self, i): """ Return the absolute path to metadata i in the image sequence. """ return self.label_path_from_index(self.image_index[i])
[ "def", "label_path_at", "(", "self", ",", "i", ")", ":", "return", "self", ".", "label_path_from_index", "(", "self", ".", "image_index", "[", "i", "]", ")" ]
https://github.com/yuxng/DA-RNN/blob/77fbb50b4272514588a10a9f90b7d5f8d46974fb/lib/datasets/gmu_scene.py#L71-L75
OPAE/opae-sdk
221124343c8275243a249eb72d69e0ea2d568d1b
python/opae.admin/opae/admin/tools/ihex2ipmi.py
python
bmc_convert
(ctype, ifile, ofile)
return 0
Main conversion. Validate after writing.
Main conversion. Validate after writing.
[ "Main", "conversion", ".", "Validate", "after", "writing", "." ]
def bmc_convert(ctype, ifile, ofile): """ Main conversion. Validate after writing. """ bw_bmc = BittwareBmc(None, ifile) bw_bmc.set_ofile(ofile) if ctype == 'bmc_bl': bw_bmc.write_partitions(bw_bmc.BW_ACT_APP_BL) elif ctype == 'bmc_app': bw_bmc.write_partitions(bw_bmc.BW_ACT_APP_MAIN) else: raise Exception("unknown ctype: %s" % (ctype)) pad_bytes = 1024 - (ofile.tell() - ((ofile.tell() / 1024) * 1024)) if pad_bytes > 0: padding = [0x0 for _ in range(pad_bytes)] ofile.write(bytearray(padding)) print("Validating") bw_bmc.validate(ctype) return 0
[ "def", "bmc_convert", "(", "ctype", ",", "ifile", ",", "ofile", ")", ":", "bw_bmc", "=", "BittwareBmc", "(", "None", ",", "ifile", ")", "bw_bmc", ".", "set_ofile", "(", "ofile", ")", "if", "ctype", "==", "'bmc_bl'", ":", "bw_bmc", ".", "write_partitions", "(", "bw_bmc", ".", "BW_ACT_APP_BL", ")", "elif", "ctype", "==", "'bmc_app'", ":", "bw_bmc", ".", "write_partitions", "(", "bw_bmc", ".", "BW_ACT_APP_MAIN", ")", "else", ":", "raise", "Exception", "(", "\"unknown ctype: %s\"", "%", "(", "ctype", ")", ")", "pad_bytes", "=", "1024", "-", "(", "ofile", ".", "tell", "(", ")", "-", "(", "(", "ofile", ".", "tell", "(", ")", "/", "1024", ")", "*", "1024", ")", ")", "if", "pad_bytes", ">", "0", ":", "padding", "=", "[", "0x0", "for", "_", "in", "range", "(", "pad_bytes", ")", "]", "ofile", ".", "write", "(", "bytearray", "(", "padding", ")", ")", "print", "(", "\"Validating\"", ")", "bw_bmc", ".", "validate", "(", "ctype", ")", "return", "0" ]
https://github.com/OPAE/opae-sdk/blob/221124343c8275243a249eb72d69e0ea2d568d1b/python/opae.admin/opae/admin/tools/ihex2ipmi.py#L237-L258
CNevd/Difacto_DMLC
f16862e35062707b1cf7e37d04d9b6ae34bbfd28
dmlc-core/tracker/tracker.py
python
RabitTracker.get_ring
(self, tree_map, parent_map)
return ring_map
get a ring connection used to recover local data
get a ring connection used to recover local data
[ "get", "a", "ring", "connection", "used", "to", "recover", "local", "data" ]
def get_ring(self, tree_map, parent_map): """ get a ring connection used to recover local data """ assert parent_map[0] == -1 rlst = self.find_share_ring(tree_map, parent_map, 0) assert len(rlst) == len(tree_map) ring_map = {} nslave = len(tree_map) for r in range(nslave): rprev = (r + nslave - 1) % nslave rnext = (r + 1) % nslave ring_map[rlst[r]] = (rlst[rprev], rlst[rnext]) return ring_map
[ "def", "get_ring", "(", "self", ",", "tree_map", ",", "parent_map", ")", ":", "assert", "parent_map", "[", "0", "]", "==", "-", "1", "rlst", "=", "self", ".", "find_share_ring", "(", "tree_map", ",", "parent_map", ",", "0", ")", "assert", "len", "(", "rlst", ")", "==", "len", "(", "tree_map", ")", "ring_map", "=", "{", "}", "nslave", "=", "len", "(", "tree_map", ")", "for", "r", "in", "range", "(", "nslave", ")", ":", "rprev", "=", "(", "r", "+", "nslave", "-", "1", ")", "%", "nslave", "rnext", "=", "(", "r", "+", "1", ")", "%", "nslave", "ring_map", "[", "rlst", "[", "r", "]", "]", "=", "(", "rlst", "[", "rprev", "]", ",", "rlst", "[", "rnext", "]", ")", "return", "ring_map" ]
https://github.com/CNevd/Difacto_DMLC/blob/f16862e35062707b1cf7e37d04d9b6ae34bbfd28/dmlc-core/tracker/tracker.py#L193-L206
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
native_client_sdk/src/project_templates/init_project.py
python
GetTargetFileName
(source_file_name, project_name)
return target_file_name
Converts a source file name into a project file name. Args: source_file_name: The name of a file that is to be included in the project stub, as it appears at the source location. project_name: The name of the project that is being generated. Returns: The target file name for a given source file. All project files are run through this filter and it modifies them as needed.
Converts a source file name into a project file name.
[ "Converts", "a", "source", "file", "name", "into", "a", "project", "file", "name", "." ]
def GetTargetFileName(source_file_name, project_name): """Converts a source file name into a project file name. Args: source_file_name: The name of a file that is to be included in the project stub, as it appears at the source location. project_name: The name of the project that is being generated. Returns: The target file name for a given source file. All project files are run through this filter and it modifies them as needed. """ target_file_name = '' if source_file_name.startswith(PROJECT_FILE_NAME): target_file_name = source_file_name.replace(PROJECT_FILE_NAME, project_name) else: target_file_name = source_file_name return target_file_name
[ "def", "GetTargetFileName", "(", "source_file_name", ",", "project_name", ")", ":", "target_file_name", "=", "''", "if", "source_file_name", ".", "startswith", "(", "PROJECT_FILE_NAME", ")", ":", "target_file_name", "=", "source_file_name", ".", "replace", "(", "PROJECT_FILE_NAME", ",", "project_name", ")", "else", ":", "target_file_name", "=", "source_file_name", "return", "target_file_name" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/project_templates/init_project.py#L174-L192
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_grad.py
python
_FresnelCosGrad
(op, grad)
Compute gradient of fresnel_cos(x) with respect to its argument.
Compute gradient of fresnel_cos(x) with respect to its argument.
[ "Compute", "gradient", "of", "fresnel_cos", "(", "x", ")", "with", "respect", "to", "its", "argument", "." ]
def _FresnelCosGrad(op, grad): """Compute gradient of fresnel_cos(x) with respect to its argument.""" x = op.inputs[0] with ops.control_dependencies([grad]): return grad * math_ops.cos((np.pi / 2.) * math_ops.square(x))
[ "def", "_FresnelCosGrad", "(", "op", ",", "grad", ")", ":", "x", "=", "op", ".", "inputs", "[", "0", "]", "with", "ops", ".", "control_dependencies", "(", "[", "grad", "]", ")", ":", "return", "grad", "*", "math_ops", ".", "cos", "(", "(", "np", ".", "pi", "/", "2.", ")", "*", "math_ops", ".", "square", "(", "x", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L901-L905
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py
python
auc
(labels, predictions, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, curve='ROC', name=None, summation_method='trapezoidal', thresholds=None)
Computes the approximate AUC via a Riemann sum. The `auc` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the AUC. To discretize the AUC curve, a linearly spaced set of thresholds is used to compute pairs of recall and precision values. The area under the ROC-curve is therefore computed using the height of the recall values by the false positive rate, while the area under the PR-curve is the computed using the height of the precision values by the recall. This value is ultimately returned as `auc`, an idempotent operation that computes the area under a discretized curve of precision versus recall values (computed using the aforementioned variables). The `num_thresholds` variable controls the degree of discretization with larger numbers of thresholds more closely approximating the true AUC. The quality of the approximation may vary dramatically depending on `num_thresholds`. For best results, `predictions` should be distributed approximately uniformly in the range [0, 1] and not peaked around 0 or 1. The quality of the AUC approximation may be poor if this is not the case. Setting `summation_method` to 'minoring' or 'majoring' can help quantify the error in the approximation by providing lower or upper bound estimate of the AUC. The `thresholds` parameter can be used to manually specify thresholds which split the predictions more evenly. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `auc`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). num_thresholds: The number of thresholds to use when discretizing the roc curve. metrics_collections: An optional list of collections that `auc` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. curve: Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve. name: An optional variable_scope name. summation_method: Specifies the Riemann summation method used (https://en.wikipedia.org/wiki/Riemann_sum): 'trapezoidal' [default] that applies the trapezoidal rule; 'careful_interpolation', a variant of it differing only by a more correct interpolation scheme for PR-AUC - interpolating (true/false) positives but not the ratio that is precision; 'minoring' that applies left summation for increasing intervals and right summation for decreasing intervals; 'majoring' that does the opposite. Note that 'careful_interpolation' is strictly preferred to 'trapezoidal' (to be deprecated soon) as it applies the same method for ROC, and a better one (see Davis & Goadrich 2006 for details) for the PR curve. thresholds: An optional list of floating point values to use as the thresholds for discretizing the curve. If set, the `num_thresholds` parameter is ignored. Values should be in [0, 1]. Endpoint thresholds equal to {-epsilon, 1+epsilon} for a small positive epsilon value will be automatically included with these to correctly handle predictions equal to exactly 0 or 1. Returns: auc: A scalar `Tensor` representing the current area-under-curve. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `auc`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled.
Computes the approximate AUC via a Riemann sum.
[ "Computes", "the", "approximate", "AUC", "via", "a", "Riemann", "sum", "." ]
def auc(labels, predictions, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, curve='ROC', name=None, summation_method='trapezoidal', thresholds=None): """Computes the approximate AUC via a Riemann sum. The `auc` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the AUC. To discretize the AUC curve, a linearly spaced set of thresholds is used to compute pairs of recall and precision values. The area under the ROC-curve is therefore computed using the height of the recall values by the false positive rate, while the area under the PR-curve is the computed using the height of the precision values by the recall. This value is ultimately returned as `auc`, an idempotent operation that computes the area under a discretized curve of precision versus recall values (computed using the aforementioned variables). The `num_thresholds` variable controls the degree of discretization with larger numbers of thresholds more closely approximating the true AUC. The quality of the approximation may vary dramatically depending on `num_thresholds`. For best results, `predictions` should be distributed approximately uniformly in the range [0, 1] and not peaked around 0 or 1. The quality of the AUC approximation may be poor if this is not the case. Setting `summation_method` to 'minoring' or 'majoring' can help quantify the error in the approximation by providing lower or upper bound estimate of the AUC. The `thresholds` parameter can be used to manually specify thresholds which split the predictions more evenly. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `auc`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). num_thresholds: The number of thresholds to use when discretizing the roc curve. metrics_collections: An optional list of collections that `auc` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. curve: Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve. name: An optional variable_scope name. summation_method: Specifies the Riemann summation method used (https://en.wikipedia.org/wiki/Riemann_sum): 'trapezoidal' [default] that applies the trapezoidal rule; 'careful_interpolation', a variant of it differing only by a more correct interpolation scheme for PR-AUC - interpolating (true/false) positives but not the ratio that is precision; 'minoring' that applies left summation for increasing intervals and right summation for decreasing intervals; 'majoring' that does the opposite. Note that 'careful_interpolation' is strictly preferred to 'trapezoidal' (to be deprecated soon) as it applies the same method for ROC, and a better one (see Davis & Goadrich 2006 for details) for the PR curve. thresholds: An optional list of floating point values to use as the thresholds for discretizing the curve. If set, the `num_thresholds` parameter is ignored. Values should be in [0, 1]. Endpoint thresholds equal to {-epsilon, 1+epsilon} for a small positive epsilon value will be automatically included with these to correctly handle predictions equal to exactly 0 or 1. Returns: auc: A scalar `Tensor` representing the current area-under-curve. update_op: An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `auc`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled. """ if context.executing_eagerly(): raise RuntimeError('tf.metrics.auc is not supported when eager execution ' 'is enabled.') with variable_scope.variable_scope(name, 'auc', (labels, predictions, weights)): if curve != 'ROC' and curve != 'PR': raise ValueError('curve must be either ROC or PR, %s unknown' % (curve)) kepsilon = 1e-7 # To account for floating point imprecisions. if thresholds is not None: # If specified, use the supplied thresholds. thresholds = sorted(thresholds) num_thresholds = len(thresholds) + 2 else: # Otherwise, linearly interpolate (num_thresholds - 2) thresholds in # (0, 1). thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds - 2)] # Add an endpoint "threshold" below zero and above one for either threshold # method. thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon] values, update_ops = _confusion_matrix_at_thresholds( labels, predictions, thresholds, weights) # Add epsilons to avoid dividing by 0. epsilon = 1.0e-6 def interpolate_pr_auc(tp, fp, fn): """Interpolation formula inspired by section 4 of Davis & Goadrich 2006. Note here we derive & use a closed formula not present in the paper - as follows: Modeling all of TP (true positive weight), FP (false positive weight) and their sum P = TP + FP (positive weight) as varying linearly within each interval [A, B] between successive thresholds, we get Precision = (TP_A + slope * (P - P_A)) / P with slope = dTP / dP = (TP_B - TP_A) / (P_B - P_A). The area within the interval is thus (slope / total_pos_weight) times int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P} int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P} where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A) Bringing back the factor (slope / total_pos_weight) we'd put aside, we get slope * [dTP + intercept * log(P_B / P_A)] / total_pos_weight where dTP == TP_B - TP_A. Note that when P_A == 0 the above calculation simplifies into int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A) which is really equivalent to imputing constant precision throughout the first bucket having >0 true positives. Args: tp: true positive counts fp: false positive counts fn: false negative counts Returns: pr_auc: an approximation of the area under the P-R curve. """ dtp = tp[:num_thresholds - 1] - tp[1:] p = tp + fp prec_slope = math_ops.div_no_nan( dtp, math_ops.maximum(p[:num_thresholds - 1] - p[1:], 0), name='prec_slope') intercept = tp[1:] - math_ops.multiply(prec_slope, p[1:]) safe_p_ratio = array_ops.where( math_ops.logical_and(p[:num_thresholds - 1] > 0, p[1:] > 0), math_ops.div_no_nan( p[:num_thresholds - 1], math_ops.maximum(p[1:], 0), name='recall_relative_ratio'), array_ops.ones_like(p[1:])) return math_ops.reduce_sum( math_ops.div_no_nan( prec_slope * (dtp + intercept * math_ops.log(safe_p_ratio)), math_ops.maximum(tp[1:] + fn[1:], 0), name='pr_auc_increment'), name='interpolate_pr_auc') def compute_auc(tp, fn, tn, fp, name): """Computes the roc-auc or pr-auc based on confusion counts.""" if curve == 'PR': if summation_method == 'trapezoidal': logging.warning( 'Trapezoidal rule is known to produce incorrect PR-AUCs; ' 'please switch to "careful_interpolation" instead.') elif summation_method == 'careful_interpolation': # This one is a bit tricky and is handled separately. return interpolate_pr_auc(tp, fp, fn) rec = math_ops.div(tp + epsilon, tp + fn + epsilon) if curve == 'ROC': fp_rate = math_ops.div(fp, fp + tn + epsilon) x = fp_rate y = rec else: # curve == 'PR'. prec = math_ops.div(tp + epsilon, tp + fp + epsilon) x = rec y = prec if summation_method in ('trapezoidal', 'careful_interpolation'): # Note that the case ('PR', 'careful_interpolation') has been handled # above. return math_ops.reduce_sum( math_ops.multiply(x[:num_thresholds - 1] - x[1:], (y[:num_thresholds - 1] + y[1:]) / 2.), name=name) elif summation_method == 'minoring': return math_ops.reduce_sum( math_ops.multiply(x[:num_thresholds - 1] - x[1:], math_ops.minimum(y[:num_thresholds - 1], y[1:])), name=name) elif summation_method == 'majoring': return math_ops.reduce_sum( math_ops.multiply(x[:num_thresholds - 1] - x[1:], math_ops.maximum(y[:num_thresholds - 1], y[1:])), name=name) else: raise ValueError('Invalid summation_method: %s' % summation_method) # sum up the areas of all the trapeziums def compute_auc_value(_, values): return compute_auc(values['tp'], values['fn'], values['tn'], values['fp'], 'value') auc_value = _aggregate_across_replicas( metrics_collections, compute_auc_value, values) update_op = compute_auc(update_ops['tp'], update_ops['fn'], update_ops['tn'], update_ops['fp'], 'update_op') if updates_collections: ops.add_to_collections(updates_collections, update_op) return auc_value, update_op
[ "def", "auc", "(", "labels", ",", "predictions", ",", "weights", "=", "None", ",", "num_thresholds", "=", "200", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "curve", "=", "'ROC'", ",", "name", "=", "None", ",", "summation_method", "=", "'trapezoidal'", ",", "thresholds", "=", "None", ")", ":", "if", "context", ".", "executing_eagerly", "(", ")", ":", "raise", "RuntimeError", "(", "'tf.metrics.auc is not supported when eager execution '", "'is enabled.'", ")", "with", "variable_scope", ".", "variable_scope", "(", "name", ",", "'auc'", ",", "(", "labels", ",", "predictions", ",", "weights", ")", ")", ":", "if", "curve", "!=", "'ROC'", "and", "curve", "!=", "'PR'", ":", "raise", "ValueError", "(", "'curve must be either ROC or PR, %s unknown'", "%", "(", "curve", ")", ")", "kepsilon", "=", "1e-7", "# To account for floating point imprecisions.", "if", "thresholds", "is", "not", "None", ":", "# If specified, use the supplied thresholds.", "thresholds", "=", "sorted", "(", "thresholds", ")", "num_thresholds", "=", "len", "(", "thresholds", ")", "+", "2", "else", ":", "# Otherwise, linearly interpolate (num_thresholds - 2) thresholds in", "# (0, 1).", "thresholds", "=", "[", "(", "i", "+", "1", ")", "*", "1.0", "/", "(", "num_thresholds", "-", "1", ")", "for", "i", "in", "range", "(", "num_thresholds", "-", "2", ")", "]", "# Add an endpoint \"threshold\" below zero and above one for either threshold", "# method.", "thresholds", "=", "[", "0.0", "-", "kepsilon", "]", "+", "thresholds", "+", "[", "1.0", "+", "kepsilon", "]", "values", ",", "update_ops", "=", "_confusion_matrix_at_thresholds", "(", "labels", ",", "predictions", ",", "thresholds", ",", "weights", ")", "# Add epsilons to avoid dividing by 0.", "epsilon", "=", "1.0e-6", "def", "interpolate_pr_auc", "(", "tp", ",", "fp", ",", "fn", ")", ":", "\"\"\"Interpolation formula inspired by section 4 of Davis & Goadrich 2006.\n\n Note here we derive & use a closed formula not present in the paper\n - as follows:\n Modeling all of TP (true positive weight),\n FP (false positive weight) and their sum P = TP + FP (positive weight)\n as varying linearly within each interval [A, B] between successive\n thresholds, we get\n Precision = (TP_A + slope * (P - P_A)) / P\n with slope = dTP / dP = (TP_B - TP_A) / (P_B - P_A).\n The area within the interval is thus (slope / total_pos_weight) times\n int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P}\n int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P}\n where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in\n int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A)\n Bringing back the factor (slope / total_pos_weight) we'd put aside, we get\n slope * [dTP + intercept * log(P_B / P_A)] / total_pos_weight\n where dTP == TP_B - TP_A.\n Note that when P_A == 0 the above calculation simplifies into\n int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A)\n which is really equivalent to imputing constant precision throughout the\n first bucket having >0 true positives.\n\n Args:\n tp: true positive counts\n fp: false positive counts\n fn: false negative counts\n Returns:\n pr_auc: an approximation of the area under the P-R curve.\n \"\"\"", "dtp", "=", "tp", "[", ":", "num_thresholds", "-", "1", "]", "-", "tp", "[", "1", ":", "]", "p", "=", "tp", "+", "fp", "prec_slope", "=", "math_ops", ".", "div_no_nan", "(", "dtp", ",", "math_ops", ".", "maximum", "(", "p", "[", ":", "num_thresholds", "-", "1", "]", "-", "p", "[", "1", ":", "]", ",", "0", ")", ",", "name", "=", "'prec_slope'", ")", "intercept", "=", "tp", "[", "1", ":", "]", "-", "math_ops", ".", "multiply", "(", "prec_slope", ",", "p", "[", "1", ":", "]", ")", "safe_p_ratio", "=", "array_ops", ".", "where", "(", "math_ops", ".", "logical_and", "(", "p", "[", ":", "num_thresholds", "-", "1", "]", ">", "0", ",", "p", "[", "1", ":", "]", ">", "0", ")", ",", "math_ops", ".", "div_no_nan", "(", "p", "[", ":", "num_thresholds", "-", "1", "]", ",", "math_ops", ".", "maximum", "(", "p", "[", "1", ":", "]", ",", "0", ")", ",", "name", "=", "'recall_relative_ratio'", ")", ",", "array_ops", ".", "ones_like", "(", "p", "[", "1", ":", "]", ")", ")", "return", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "div_no_nan", "(", "prec_slope", "*", "(", "dtp", "+", "intercept", "*", "math_ops", ".", "log", "(", "safe_p_ratio", ")", ")", ",", "math_ops", ".", "maximum", "(", "tp", "[", "1", ":", "]", "+", "fn", "[", "1", ":", "]", ",", "0", ")", ",", "name", "=", "'pr_auc_increment'", ")", ",", "name", "=", "'interpolate_pr_auc'", ")", "def", "compute_auc", "(", "tp", ",", "fn", ",", "tn", ",", "fp", ",", "name", ")", ":", "\"\"\"Computes the roc-auc or pr-auc based on confusion counts.\"\"\"", "if", "curve", "==", "'PR'", ":", "if", "summation_method", "==", "'trapezoidal'", ":", "logging", ".", "warning", "(", "'Trapezoidal rule is known to produce incorrect PR-AUCs; '", "'please switch to \"careful_interpolation\" instead.'", ")", "elif", "summation_method", "==", "'careful_interpolation'", ":", "# This one is a bit tricky and is handled separately.", "return", "interpolate_pr_auc", "(", "tp", ",", "fp", ",", "fn", ")", "rec", "=", "math_ops", ".", "div", "(", "tp", "+", "epsilon", ",", "tp", "+", "fn", "+", "epsilon", ")", "if", "curve", "==", "'ROC'", ":", "fp_rate", "=", "math_ops", ".", "div", "(", "fp", ",", "fp", "+", "tn", "+", "epsilon", ")", "x", "=", "fp_rate", "y", "=", "rec", "else", ":", "# curve == 'PR'.", "prec", "=", "math_ops", ".", "div", "(", "tp", "+", "epsilon", ",", "tp", "+", "fp", "+", "epsilon", ")", "x", "=", "rec", "y", "=", "prec", "if", "summation_method", "in", "(", "'trapezoidal'", ",", "'careful_interpolation'", ")", ":", "# Note that the case ('PR', 'careful_interpolation') has been handled", "# above.", "return", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "multiply", "(", "x", "[", ":", "num_thresholds", "-", "1", "]", "-", "x", "[", "1", ":", "]", ",", "(", "y", "[", ":", "num_thresholds", "-", "1", "]", "+", "y", "[", "1", ":", "]", ")", "/", "2.", ")", ",", "name", "=", "name", ")", "elif", "summation_method", "==", "'minoring'", ":", "return", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "multiply", "(", "x", "[", ":", "num_thresholds", "-", "1", "]", "-", "x", "[", "1", ":", "]", ",", "math_ops", ".", "minimum", "(", "y", "[", ":", "num_thresholds", "-", "1", "]", ",", "y", "[", "1", ":", "]", ")", ")", ",", "name", "=", "name", ")", "elif", "summation_method", "==", "'majoring'", ":", "return", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "multiply", "(", "x", "[", ":", "num_thresholds", "-", "1", "]", "-", "x", "[", "1", ":", "]", ",", "math_ops", ".", "maximum", "(", "y", "[", ":", "num_thresholds", "-", "1", "]", ",", "y", "[", "1", ":", "]", ")", ")", ",", "name", "=", "name", ")", "else", ":", "raise", "ValueError", "(", "'Invalid summation_method: %s'", "%", "summation_method", ")", "# sum up the areas of all the trapeziums", "def", "compute_auc_value", "(", "_", ",", "values", ")", ":", "return", "compute_auc", "(", "values", "[", "'tp'", "]", ",", "values", "[", "'fn'", "]", ",", "values", "[", "'tn'", "]", ",", "values", "[", "'fp'", "]", ",", "'value'", ")", "auc_value", "=", "_aggregate_across_replicas", "(", "metrics_collections", ",", "compute_auc_value", ",", "values", ")", "update_op", "=", "compute_auc", "(", "update_ops", "[", "'tp'", "]", ",", "update_ops", "[", "'fn'", "]", ",", "update_ops", "[", "'tn'", "]", ",", "update_ops", "[", "'fp'", "]", ",", "'update_op'", ")", "if", "updates_collections", ":", "ops", ".", "add_to_collections", "(", "updates_collections", ",", "update_op", ")", "return", "auc_value", ",", "update_op" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py#L630-L850
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/rook/rook_cluster.py
python
KubernetesResource.items
(self)
return self._items.values()
Returns the items of the request. Creates the watcher as a side effect. :return:
Returns the items of the request. Creates the watcher as a side effect. :return:
[ "Returns", "the", "items", "of", "the", "request", ".", "Creates", "the", "watcher", "as", "a", "side", "effect", ".", ":", "return", ":" ]
def items(self) -> Iterable[T]: """ Returns the items of the request. Creates the watcher as a side effect. :return: """ if self.exception: e = self.exception self.exception = None raise e # Propagate the exception to the user. if not self.thread or not self.thread.is_alive(): resource_version = self._fetch() if _urllib3_supports_read_chunked: # Start a thread which will use the kubernetes watch client against a resource log.debug("Attaching resource watcher for k8s {}".format(self.api_func)) self.thread = self._watch(resource_version) return self._items.values()
[ "def", "items", "(", "self", ")", "->", "Iterable", "[", "T", "]", ":", "if", "self", ".", "exception", ":", "e", "=", "self", ".", "exception", "self", ".", "exception", "=", "None", "raise", "e", "# Propagate the exception to the user.", "if", "not", "self", ".", "thread", "or", "not", "self", ".", "thread", ".", "is_alive", "(", ")", ":", "resource_version", "=", "self", ".", "_fetch", "(", ")", "if", "_urllib3_supports_read_chunked", ":", "# Start a thread which will use the kubernetes watch client against a resource", "log", ".", "debug", "(", "\"Attaching resource watcher for k8s {}\"", ".", "format", "(", "self", ".", "api_func", ")", ")", "self", ".", "thread", "=", "self", ".", "_watch", "(", "resource_version", ")", "return", "self", ".", "_items", ".", "values", "(", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/rook/rook_cluster.py#L249-L266
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/EnggCalibrateFull.py
python
EnggCalibrateFull._prepare_ws_for_fitting
(self, ws, bin_width)
return result
Rebins the workspace and converts it to distribution
Rebins the workspace and converts it to distribution
[ "Rebins", "the", "workspace", "and", "converts", "it", "to", "distribution" ]
def _prepare_ws_for_fitting(self, ws, bin_width): """ Rebins the workspace and converts it to distribution """ rebin_alg = self.createChildAlgorithm('Rebin') rebin_alg.setProperty('InputWorkspace', ws) rebin_alg.setProperty('Params', bin_width) rebin_alg.execute() result = rebin_alg.getProperty('OutputWorkspace').value if not result.isDistribution(): convert_alg = self.createChildAlgorithm('ConvertToDistribution') convert_alg.setProperty('Workspace', result) convert_alg.execute() return result
[ "def", "_prepare_ws_for_fitting", "(", "self", ",", "ws", ",", "bin_width", ")", ":", "rebin_alg", "=", "self", ".", "createChildAlgorithm", "(", "'Rebin'", ")", "rebin_alg", ".", "setProperty", "(", "'InputWorkspace'", ",", "ws", ")", "rebin_alg", ".", "setProperty", "(", "'Params'", ",", "bin_width", ")", "rebin_alg", ".", "execute", "(", ")", "result", "=", "rebin_alg", ".", "getProperty", "(", "'OutputWorkspace'", ")", ".", "value", "if", "not", "result", ".", "isDistribution", "(", ")", ":", "convert_alg", "=", "self", ".", "createChildAlgorithm", "(", "'ConvertToDistribution'", ")", "convert_alg", ".", "setProperty", "(", "'Workspace'", ",", "result", ")", "convert_alg", ".", "execute", "(", ")", "return", "result" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/EnggCalibrateFull.py#L149-L164
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/bsplines.py
python
gauss_spline
(x, n)
return 1 / sqrt(2 * pi * signsq) * exp(-x ** 2 / 2 / signsq)
Gaussian approximation to B-spline basis function of order n. Parameters ---------- n : int The order of the spline. Must be nonnegative, i.e. n >= 0 References ---------- .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In: Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer Science, vol 4485. Springer, Berlin, Heidelberg
Gaussian approximation to B-spline basis function of order n.
[ "Gaussian", "approximation", "to", "B", "-", "spline", "basis", "function", "of", "order", "n", "." ]
def gauss_spline(x, n): """Gaussian approximation to B-spline basis function of order n. Parameters ---------- n : int The order of the spline. Must be nonnegative, i.e. n >= 0 References ---------- .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In: Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer Science, vol 4485. Springer, Berlin, Heidelberg """ signsq = (n + 1) / 12.0 return 1 / sqrt(2 * pi * signsq) * exp(-x ** 2 / 2 / signsq)
[ "def", "gauss_spline", "(", "x", ",", "n", ")", ":", "signsq", "=", "(", "n", "+", "1", ")", "/", "12.0", "return", "1", "/", "sqrt", "(", "2", "*", "pi", "*", "signsq", ")", "*", "exp", "(", "-", "x", "**", "2", "/", "2", "/", "signsq", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/bsplines.py#L132-L149
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
clang/bindings/python/clang/cindex.py
python
SourceLocation.file
(self)
return self._get_instantiation()[0]
Get the file represented by this source location.
Get the file represented by this source location.
[ "Get", "the", "file", "represented", "by", "this", "source", "location", "." ]
def file(self): """Get the file represented by this source location.""" return self._get_instantiation()[0]
[ "def", "file", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "0", "]" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang/bindings/python/clang/cindex.py#L270-L272
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/slim/python/slim/evaluation.py
python
evaluation_loop
(master, checkpoint_dir, logdir, num_evals=1, initial_op=None, initial_op_feed_dict=None, init_fn=None, eval_op=None, eval_op_feed_dict=None, final_op=None, final_op_feed_dict=None, summary_op=_USE_DEFAULT, summary_op_feed_dict=None, variables_to_restore=None, eval_interval_secs=60, max_number_of_evaluations=None, session_config=None, timeout=None, hooks=None)
return evaluation.evaluate_repeatedly( checkpoint_dir, master=master, scaffold=monitored_session.Scaffold( init_op=initial_op, init_feed_dict=initial_op_feed_dict, init_fn=init_fn, saver=saver), eval_ops=eval_op, feed_dict=eval_op_feed_dict, final_ops=final_op, final_ops_feed_dict=final_op_feed_dict, eval_interval_secs=eval_interval_secs, hooks=all_hooks, config=session_config, max_number_of_evaluations=max_number_of_evaluations, timeout=timeout)
Runs TF-Slim's Evaluation Loop. Args: master: The BNS address of the TensorFlow master. checkpoint_dir: The directory where checkpoints are stored. logdir: The directory where the TensorFlow summaries are written to. num_evals: The number of times to run `eval_op`. initial_op: An operation run at the beginning of evaluation. initial_op_feed_dict: A feed dictionary to use when executing `initial_op`. init_fn: An optional callable to be executed after `init_op` is called. The callable must accept one argument, the session being initialized. eval_op: A operation run `num_evals` times. eval_op_feed_dict: The feed dictionary to use when executing the `eval_op`. final_op: An operation to execute after all of the `eval_op` executions. The value of `final_op` is returned. final_op_feed_dict: A feed dictionary to use when executing `final_op`. summary_op: The summary_op to evaluate after running TF-Slims metric ops. By default the summary_op is set to tf.summary.merge_all(). summary_op_feed_dict: An optional feed dictionary to use when running the `summary_op`. variables_to_restore: A list of TensorFlow variables to restore during evaluation. If the argument is left as `None` then slim.variables.GetVariablesToRestore() is used. eval_interval_secs: The minimum number of seconds between evaluations. max_number_of_evaluations: the max number of iterations of the evaluation. If the value is left as 'None', the evaluation continues indefinitely. session_config: An instance of `tf.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. timeout: The maximum amount of time to wait between checkpoints. If left as `None`, then the process will wait indefinitely. hooks: A list of additional SessionRunHook objects to pass during repeated evaluations. Returns: The value of `final_op` or `None` if `final_op` is `None`.
Runs TF-Slim's Evaluation Loop.
[ "Runs", "TF", "-", "Slim", "s", "Evaluation", "Loop", "." ]
def evaluation_loop(master, checkpoint_dir, logdir, num_evals=1, initial_op=None, initial_op_feed_dict=None, init_fn=None, eval_op=None, eval_op_feed_dict=None, final_op=None, final_op_feed_dict=None, summary_op=_USE_DEFAULT, summary_op_feed_dict=None, variables_to_restore=None, eval_interval_secs=60, max_number_of_evaluations=None, session_config=None, timeout=None, hooks=None): """Runs TF-Slim's Evaluation Loop. Args: master: The BNS address of the TensorFlow master. checkpoint_dir: The directory where checkpoints are stored. logdir: The directory where the TensorFlow summaries are written to. num_evals: The number of times to run `eval_op`. initial_op: An operation run at the beginning of evaluation. initial_op_feed_dict: A feed dictionary to use when executing `initial_op`. init_fn: An optional callable to be executed after `init_op` is called. The callable must accept one argument, the session being initialized. eval_op: A operation run `num_evals` times. eval_op_feed_dict: The feed dictionary to use when executing the `eval_op`. final_op: An operation to execute after all of the `eval_op` executions. The value of `final_op` is returned. final_op_feed_dict: A feed dictionary to use when executing `final_op`. summary_op: The summary_op to evaluate after running TF-Slims metric ops. By default the summary_op is set to tf.summary.merge_all(). summary_op_feed_dict: An optional feed dictionary to use when running the `summary_op`. variables_to_restore: A list of TensorFlow variables to restore during evaluation. If the argument is left as `None` then slim.variables.GetVariablesToRestore() is used. eval_interval_secs: The minimum number of seconds between evaluations. max_number_of_evaluations: the max number of iterations of the evaluation. If the value is left as 'None', the evaluation continues indefinitely. session_config: An instance of `tf.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. timeout: The maximum amount of time to wait between checkpoints. If left as `None`, then the process will wait indefinitely. hooks: A list of additional SessionRunHook objects to pass during repeated evaluations. Returns: The value of `final_op` or `None` if `final_op` is `None`. """ if summary_op == _USE_DEFAULT: summary_op = summary.merge_all() all_hooks = [evaluation.StopAfterNEvalsHook(num_evals),] if summary_op is not None: all_hooks.append(evaluation.SummaryAtEndHook( log_dir=logdir, summary_op=summary_op, feed_dict=summary_op_feed_dict)) if hooks is not None: # Add custom hooks if provided. all_hooks.extend(hooks) saver = None if variables_to_restore is not None: saver = tf_saver.Saver(variables_to_restore) return evaluation.evaluate_repeatedly( checkpoint_dir, master=master, scaffold=monitored_session.Scaffold( init_op=initial_op, init_feed_dict=initial_op_feed_dict, init_fn=init_fn, saver=saver), eval_ops=eval_op, feed_dict=eval_op_feed_dict, final_ops=final_op, final_ops_feed_dict=final_op_feed_dict, eval_interval_secs=eval_interval_secs, hooks=all_hooks, config=session_config, max_number_of_evaluations=max_number_of_evaluations, timeout=timeout)
[ "def", "evaluation_loop", "(", "master", ",", "checkpoint_dir", ",", "logdir", ",", "num_evals", "=", "1", ",", "initial_op", "=", "None", ",", "initial_op_feed_dict", "=", "None", ",", "init_fn", "=", "None", ",", "eval_op", "=", "None", ",", "eval_op_feed_dict", "=", "None", ",", "final_op", "=", "None", ",", "final_op_feed_dict", "=", "None", ",", "summary_op", "=", "_USE_DEFAULT", ",", "summary_op_feed_dict", "=", "None", ",", "variables_to_restore", "=", "None", ",", "eval_interval_secs", "=", "60", ",", "max_number_of_evaluations", "=", "None", ",", "session_config", "=", "None", ",", "timeout", "=", "None", ",", "hooks", "=", "None", ")", ":", "if", "summary_op", "==", "_USE_DEFAULT", ":", "summary_op", "=", "summary", ".", "merge_all", "(", ")", "all_hooks", "=", "[", "evaluation", ".", "StopAfterNEvalsHook", "(", "num_evals", ")", ",", "]", "if", "summary_op", "is", "not", "None", ":", "all_hooks", ".", "append", "(", "evaluation", ".", "SummaryAtEndHook", "(", "log_dir", "=", "logdir", ",", "summary_op", "=", "summary_op", ",", "feed_dict", "=", "summary_op_feed_dict", ")", ")", "if", "hooks", "is", "not", "None", ":", "# Add custom hooks if provided.", "all_hooks", ".", "extend", "(", "hooks", ")", "saver", "=", "None", "if", "variables_to_restore", "is", "not", "None", ":", "saver", "=", "tf_saver", ".", "Saver", "(", "variables_to_restore", ")", "return", "evaluation", ".", "evaluate_repeatedly", "(", "checkpoint_dir", ",", "master", "=", "master", ",", "scaffold", "=", "monitored_session", ".", "Scaffold", "(", "init_op", "=", "initial_op", ",", "init_feed_dict", "=", "initial_op_feed_dict", ",", "init_fn", "=", "init_fn", ",", "saver", "=", "saver", ")", ",", "eval_ops", "=", "eval_op", ",", "feed_dict", "=", "eval_op_feed_dict", ",", "final_ops", "=", "final_op", ",", "final_ops_feed_dict", "=", "final_op_feed_dict", ",", "eval_interval_secs", "=", "eval_interval_secs", ",", "hooks", "=", "all_hooks", ",", "config", "=", "session_config", ",", "max_number_of_evaluations", "=", "max_number_of_evaluations", ",", "timeout", "=", "timeout", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/slim/python/slim/evaluation.py#L210-L296
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/molecule.py
python
Molecule.__getattr__
(self, name)
Function to overload accessing attribute contents to allow retrival of geometry variable values as if member data.
Function to overload accessing attribute contents to allow retrival of geometry variable values as if member data.
[ "Function", "to", "overload", "accessing", "attribute", "contents", "to", "allow", "retrival", "of", "geometry", "variable", "values", "as", "if", "member", "data", "." ]
def __getattr__(self, name): """Function to overload accessing attribute contents to allow retrival of geometry variable values as if member data. """ if 'all_variables' in self.__dict__ and name.upper() in self.__dict__['all_variables']: return self.get_variable(name) else: raise AttributeError
[ "def", "__getattr__", "(", "self", ",", "name", ")", ":", "if", "'all_variables'", "in", "self", ".", "__dict__", "and", "name", ".", "upper", "(", ")", "in", "self", ".", "__dict__", "[", "'all_variables'", "]", ":", "return", "self", ".", "get_variable", "(", "name", ")", "else", ":", "raise", "AttributeError" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/molecule.py#L167-L175
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/importIFCHelper.py
python
getIfcPsetProperties
(ifcfile, pid)
return getIfcProperties(ifcfile, pid, getIfcPropertySets(ifcfile, pid), {})
directly build the property table from pid and ifcfile for FreeCAD
directly build the property table from pid and ifcfile for FreeCAD
[ "directly", "build", "the", "property", "table", "from", "pid", "and", "ifcfile", "for", "FreeCAD" ]
def getIfcPsetProperties(ifcfile, pid): """ directly build the property table from pid and ifcfile for FreeCAD""" return getIfcProperties(ifcfile, pid, getIfcPropertySets(ifcfile, pid), {})
[ "def", "getIfcPsetProperties", "(", "ifcfile", ",", "pid", ")", ":", "return", "getIfcProperties", "(", "ifcfile", ",", "pid", ",", "getIfcPropertySets", "(", "ifcfile", ",", "pid", ")", ",", "{", "}", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/importIFCHelper.py#L614-L617
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/examples/python/mach_o.py
python
TerminalColors.magenta
(self, fg=True)
return ''
Set the foreground or background color to magenta. The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.
Set the foreground or background color to magenta. The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.
[ "Set", "the", "foreground", "or", "background", "color", "to", "magenta", ".", "The", "foreground", "color", "will", "be", "set", "if", "fg", "tests", "True", ".", "The", "background", "color", "will", "be", "set", "if", "fg", "tests", "False", "." ]
def magenta(self, fg=True): '''Set the foreground or background color to magenta. The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.''' if self.enabled: if fg: return "\x1b[35m" else: return "\x1b[45m" return ''
[ "def", "magenta", "(", "self", ",", "fg", "=", "True", ")", ":", "if", "self", ".", "enabled", ":", "if", "fg", ":", "return", "\"\\x1b[35m\"", "else", ":", "return", "\"\\x1b[45m\"", "return", "''" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/examples/python/mach_o.py#L321-L329
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ptyprocess/ptyprocess/ptyprocess.py
python
PtyProcessUnicode.read
(self, size=1024)
return self.decoder.decode(b, final=False)
Read at most ``size`` bytes from the pty, return them as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. The size argument still refers to bytes, not unicode code points.
Read at most ``size`` bytes from the pty, return them as unicode.
[ "Read", "at", "most", "size", "bytes", "from", "the", "pty", "return", "them", "as", "unicode", "." ]
def read(self, size=1024): """Read at most ``size`` bytes from the pty, return them as unicode. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. The size argument still refers to bytes, not unicode code points. """ b = super(PtyProcessUnicode, self).read(size) return self.decoder.decode(b, final=False)
[ "def", "read", "(", "self", ",", "size", "=", "1024", ")", ":", "b", "=", "super", "(", "PtyProcessUnicode", ",", "self", ")", ".", "read", "(", "size", ")", "return", "self", ".", "decoder", ".", "decode", "(", "b", ",", "final", "=", "False", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ptyprocess/ptyprocess/ptyprocess.py#L816-L825
facebook/fboss
60063db1df37c2ec0e7dcd0955c54885ea9bf7f0
fboss/py/fboss/cli/cli.py
python
PortState._show
(cli_opts, ports, all)
Show port state for given [port(s)]
Show port state for given [port(s)]
[ "Show", "port", "state", "for", "given", "[", "port", "(", "s", ")", "]" ]
def _show(cli_opts, ports, all): # noqa: B902 """Show port state for given [port(s)]""" port.PortStatusCmd(cli_opts).run( detail=False, ports=ports, verbose=False, internal=True, all=all )
[ "def", "_show", "(", "cli_opts", ",", "ports", ",", "all", ")", ":", "# noqa: B902", "port", ".", "PortStatusCmd", "(", "cli_opts", ")", ".", "run", "(", "detail", "=", "False", ",", "ports", "=", "ports", ",", "verbose", "=", "False", ",", "internal", "=", "True", ",", "all", "=", "all", ")" ]
https://github.com/facebook/fboss/blob/60063db1df37c2ec0e7dcd0955c54885ea9bf7f0/fboss/py/fboss/cli/cli.py#L323-L327
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/inputtransformer.py
python
has_comment
(src)
return (tokenize2.COMMENT in _line_tokens(src))
Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- comment : bool True if source has a comment.
Indicate whether an input line has (i.e. ends in, or is) a comment.
[ "Indicate", "whether", "an", "input", "line", "has", "(", "i", ".", "e", ".", "ends", "in", "or", "is", ")", "a", "comment", "." ]
def has_comment(src): """Indicate whether an input line has (i.e. ends in, or is) a comment. This uses tokenize, so it can distinguish comments from # inside strings. Parameters ---------- src : string A single line input string. Returns ------- comment : bool True if source has a comment. """ return (tokenize2.COMMENT in _line_tokens(src))
[ "def", "has_comment", "(", "src", ")", ":", "return", "(", "tokenize2", ".", "COMMENT", "in", "_line_tokens", "(", "src", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/inputtransformer.py#L306-L321
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/texture_cube.py
python
TextureCube.filter
(self)
return self.mglo.filter
tuple: The minification and magnification filter for the texture. (Default ``(moderngl.LINEAR. moderngl.LINEAR)``) Example:: texture.filter == (moderngl.NEAREST, moderngl.NEAREST) texture.filter == (moderngl.LINEAR_MIPMAP_LINEAR, moderngl.LINEAR) texture.filter == (moderngl.NEAREST_MIPMAP_LINEAR, moderngl.NEAREST) texture.filter == (moderngl.LINEAR_MIPMAP_NEAREST, moderngl.NEAREST)
tuple: The minification and magnification filter for the texture. (Default ``(moderngl.LINEAR. moderngl.LINEAR)``)
[ "tuple", ":", "The", "minification", "and", "magnification", "filter", "for", "the", "texture", ".", "(", "Default", "(", "moderngl", ".", "LINEAR", ".", "moderngl", ".", "LINEAR", ")", ")" ]
def filter(self): ''' tuple: The minification and magnification filter for the texture. (Default ``(moderngl.LINEAR. moderngl.LINEAR)``) Example:: texture.filter == (moderngl.NEAREST, moderngl.NEAREST) texture.filter == (moderngl.LINEAR_MIPMAP_LINEAR, moderngl.LINEAR) texture.filter == (moderngl.NEAREST_MIPMAP_LINEAR, moderngl.NEAREST) texture.filter == (moderngl.LINEAR_MIPMAP_NEAREST, moderngl.NEAREST) ''' return self.mglo.filter
[ "def", "filter", "(", "self", ")", ":", "return", "self", ".", "mglo", ".", "filter" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/texture_cube.py#L77-L89
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/cmathimpl.py
python
log_impl
(x, y, x_is_finite, y_is_finite)
return complex(a, b)
cmath.log(x + y j)
cmath.log(x + y j)
[ "cmath", ".", "log", "(", "x", "+", "y", "j", ")" ]
def log_impl(x, y, x_is_finite, y_is_finite): """cmath.log(x + y j)""" a = math.log(math.hypot(x, y)) b = math.atan2(y, x) return complex(a, b)
[ "def", "log_impl", "(", "x", ",", "y", ",", "x_is_finite", ",", "y_is_finite", ")", ":", "a", "=", "math", ".", "log", "(", "math", ".", "hypot", "(", "x", ",", "y", ")", ")", "b", "=", "math", ".", "atan2", "(", "y", ",", "x", ")", "return", "complex", "(", "a", ",", "b", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/cmathimpl.py#L160-L164
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/handlers.py
python
set_operation_specific_signer
(context, signing_name, **kwargs)
Choose the operation-specific signer. Individual operations may have a different auth type than the service as a whole. This will most often manifest as operations that should not be authenticated at all, but can include other auth modes such as sigv4 without body signing.
Choose the operation-specific signer.
[ "Choose", "the", "operation", "-", "specific", "signer", "." ]
def set_operation_specific_signer(context, signing_name, **kwargs): """ Choose the operation-specific signer. Individual operations may have a different auth type than the service as a whole. This will most often manifest as operations that should not be authenticated at all, but can include other auth modes such as sigv4 without body signing. """ auth_type = context.get('auth_type') # Auth type will be None if the operation doesn't have a configured auth # type. if not auth_type: return # Auth type will be the string value 'none' if the operation should not # be signed at all. if auth_type == 'none': return botocore.UNSIGNED if auth_type.startswith('v4'): signature_version = 'v4' if signing_name == 's3': signature_version = 's3v4' # If the operation needs an unsigned body, we set additional context # allowing the signer to be aware of this. if auth_type == 'v4-unsigned-body': context['payload_signing_enabled'] = False return signature_version
[ "def", "set_operation_specific_signer", "(", "context", ",", "signing_name", ",", "*", "*", "kwargs", ")", ":", "auth_type", "=", "context", ".", "get", "(", "'auth_type'", ")", "# Auth type will be None if the operation doesn't have a configured auth", "# type.", "if", "not", "auth_type", ":", "return", "# Auth type will be the string value 'none' if the operation should not", "# be signed at all.", "if", "auth_type", "==", "'none'", ":", "return", "botocore", ".", "UNSIGNED", "if", "auth_type", ".", "startswith", "(", "'v4'", ")", ":", "signature_version", "=", "'v4'", "if", "signing_name", "==", "'s3'", ":", "signature_version", "=", "'s3v4'", "# If the operation needs an unsigned body, we set additional context", "# allowing the signer to be aware of this.", "if", "auth_type", "==", "'v4-unsigned-body'", ":", "context", "[", "'payload_signing_enabled'", "]", "=", "False", "return", "signature_version" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/handlers.py#L115-L145
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/jinja2/bccache.py
python
BytecodeCache.clear
(self)
Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment.
Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment.
[ "Clears", "the", "cache", ".", "This", "method", "is", "not", "used", "by", "Jinja2", "but", "should", "be", "implemented", "to", "allow", "applications", "to", "clear", "the", "bytecode", "cache", "used", "by", "a", "particular", "environment", "." ]
def clear(self): """Clears the cache. This method is not used by Jinja2 but should be implemented to allow applications to clear the bytecode cache used by a particular environment. """
[ "def", "clear", "(", "self", ")", ":" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/bccache.py#L160-L164
pgRouting/osm2pgrouting
8491929fc4037d308f271e84d59bb96da3c28aa2
tools/cpplint.py
python
FindStartOfExpressionInLine
(line, endpos, stack)
return (-1, stack)
Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line)
Find position at the matching start of current expression.
[ "Find", "position", "at", "the", "matching", "start", "of", "current", "expression", "." ]
def FindStartOfExpressionInLine(line, endpos, stack): """Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line) """ i = endpos while i >= 0: char = line[i] if char in ')]}': # Found end of expression, push to expression stack stack.append(char) elif char == '>': # Found potential end of template argument list. # # Ignore it if it's a "->" or ">=" or "operator>" if (i > 0 and (line[i - 1] == '-' or Match(r'\s>=\s', line[i - 1:]) or Search(r'\boperator\s*$', line[0:i]))): i -= 1 else: stack.append('>') elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator i -= 1 else: # If there is a matching '>', we can pop the expression stack. # Otherwise, ignore this '<' since it must be an operator. if stack and stack[-1] == '>': stack.pop() if not stack: return (i, None) elif char in '([{': # Found start of expression. # # If there are any unmatched '>' on the stack, they must be # operators. Remove those. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) if ((char == '(' and stack[-1] == ')') or (char == '[' and stack[-1] == ']') or (char == '{' and stack[-1] == '}')): stack.pop() if not stack: return (i, None) else: # Mismatched parentheses return (-1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '<', the matching '>' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) i -= 1 return (-1, stack)
[ "def", "FindStartOfExpressionInLine", "(", "line", ",", "endpos", ",", "stack", ")", ":", "i", "=", "endpos", "while", "i", ">=", "0", ":", "char", "=", "line", "[", "i", "]", "if", "char", "in", "')]}'", ":", "# Found end of expression, push to expression stack", "stack", ".", "append", "(", "char", ")", "elif", "char", "==", "'>'", ":", "# Found potential end of template argument list.", "#", "# Ignore it if it's a \"->\" or \">=\" or \"operator>\"", "if", "(", "i", ">", "0", "and", "(", "line", "[", "i", "-", "1", "]", "==", "'-'", "or", "Match", "(", "r'\\s>=\\s'", ",", "line", "[", "i", "-", "1", ":", "]", ")", "or", "Search", "(", "r'\\boperator\\s*$'", ",", "line", "[", "0", ":", "i", "]", ")", ")", ")", ":", "i", "-=", "1", "else", ":", "stack", ".", "append", "(", "'>'", ")", "elif", "char", "==", "'<'", ":", "# Found potential start of template argument list", "if", "i", ">", "0", "and", "line", "[", "i", "-", "1", "]", "==", "'<'", ":", "# Left shift operator", "i", "-=", "1", "else", ":", "# If there is a matching '>', we can pop the expression stack.", "# Otherwise, ignore this '<' since it must be an operator.", "if", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", ",", "None", ")", "elif", "char", "in", "'([{'", ":", "# Found start of expression.", "#", "# If there are any unmatched '>' on the stack, they must be", "# operators. Remove those.", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "if", "(", "(", "char", "==", "'('", "and", "stack", "[", "-", "1", "]", "==", "')'", ")", "or", "(", "char", "==", "'['", "and", "stack", "[", "-", "1", "]", "==", "']'", ")", "or", "(", "char", "==", "'{'", "and", "stack", "[", "-", "1", "]", "==", "'}'", ")", ")", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "i", ",", "None", ")", "else", ":", "# Mismatched parentheses", "return", "(", "-", "1", ",", "None", ")", "elif", "char", "==", "';'", ":", "# Found something that look like end of statements. If we are currently", "# expecting a '<', the matching '>' must have been an operator, since", "# template argument list should not contain statements.", "while", "stack", "and", "stack", "[", "-", "1", "]", "==", "'>'", ":", "stack", ".", "pop", "(", ")", "if", "not", "stack", ":", "return", "(", "-", "1", ",", "None", ")", "i", "-=", "1", "return", "(", "-", "1", ",", "stack", ")" ]
https://github.com/pgRouting/osm2pgrouting/blob/8491929fc4037d308f271e84d59bb96da3c28aa2/tools/cpplint.py#L1505-L1579
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py
python
TensorArray.__init__
(self, dtype, size=None, dynamic_size=None, clear_after_read=None, tensor_array_name=None, handle=None, flow=None, infer_shape=True, name=None)
Construct a new TensorArray or wrap an existing TensorArray handle. A note about the parameter `name`: The name of the `TensorArray` (even if passed in) is uniquified: each time a new `TensorArray` is created at runtime it is assigned its own name for the duration of the run. This avoids name collissions if a `TensorArray` is created within a `while_loop`. Args: dtype: (required) data type of the TensorArray. size: (optional) int32 scalar `Tensor`: the size of the TensorArray. Required if handle is not provided. dynamic_size: (optional) Python bool: If true, writes to the TensorArray can grow the TensorArray past its initial size. Default: False. clear_after_read: Boolean (optional, default: True). If True, clear TensorArray values after reading them. This disables read-many semantics, but allows early release of memory. tensor_array_name: (optional) Python string: the name of the TensorArray. This is used when creating the TensorArray handle. If this value is set, handle should be None. handle: (optional) A `Tensor` handle to an existing TensorArray. If this is set, tensor_array_name should be None. flow: (optional) A float `Tensor` scalar coming from an existing `TensorArray.flow`. infer_shape: (optional, default: True) If True, shape inference is enabled. In this case, all elements must have the same shape. name: A name for the operation (optional). Raises: ValueError: if both handle and tensor_array_name are provided. TypeError: if handle is provided but is not a Tensor.
Construct a new TensorArray or wrap an existing TensorArray handle.
[ "Construct", "a", "new", "TensorArray", "or", "wrap", "an", "existing", "TensorArray", "handle", "." ]
def __init__(self, dtype, size=None, dynamic_size=None, clear_after_read=None, tensor_array_name=None, handle=None, flow=None, infer_shape=True, name=None): """Construct a new TensorArray or wrap an existing TensorArray handle. A note about the parameter `name`: The name of the `TensorArray` (even if passed in) is uniquified: each time a new `TensorArray` is created at runtime it is assigned its own name for the duration of the run. This avoids name collissions if a `TensorArray` is created within a `while_loop`. Args: dtype: (required) data type of the TensorArray. size: (optional) int32 scalar `Tensor`: the size of the TensorArray. Required if handle is not provided. dynamic_size: (optional) Python bool: If true, writes to the TensorArray can grow the TensorArray past its initial size. Default: False. clear_after_read: Boolean (optional, default: True). If True, clear TensorArray values after reading them. This disables read-many semantics, but allows early release of memory. tensor_array_name: (optional) Python string: the name of the TensorArray. This is used when creating the TensorArray handle. If this value is set, handle should be None. handle: (optional) A `Tensor` handle to an existing TensorArray. If this is set, tensor_array_name should be None. flow: (optional) A float `Tensor` scalar coming from an existing `TensorArray.flow`. infer_shape: (optional, default: True) If True, shape inference is enabled. In this case, all elements must have the same shape. name: A name for the operation (optional). Raises: ValueError: if both handle and tensor_array_name are provided. TypeError: if handle is provided but is not a Tensor. """ if handle is not None and tensor_array_name: raise ValueError( "Cannot construct with both handle and tensor_array_name") if handle is not None and not isinstance(handle, ops.Tensor): raise TypeError("Handle must be a Tensor") if handle is None and size is None: raise ValueError("Size must be provided if handle is not provided") if handle is not None and size is not None: raise ValueError("Cannot provide both a handle and size " "at the same time") if handle is not None and dynamic_size is not None: raise ValueError("Cannot provide both a handle and dynamic_size " "at the same time") if handle is not None and clear_after_read is not None: raise ValueError("Cannot provide both a handle and clear_after_read " "at the same time") if clear_after_read is None: clear_after_read = True dynamic_size = dynamic_size or False self._dtype = dtype self._infer_shape = infer_shape # Record the current static shape for the array elements. The first # write adds the shape of the tensor it writes, and all subsequent # writes checks for shape equality. self._elem_shape = [] with ops.op_scope([handle, size, flow], name, "TensorArray") as scope: if handle is not None: self._handle = handle else: if flow is not None: with ops.colocate_with(flow): self._handle = gen_data_flow_ops._tensor_array( dtype=dtype, size=size, dynamic_size=dynamic_size, clear_after_read=clear_after_read, tensor_array_name=tensor_array_name, name=scope) else: self._handle = gen_data_flow_ops._tensor_array( dtype=dtype, size=size, dynamic_size=dynamic_size, clear_after_read=clear_after_read, tensor_array_name=tensor_array_name, name=scope) if flow is not None: self._flow = flow else: with ops.colocate_with(self._handle): self._flow = constant_op.constant(0, dtype=_dtypes.float32)
[ "def", "__init__", "(", "self", ",", "dtype", ",", "size", "=", "None", ",", "dynamic_size", "=", "None", ",", "clear_after_read", "=", "None", ",", "tensor_array_name", "=", "None", ",", "handle", "=", "None", ",", "flow", "=", "None", ",", "infer_shape", "=", "True", ",", "name", "=", "None", ")", ":", "if", "handle", "is", "not", "None", "and", "tensor_array_name", ":", "raise", "ValueError", "(", "\"Cannot construct with both handle and tensor_array_name\"", ")", "if", "handle", "is", "not", "None", "and", "not", "isinstance", "(", "handle", ",", "ops", ".", "Tensor", ")", ":", "raise", "TypeError", "(", "\"Handle must be a Tensor\"", ")", "if", "handle", "is", "None", "and", "size", "is", "None", ":", "raise", "ValueError", "(", "\"Size must be provided if handle is not provided\"", ")", "if", "handle", "is", "not", "None", "and", "size", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Cannot provide both a handle and size \"", "\"at the same time\"", ")", "if", "handle", "is", "not", "None", "and", "dynamic_size", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Cannot provide both a handle and dynamic_size \"", "\"at the same time\"", ")", "if", "handle", "is", "not", "None", "and", "clear_after_read", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Cannot provide both a handle and clear_after_read \"", "\"at the same time\"", ")", "if", "clear_after_read", "is", "None", ":", "clear_after_read", "=", "True", "dynamic_size", "=", "dynamic_size", "or", "False", "self", ".", "_dtype", "=", "dtype", "self", ".", "_infer_shape", "=", "infer_shape", "# Record the current static shape for the array elements. The first", "# write adds the shape of the tensor it writes, and all subsequent", "# writes checks for shape equality.", "self", ".", "_elem_shape", "=", "[", "]", "with", "ops", ".", "op_scope", "(", "[", "handle", ",", "size", ",", "flow", "]", ",", "name", ",", "\"TensorArray\"", ")", "as", "scope", ":", "if", "handle", "is", "not", "None", ":", "self", ".", "_handle", "=", "handle", "else", ":", "if", "flow", "is", "not", "None", ":", "with", "ops", ".", "colocate_with", "(", "flow", ")", ":", "self", ".", "_handle", "=", "gen_data_flow_ops", ".", "_tensor_array", "(", "dtype", "=", "dtype", ",", "size", "=", "size", ",", "dynamic_size", "=", "dynamic_size", ",", "clear_after_read", "=", "clear_after_read", ",", "tensor_array_name", "=", "tensor_array_name", ",", "name", "=", "scope", ")", "else", ":", "self", ".", "_handle", "=", "gen_data_flow_ops", ".", "_tensor_array", "(", "dtype", "=", "dtype", ",", "size", "=", "size", ",", "dynamic_size", "=", "dynamic_size", ",", "clear_after_read", "=", "clear_after_read", ",", "tensor_array_name", "=", "tensor_array_name", ",", "name", "=", "scope", ")", "if", "flow", "is", "not", "None", ":", "self", ".", "_flow", "=", "flow", "else", ":", "with", "ops", ".", "colocate_with", "(", "self", ".", "_handle", ")", ":", "self", ".", "_flow", "=", "constant_op", ".", "constant", "(", "0", ",", "dtype", "=", "_dtypes", ".", "float32", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py#L62-L144
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibar.py
python
AuiToolBar.FindControl
(self, id)
return wnd
Returns a pointer to the control identified by `id` or ``None`` if no corresponding control is found. :param integer `id`: the control identifier.
Returns a pointer to the control identified by `id` or ``None`` if no corresponding control is found.
[ "Returns", "a", "pointer", "to", "the", "control", "identified", "by", "id", "or", "None", "if", "no", "corresponding", "control", "is", "found", "." ]
def FindControl(self, id): """ Returns a pointer to the control identified by `id` or ``None`` if no corresponding control is found. :param integer `id`: the control identifier. """ wnd = self.FindWindow(id) return wnd
[ "def", "FindControl", "(", "self", ",", "id", ")", ":", "wnd", "=", "self", ".", "FindWindow", "(", "id", ")", "return", "wnd" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L2067-L2075
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ChimeraApplication/python_scripts/rotate_region_process.py
python
ApplyRotateRegionProcess.ExecuteFinalizeSolutionStep
(self)
This method is executed in order to finalize the current step Keyword arguments: self -- It signifies an instance of a class.
This method is executed in order to finalize the current step
[ "This", "method", "is", "executed", "in", "order", "to", "finalize", "the", "current", "step" ]
def ExecuteFinalizeSolutionStep(self): """ This method is executed in order to finalize the current step Keyword arguments: self -- It signifies an instance of a class. """ current_time = self.model_part.ProcessInfo[KratosMultiphysics.TIME] if self.interval.IsInInterval(current_time): self.rotate_region_process.ExecuteFinalizeSolutionStep()
[ "def", "ExecuteFinalizeSolutionStep", "(", "self", ")", ":", "current_time", "=", "self", ".", "model_part", ".", "ProcessInfo", "[", "KratosMultiphysics", ".", "TIME", "]", "if", "self", ".", "interval", ".", "IsInInterval", "(", "current_time", ")", ":", "self", ".", "rotate_region_process", ".", "ExecuteFinalizeSolutionStep", "(", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ChimeraApplication/python_scripts/rotate_region_process.py#L85-L94
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/classifier.py
python
Classifier.predict_proba
( self, x=None, input_fn=None, batch_size=None, as_iterable=False)
Returns predicted probabilty distributions for given features. Args: x: Matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. If set, `input_fn` must be `None`. input_fn: Input function. If set, `x` and 'batch_size' must be `None`. batch_size: Override default batch size. If set, 'input_fn' must be 'None'. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: A numpy array of predicted probability distributions (or an iterable of predicted probability distributions if as_iterable is True). Raises: ValueError: If x and input_fn are both provided or both `None`.
Returns predicted probabilty distributions for given features.
[ "Returns", "predicted", "probabilty", "distributions", "for", "given", "features", "." ]
def predict_proba( self, x=None, input_fn=None, batch_size=None, as_iterable=False): """Returns predicted probabilty distributions for given features. Args: x: Matrix of shape [n_samples, n_features...]. Can be iterator that returns arrays of features. The training input samples for fitting the model. If set, `input_fn` must be `None`. input_fn: Input function. If set, `x` and 'batch_size' must be `None`. batch_size: Override default batch size. If set, 'input_fn' must be 'None'. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: A numpy array of predicted probability distributions (or an iterable of predicted probability distributions if as_iterable is True). Raises: ValueError: If x and input_fn are both provided or both `None`. """ predictions = super(Classifier, self).predict( x=x, input_fn=input_fn, batch_size=batch_size, as_iterable=as_iterable, outputs=[self.PROBABILITY_OUTPUT]) if as_iterable: return (p[self.PROBABILITY_OUTPUT] for p in predictions) else: return predictions[self.PROBABILITY_OUTPUT]
[ "def", "predict_proba", "(", "self", ",", "x", "=", "None", ",", "input_fn", "=", "None", ",", "batch_size", "=", "None", ",", "as_iterable", "=", "False", ")", ":", "predictions", "=", "super", "(", "Classifier", ",", "self", ")", ".", "predict", "(", "x", "=", "x", ",", "input_fn", "=", "input_fn", ",", "batch_size", "=", "batch_size", ",", "as_iterable", "=", "as_iterable", ",", "outputs", "=", "[", "self", ".", "PROBABILITY_OUTPUT", "]", ")", "if", "as_iterable", ":", "return", "(", "p", "[", "self", ".", "PROBABILITY_OUTPUT", "]", "for", "p", "in", "predictions", ")", "else", ":", "return", "predictions", "[", "self", ".", "PROBABILITY_OUTPUT", "]" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/classifier.py#L97-L126
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/devtools_client_backend.py
python
DevToolsClientBackend.CloseTab
(self, tab_id, timeout)
Closes the tab with the given id. Raises: devtools_http.DevToolsClientConnectionError TabNotFoundError
Closes the tab with the given id.
[ "Closes", "the", "tab", "with", "the", "given", "id", "." ]
def CloseTab(self, tab_id, timeout): """Closes the tab with the given id. Raises: devtools_http.DevToolsClientConnectionError TabNotFoundError """ try: return self._devtools_http.Request('close/%s' % tab_id, timeout=timeout) except devtools_http.DevToolsClientUrlError: error = TabNotFoundError( 'Unable to close tab, tab id not found: %s' % tab_id) raise error, None, sys.exc_info()[2]
[ "def", "CloseTab", "(", "self", ",", "tab_id", ",", "timeout", ")", ":", "try", ":", "return", "self", ".", "_devtools_http", ".", "Request", "(", "'close/%s'", "%", "tab_id", ",", "timeout", "=", "timeout", ")", "except", "devtools_http", ".", "DevToolsClientUrlError", ":", "error", "=", "TabNotFoundError", "(", "'Unable to close tab, tab id not found: %s'", "%", "tab_id", ")", "raise", "error", ",", "None", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/devtools_client_backend.py#L246-L259
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py
python
CP_fileobject.sendall
(self, data)
Sendall for non-blocking sockets.
Sendall for non-blocking sockets.
[ "Sendall", "for", "non", "-", "blocking", "sockets", "." ]
def sendall(self, data): """Sendall for non-blocking sockets.""" while data: try: bytes_sent = self.send(data) data = data[bytes_sent:] except socket.error, e: if e.args[0] not in socket_errors_nonblocking: raise
[ "def", "sendall", "(", "self", ",", "data", ")", ":", "while", "data", ":", "try", ":", "bytes_sent", "=", "self", ".", "send", "(", "data", ")", "data", "=", "data", "[", "bytes_sent", ":", "]", "except", "socket", ".", "error", ",", "e", ":", "if", "e", ".", "args", "[", "0", "]", "not", "in", "socket_errors_nonblocking", ":", "raise" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/wsgiserver/wsgiserver2.py#L966-L974
acado/acado
b4e28f3131f79cadfd1a001e9fff061f361d3a0f
misc/cpplint.py
python
CheckAccess
(filename, clean_lines, linenum, nesting_state, error)
Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks for improper use of DISALLOW* macros.
[ "Checks", "for", "improper", "use", "of", "DISALLOW", "*", "macros", "." ]
def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_EVIL_CONSTRUCTORS|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass
[ "def", "CheckAccess", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "matched", "=", "Match", "(", "(", "r'\\s*(DISALLOW_COPY_AND_ASSIGN|'", "r'DISALLOW_EVIL_CONSTRUCTORS|'", "r'DISALLOW_IMPLICIT_CONSTRUCTORS)'", ")", ",", "line", ")", "if", "not", "matched", ":", "return", "if", "nesting_state", ".", "stack", "and", "isinstance", "(", "nesting_state", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", ":", "if", "nesting_state", ".", "stack", "[", "-", "1", "]", ".", "access", "!=", "'private'", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/constructors'", ",", "3", ",", "'%s must be in the private: section'", "%", "matched", ".", "group", "(", "1", ")", ")", "else", ":", "# Found DISALLOW* macro outside a class declaration, or perhaps it", "# was used inside a function when it should have been part of the", "# class declaration. We could issue a warning here, but it", "# probably resulted in a compiler error already.", "pass" ]
https://github.com/acado/acado/blob/b4e28f3131f79cadfd1a001e9fff061f361d3a0f/misc/cpplint.py#L2378-L2406
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/nndct_graph/base_graph.py
python
GraphBase.nodes
(self)
Yield node in graph according to topo order Returns: generator: yiled a node when tranverse graph
Yield node in graph according to topo order
[ "Yield", "node", "in", "graph", "according", "to", "topo", "order" ]
def nodes(self): """Yield node in graph according to topo order Returns: generator: yiled a node when tranverse graph """
[ "def", "nodes", "(", "self", ")", ":" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_pytorch/nndct_shared/nndct_graph/base_graph.py#L43-L48
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
win32/Demos/win32netdemo.py
python
GroupEnum
()
Enumerates all the domain groups
Enumerates all the domain groups
[ "Enumerates", "all", "the", "domain", "groups" ]
def GroupEnum(): "Enumerates all the domain groups" nmembers = 0 resume = 0 while 1: data, total, resume = win32net.NetGroupEnum(server, 1, resume) # print "Call to NetGroupEnum obtained %d entries of %d total" % (len(data), total) for group in data: verbose("Found group %(name)s:%(comment)s " % group) memberresume = 0 while 1: memberdata, total, memberresume = win32net.NetGroupGetUsers( server, group["name"], 0, resume ) for member in memberdata: verbose(" Member %(name)s" % member) nmembers = nmembers + 1 if memberresume == 0: break if not resume: break assert nmembers, "Couldnt find a single member in a single group!" print("Enumerated all the groups")
[ "def", "GroupEnum", "(", ")", ":", "nmembers", "=", "0", "resume", "=", "0", "while", "1", ":", "data", ",", "total", ",", "resume", "=", "win32net", ".", "NetGroupEnum", "(", "server", ",", "1", ",", "resume", ")", "# print \"Call to NetGroupEnum obtained %d entries of %d total\" % (len(data), total)", "for", "group", "in", "data", ":", "verbose", "(", "\"Found group %(name)s:%(comment)s \"", "%", "group", ")", "memberresume", "=", "0", "while", "1", ":", "memberdata", ",", "total", ",", "memberresume", "=", "win32net", ".", "NetGroupGetUsers", "(", "server", ",", "group", "[", "\"name\"", "]", ",", "0", ",", "resume", ")", "for", "member", "in", "memberdata", ":", "verbose", "(", "\" Member %(name)s\"", "%", "member", ")", "nmembers", "=", "nmembers", "+", "1", "if", "memberresume", "==", "0", ":", "break", "if", "not", "resume", ":", "break", "assert", "nmembers", ",", "\"Couldnt find a single member in a single group!\"", "print", "(", "\"Enumerated all the groups\"", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/Demos/win32netdemo.py#L67-L89
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/busco/BuscoConfig.py
python
BuscoConfig.nice_path
(path)
:param path: a path to check :type path: str :return: the same but cleaned path :rtype str:
:param path: a path to check :type path: str :return: the same but cleaned path :rtype str:
[ ":", "param", "path", ":", "a", "path", "to", "check", ":", "type", "path", ":", "str", ":", "return", ":", "the", "same", "but", "cleaned", "path", ":", "rtype", "str", ":" ]
def nice_path(path): """ :param path: a path to check :type path: str :return: the same but cleaned path :rtype str: """ try: if path[-1] != '/': path += '/' return path except TypeError: return None
[ "def", "nice_path", "(", "path", ")", ":", "try", ":", "if", "path", "[", "-", "1", "]", "!=", "'/'", ":", "path", "+=", "'/'", "return", "path", "except", "TypeError", ":", "return", "None" ]
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/busco/BuscoConfig.py#L230-L242
h2oai/deepwater
80e345c582e6ef912a31f42707a2f31c01b064da
tensorflow/src/main/resources/deepwater/train.py
python
ImageClassificationTrainStrategy.loss
(self)
return self._loss
Returns the tensor containing the loss value
Returns the tensor containing the loss value
[ "Returns", "the", "tensor", "containing", "the", "loss", "value" ]
def loss(self): """ Returns the tensor containing the loss value """ return self._loss
[ "def", "loss", "(", "self", ")", ":", "return", "self", ".", "_loss" ]
https://github.com/h2oai/deepwater/blob/80e345c582e6ef912a31f42707a2f31c01b064da/tensorflow/src/main/resources/deepwater/train.py#L121-L123
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/cpplint.py
python
ProcessFile
(filename, vlevel, extra_check_functions=[])
Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Does google-lint on a single file.
[ "Does", "google", "-", "lint", "on", "a", "single", "file", "." ]
def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) _BackupFilters() old_errors = _cpplint_state.error_count if not ProcessConfigOverrides(filename): _RestoreFilters() return lf_lines = [] crlf_lines = [] try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') # Remove trailing '\r'. # The -1 accounts for the extra trailing blank line we get from split() for linenum in range(len(lines) - 1): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') crlf_lines.append(linenum + 1) else: lf_lines.append(linenum + 1) except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) _RestoreFilters() return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) # If end-of-line sequences are a mix of LF and CR-LF, issue # warnings on the lines with CR. # # Don't issue any warnings if all lines are uniformly LF or CR-LF, # since critique can handle these just fine, and the style guide # doesn't dictate a particular end of line sequence. # # We can't depend on os.linesep to determine what the desired # end-of-line sequence should be, since that will return the # server-side end-of-line sequence. if lf_lines and crlf_lines: # Warn on every line with CR. An alternative approach might be to # check whether the file is mostly CRLF or just LF, and warn on the # minority, we bias toward LF here since most tools prefer LF. for linenum in crlf_lines: Error(filename, linenum, 'whitespace/newline', 1, 'Unexpected \\r (^M) found; better to use only \\n') # Suppress printing anything if --quiet was passed unless the error # count has increased after processing this file. if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count: sys.stdout.write('Done processing %s\n' % filename) _RestoreFilters()
[ "def", "ProcessFile", "(", "filename", ",", "vlevel", ",", "extra_check_functions", "=", "[", "]", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "_BackupFilters", "(", ")", "old_errors", "=", "_cpplint_state", ".", "error_count", "if", "not", "ProcessConfigOverrides", "(", "filename", ")", ":", "_RestoreFilters", "(", ")", "return", "lf_lines", "=", "[", "]", "crlf_lines", "=", "[", "]", "try", ":", "# Support the UNIX convention of using \"-\" for stdin. Note that", "# we are not opening the file with universal newline support", "# (which codecs doesn't support anyway), so the resulting lines do", "# contain trailing '\\r' characters if we are reading a file that", "# has CRLF endings.", "# If after the split a trailing '\\r' is present, it is removed", "# below.", "if", "filename", "==", "'-'", ":", "lines", "=", "codecs", ".", "StreamReaderWriter", "(", "sys", ".", "stdin", ",", "codecs", ".", "getreader", "(", "'utf8'", ")", ",", "codecs", ".", "getwriter", "(", "'utf8'", ")", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "else", ":", "lines", "=", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "# Remove trailing '\\r'.", "# The -1 accounts for the extra trailing blank line we get from split()", "for", "linenum", "in", "range", "(", "len", "(", "lines", ")", "-", "1", ")", ":", "if", "lines", "[", "linenum", "]", ".", "endswith", "(", "'\\r'", ")", ":", "lines", "[", "linenum", "]", "=", "lines", "[", "linenum", "]", ".", "rstrip", "(", "'\\r'", ")", "crlf_lines", ".", "append", "(", "linenum", "+", "1", ")", "else", ":", "lf_lines", ".", "append", "(", "linenum", "+", "1", ")", "except", "IOError", ":", "sys", ".", "stderr", ".", "write", "(", "\"Skipping input '%s': Can't open for reading\\n\"", "%", "filename", ")", "_RestoreFilters", "(", ")", "return", "# Note, if no dot is found, this will give the entire filename as the ext.", "file_extension", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "# When reading from stdin, the extension is unknown, so no cpplint tests", "# should rely on the extension.", "if", "filename", "!=", "'-'", "and", "file_extension", "not", "in", "_valid_extensions", ":", "sys", ".", "stderr", ".", "write", "(", "'Ignoring %s; not a valid file name '", "'(%s)\\n'", "%", "(", "filename", ",", "', '", ".", "join", "(", "_valid_extensions", ")", ")", ")", "else", ":", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "Error", ",", "extra_check_functions", ")", "# If end-of-line sequences are a mix of LF and CR-LF, issue", "# warnings on the lines with CR.", "#", "# Don't issue any warnings if all lines are uniformly LF or CR-LF,", "# since critique can handle these just fine, and the style guide", "# doesn't dictate a particular end of line sequence.", "#", "# We can't depend on os.linesep to determine what the desired", "# end-of-line sequence should be, since that will return the", "# server-side end-of-line sequence.", "if", "lf_lines", "and", "crlf_lines", ":", "# Warn on every line with CR. An alternative approach might be to", "# check whether the file is mostly CRLF or just LF, and warn on the", "# minority, we bias toward LF here since most tools prefer LF.", "for", "linenum", "in", "crlf_lines", ":", "Error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "1", ",", "'Unexpected \\\\r (^M) found; better to use only \\\\n'", ")", "# Suppress printing anything if --quiet was passed unless the error", "# count has increased after processing this file.", "if", "not", "_cpplint_state", ".", "quiet", "or", "old_errors", "!=", "_cpplint_state", ".", "error_count", ":", "sys", ".", "stdout", ".", "write", "(", "'Done processing %s\\n'", "%", "filename", ")", "_RestoreFilters", "(", ")" ]
https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L6031-L6120
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/timedeltas.py
python
TimedeltaArray.components
(self)
return result
Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas. Returns ------- a DataFrame
Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
[ "Return", "a", "dataframe", "of", "the", "components", "(", "days", "hours", "minutes", "seconds", "milliseconds", "microseconds", "nanoseconds", ")", "of", "the", "Timedeltas", "." ]
def components(self): """ Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas. Returns ------- a DataFrame """ from pandas import DataFrame columns = [ "days", "hours", "minutes", "seconds", "milliseconds", "microseconds", "nanoseconds", ] hasnans = self._hasnans if hasnans: def f(x): if isna(x): return [np.nan] * len(columns) return x.components else: def f(x): return x.components result = DataFrame([f(x) for x in self], columns=columns) if not hasnans: result = result.astype("int64") return result
[ "def", "components", "(", "self", ")", ":", "from", "pandas", "import", "DataFrame", "columns", "=", "[", "\"days\"", ",", "\"hours\"", ",", "\"minutes\"", ",", "\"seconds\"", ",", "\"milliseconds\"", ",", "\"microseconds\"", ",", "\"nanoseconds\"", ",", "]", "hasnans", "=", "self", ".", "_hasnans", "if", "hasnans", ":", "def", "f", "(", "x", ")", ":", "if", "isna", "(", "x", ")", ":", "return", "[", "np", ".", "nan", "]", "*", "len", "(", "columns", ")", "return", "x", ".", "components", "else", ":", "def", "f", "(", "x", ")", ":", "return", "x", ".", "components", "result", "=", "DataFrame", "(", "[", "f", "(", "x", ")", "for", "x", "in", "self", "]", ",", "columns", "=", "columns", ")", "if", "not", "hasnans", ":", "result", "=", "result", ".", "astype", "(", "\"int64\"", ")", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/timedeltas.py#L852-L888
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/build/targets.py
python
BasicTarget.compute_usage_requirements
(self, subvariant)
return result
Given the set of generated targets, and refined build properties, determines and sets appripriate usage requirements on those targets.
Given the set of generated targets, and refined build properties, determines and sets appripriate usage requirements on those targets.
[ "Given", "the", "set", "of", "generated", "targets", "and", "refined", "build", "properties", "determines", "and", "sets", "appripriate", "usage", "requirements", "on", "those", "targets", "." ]
def compute_usage_requirements (self, subvariant): """ Given the set of generated targets, and refined build properties, determines and sets appripriate usage requirements on those targets. """ assert isinstance(subvariant, virtual_target.Subvariant) rproperties = subvariant.build_properties () xusage_requirements =self.evaluate_requirements( self.usage_requirements_, rproperties, "added") # We generate all dependency properties and add them, # as well as their usage requirements, to result. (r1, r2) = self.generate_dependency_properties(xusage_requirements.dependency (), rproperties) extra = r1 + r2 result = property_set.create (xusage_requirements.non_dependency () + extra) # Propagate usage requirements we've got from sources, except # for the <pch-header> and <pch-file> features. # # That feature specifies which pch file to use, and should apply # only to direct dependents. Consider: # # pch pch1 : ... # lib lib1 : ..... pch1 ; # pch pch2 : # lib lib2 : pch2 lib1 ; # # Here, lib2 should not get <pch-header> property from pch1. # # Essentially, when those two features are in usage requirements, # they are propagated only to direct dependents. We might need # a more general mechanism, but for now, only those two # features are special. removed_pch = filter(lambda prop: prop.feature().name() not in ['<pch-header>', '<pch-file>'], subvariant.sources_usage_requirements().all()) result = result.add(property_set.PropertySet(removed_pch)) return result
[ "def", "compute_usage_requirements", "(", "self", ",", "subvariant", ")", ":", "assert", "isinstance", "(", "subvariant", ",", "virtual_target", ".", "Subvariant", ")", "rproperties", "=", "subvariant", ".", "build_properties", "(", ")", "xusage_requirements", "=", "self", ".", "evaluate_requirements", "(", "self", ".", "usage_requirements_", ",", "rproperties", ",", "\"added\"", ")", "# We generate all dependency properties and add them,", "# as well as their usage requirements, to result.", "(", "r1", ",", "r2", ")", "=", "self", ".", "generate_dependency_properties", "(", "xusage_requirements", ".", "dependency", "(", ")", ",", "rproperties", ")", "extra", "=", "r1", "+", "r2", "result", "=", "property_set", ".", "create", "(", "xusage_requirements", ".", "non_dependency", "(", ")", "+", "extra", ")", "# Propagate usage requirements we've got from sources, except", "# for the <pch-header> and <pch-file> features.", "#", "# That feature specifies which pch file to use, and should apply", "# only to direct dependents. Consider:", "#", "# pch pch1 : ...", "# lib lib1 : ..... pch1 ;", "# pch pch2 :", "# lib lib2 : pch2 lib1 ;", "#", "# Here, lib2 should not get <pch-header> property from pch1.", "#", "# Essentially, when those two features are in usage requirements,", "# they are propagated only to direct dependents. We might need", "# a more general mechanism, but for now, only those two", "# features are special.", "removed_pch", "=", "filter", "(", "lambda", "prop", ":", "prop", ".", "feature", "(", ")", ".", "name", "(", ")", "not", "in", "[", "'<pch-header>'", ",", "'<pch-file>'", "]", ",", "subvariant", ".", "sources_usage_requirements", "(", ")", ".", "all", "(", ")", ")", "result", "=", "result", ".", "add", "(", "property_set", ".", "PropertySet", "(", "removed_pch", ")", ")", "return", "result" ]
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/targets.py#L1282-L1319
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
parserCtxt.validate
(self, validate)
Switch the parser to validation mode.
Switch the parser to validation mode.
[ "Switch", "the", "parser", "to", "validation", "mode", "." ]
def validate(self, validate): """Switch the parser to validation mode. """ libxml2mod.xmlParserSetValidate(self._o, validate)
[ "def", "validate", "(", "self", ",", "validate", ")", ":", "libxml2mod", ".", "xmlParserSetValidate", "(", "self", ".", "_o", ",", "validate", ")" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L4884-L4886
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
dali/python/nvidia/dali/pipeline.py
python
Pipeline.feed_input
(self, data_node, data, layout = None, cuda_stream = None, use_copy_kernel = False)
Pass a mutlidimensional array or DLPack (or a list thereof) to an output of ExternalSource. In the case of the GPU input, the data must be modified on the same stream as the one used by feed_input. See ``cuda_stream`` parameter for details. Parameters ---------- data_node : :class:`DataNode` or str The name of the :class:`nvidia.dali.fn.external_source` node or a :class:`DataNode` object returned by a call to that ExternalSource. data : an ndarray or DLPack or a list thereof The array(s) may be one of: * NumPy ndarray (CPU) * MXNet ndarray (CPU) * PyTorch tensor (CPU or GPU) * CuPy array (GPU) * objects implementing ``__cuda_array_interface__`` * DALI `TensorList` or list of DALI `Tensor` objects The data to be used as the output of the ExternalSource referred to by `data_node`. layout : str or None The description of the data layout (or empty string, if not specified). It should be a string of the length that matches the dimensionality of the data, batch dimension excluded. For a batch of channel-first images, this should be "CHW", for channel-last video it's "FHWC" and so on. If ``data`` is a DALI `TensorList` or a list of DALI `Tensor` objects and ``layout`` is ``None``, the layout is taken from ``data``. cuda_stream : optional, `cudaStream_t` or an object convertible to `cudaStream_t`, e.g. `cupy.cuda.Stream`, `torch.cuda.Stream` The CUDA stream, which is going to be used for copying data to GPU or from a GPU source. If not set, best effort will be taken to maintain correctness - i.e. if the data is provided as a tensor/array from a recognized library (CuPy, PyTorch), the library's current stream is used. This should work in typical scenarios, but advanced use cases (and code using unsupported libraries) may still need to supply the stream handle explicitly. Special values: * 0 - use default CUDA stream * -1 - use DALI's internal stream If internal stream is used, the call to ``feed_input`` will block until the copy to internal buffer is complete, since there's no way to synchronize with this stream to prevent overwriting the array with new data in another stream. use_copy_kernel : optional, `bool` If set to True, DALI will use a CUDA kernel to feed the data (only applicable when copying data to/from GPU memory) instead of cudaMemcpyAsync (default).
Pass a mutlidimensional array or DLPack (or a list thereof) to an output of ExternalSource. In the case of the GPU input, the data must be modified on the same stream as the one used by feed_input. See ``cuda_stream`` parameter for details.
[ "Pass", "a", "mutlidimensional", "array", "or", "DLPack", "(", "or", "a", "list", "thereof", ")", "to", "an", "output", "of", "ExternalSource", ".", "In", "the", "case", "of", "the", "GPU", "input", "the", "data", "must", "be", "modified", "on", "the", "same", "stream", "as", "the", "one", "used", "by", "feed_input", ".", "See", "cuda_stream", "parameter", "for", "details", "." ]
def feed_input(self, data_node, data, layout = None, cuda_stream = None, use_copy_kernel = False): """Pass a mutlidimensional array or DLPack (or a list thereof) to an output of ExternalSource. In the case of the GPU input, the data must be modified on the same stream as the one used by feed_input. See ``cuda_stream`` parameter for details. Parameters ---------- data_node : :class:`DataNode` or str The name of the :class:`nvidia.dali.fn.external_source` node or a :class:`DataNode` object returned by a call to that ExternalSource. data : an ndarray or DLPack or a list thereof The array(s) may be one of: * NumPy ndarray (CPU) * MXNet ndarray (CPU) * PyTorch tensor (CPU or GPU) * CuPy array (GPU) * objects implementing ``__cuda_array_interface__`` * DALI `TensorList` or list of DALI `Tensor` objects The data to be used as the output of the ExternalSource referred to by `data_node`. layout : str or None The description of the data layout (or empty string, if not specified). It should be a string of the length that matches the dimensionality of the data, batch dimension excluded. For a batch of channel-first images, this should be "CHW", for channel-last video it's "FHWC" and so on. If ``data`` is a DALI `TensorList` or a list of DALI `Tensor` objects and ``layout`` is ``None``, the layout is taken from ``data``. cuda_stream : optional, `cudaStream_t` or an object convertible to `cudaStream_t`, e.g. `cupy.cuda.Stream`, `torch.cuda.Stream` The CUDA stream, which is going to be used for copying data to GPU or from a GPU source. If not set, best effort will be taken to maintain correctness - i.e. if the data is provided as a tensor/array from a recognized library (CuPy, PyTorch), the library's current stream is used. This should work in typical scenarios, but advanced use cases (and code using unsupported libraries) may still need to supply the stream handle explicitly. Special values: * 0 - use default CUDA stream * -1 - use DALI's internal stream If internal stream is used, the call to ``feed_input`` will block until the copy to internal buffer is complete, since there's no way to synchronize with this stream to prevent overwriting the array with new data in another stream. use_copy_kernel : optional, `bool` If set to True, DALI will use a CUDA kernel to feed the data (only applicable when copying data to/from GPU memory) instead of cudaMemcpyAsync (default). """ if not self._built: raise RuntimeError("Pipeline must be built first.") if isinstance(data_node, str): name = data_node else: _data_node._check(data_node) name = data_node.name # Check for use of feed_input on an external_source operator that was initialized with 'source'. if next((op._callback is not None for op in self._ops if op.name == name), False): raise RuntimeError(f"Cannot use `feed_input` on the external source '{name}' with a `source`" " argument specified.") self._feed_input(name, data, layout, cuda_stream, use_copy_kernel)
[ "def", "feed_input", "(", "self", ",", "data_node", ",", "data", ",", "layout", "=", "None", ",", "cuda_stream", "=", "None", ",", "use_copy_kernel", "=", "False", ")", ":", "if", "not", "self", ".", "_built", ":", "raise", "RuntimeError", "(", "\"Pipeline must be built first.\"", ")", "if", "isinstance", "(", "data_node", ",", "str", ")", ":", "name", "=", "data_node", "else", ":", "_data_node", ".", "_check", "(", "data_node", ")", "name", "=", "data_node", ".", "name", "# Check for use of feed_input on an external_source operator that was initialized with 'source'.", "if", "next", "(", "(", "op", ".", "_callback", "is", "not", "None", "for", "op", "in", "self", ".", "_ops", "if", "op", ".", "name", "==", "name", ")", ",", "False", ")", ":", "raise", "RuntimeError", "(", "f\"Cannot use `feed_input` on the external source '{name}' with a `source`\"", "\" argument specified.\"", ")", "self", ".", "_feed_input", "(", "name", ",", "data", ",", "layout", ",", "cuda_stream", ",", "use_copy_kernel", ")" ]
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/dali/python/nvidia/dali/pipeline.py#L733-L798
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
PrintDialogData.EnableSelection
(*args, **kwargs)
return _windows_.PrintDialogData_EnableSelection(*args, **kwargs)
EnableSelection(self, bool flag)
EnableSelection(self, bool flag)
[ "EnableSelection", "(", "self", "bool", "flag", ")" ]
def EnableSelection(*args, **kwargs): """EnableSelection(self, bool flag)""" return _windows_.PrintDialogData_EnableSelection(*args, **kwargs)
[ "def", "EnableSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintDialogData_EnableSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L5118-L5120
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/pyserial/serial/serialutil.py
python
SerialBase.getInterCharTimeout
(self)
return self._interCharTimeout
Get the current inter-character timeout setting.
Get the current inter-character timeout setting.
[ "Get", "the", "current", "inter", "-", "character", "timeout", "setting", "." ]
def getInterCharTimeout(self): """Get the current inter-character timeout setting.""" return self._interCharTimeout
[ "def", "getInterCharTimeout", "(", "self", ")", ":", "return", "self", ".", "_interCharTimeout" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/serialutil.py#L480-L482
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
examples/instance_segmentation/common.py
python
area_filter
(mask, bounding_box, img_height, img_width, size_tol=0.05)
return not_sparse and big_enough
Function to filter out masks that contain sparse instances for example: 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 This is a sparse mask 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 1 This is not a sparse mask 0 0 0 1 1 1 0 0 0 0 0 0
Function to filter out masks that contain sparse instances for example:
[ "Function", "to", "filter", "out", "masks", "that", "contain", "sparse", "instances", "for", "example", ":" ]
def area_filter(mask, bounding_box, img_height, img_width, size_tol=0.05): """ Function to filter out masks that contain sparse instances for example: 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 This is a sparse mask 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 1 This is not a sparse mask 0 0 0 1 1 1 0 0 0 0 0 0 """ xmin, ymin, xmax, ymax = bounding_box num_positive_pixels = np.sum(mask[ymin:ymax, xmin:xmax]) num_total_pixels = (xmax - xmin) * (ymax - ymin) not_sparse = num_positive_pixels / num_total_pixels >= 0.3 big_enough = (xmax - xmin) >= size_tol * img_width and ( ymax - ymin ) >= size_tol * img_height return not_sparse and big_enough
[ "def", "area_filter", "(", "mask", ",", "bounding_box", ",", "img_height", ",", "img_width", ",", "size_tol", "=", "0.05", ")", ":", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", "=", "bounding_box", "num_positive_pixels", "=", "np", ".", "sum", "(", "mask", "[", "ymin", ":", "ymax", ",", "xmin", ":", "xmax", "]", ")", "num_total_pixels", "=", "(", "xmax", "-", "xmin", ")", "*", "(", "ymax", "-", "ymin", ")", "not_sparse", "=", "num_positive_pixels", "/", "num_total_pixels", ">=", "0.3", "big_enough", "=", "(", "xmax", "-", "xmin", ")", ">=", "size_tol", "*", "img_width", "and", "(", "ymax", "-", "ymin", ")", ">=", "size_tol", "*", "img_height", "return", "not_sparse", "and", "big_enough" ]
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/examples/instance_segmentation/common.py#L21-L46
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py
python
depthwise_conv_1d_nwc_wc
( I=TensorDef(T1, S.N, S.OW * S.SW + S.KW * S.DW, S.IC), K=TensorDef(T2, S.KW, S.IC), O=TensorDef(U, S.N, S.OW, S.IC, output=True), strides=IndexAttrDef(S.SW), dilations=IndexAttrDef(S.DW))
Performs depth-wise 1-D convolution. Numeric casting is performed on the operands to the inner multiply, promoting them to the same data type as the accumulator/output. Multiplier is set to 1 which is a special case for most depthwise convolutions.
Performs depth-wise 1-D convolution.
[ "Performs", "depth", "-", "wise", "1", "-", "D", "convolution", "." ]
def depthwise_conv_1d_nwc_wc( I=TensorDef(T1, S.N, S.OW * S.SW + S.KW * S.DW, S.IC), K=TensorDef(T2, S.KW, S.IC), O=TensorDef(U, S.N, S.OW, S.IC, output=True), strides=IndexAttrDef(S.SW), dilations=IndexAttrDef(S.DW)): """Performs depth-wise 1-D convolution. Numeric casting is performed on the operands to the inner multiply, promoting them to the same data type as the accumulator/output. Multiplier is set to 1 which is a special case for most depthwise convolutions. """ implements(ConvolutionOpInterface) domain(D.n, D.ow, D.ic, D.kw) O[D.n, D.ow, D.ic] += \ TypeFn.cast(U, I[D.n, D.ow * S.SW + D.kw * S.DW, D.ic]) * \ TypeFn.cast(U, K[D.kw, D.ic])
[ "def", "depthwise_conv_1d_nwc_wc", "(", "I", "=", "TensorDef", "(", "T1", ",", "S", ".", "N", ",", "S", ".", "OW", "*", "S", ".", "SW", "+", "S", ".", "KW", "*", "S", ".", "DW", ",", "S", ".", "IC", ")", ",", "K", "=", "TensorDef", "(", "T2", ",", "S", ".", "KW", ",", "S", ".", "IC", ")", ",", "O", "=", "TensorDef", "(", "U", ",", "S", ".", "N", ",", "S", ".", "OW", ",", "S", ".", "IC", ",", "output", "=", "True", ")", ",", "strides", "=", "IndexAttrDef", "(", "S", ".", "SW", ")", ",", "dilations", "=", "IndexAttrDef", "(", "S", ".", "DW", ")", ")", ":", "implements", "(", "ConvolutionOpInterface", ")", "domain", "(", "D", ".", "n", ",", "D", ".", "ow", ",", "D", ".", "ic", ",", "D", ".", "kw", ")", "O", "[", "D", ".", "n", ",", "D", ".", "ow", ",", "D", ".", "ic", "]", "+=", "TypeFn", ".", "cast", "(", "U", ",", "I", "[", "D", ".", "n", ",", "D", ".", "ow", "*", "S", ".", "SW", "+", "D", ".", "kw", "*", "S", ".", "DW", ",", "D", ".", "ic", "]", ")", "*", "TypeFn", ".", "cast", "(", "U", ",", "K", "[", "D", ".", "kw", ",", "D", ".", "ic", "]", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L340-L356
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/run_check/run_check.py
python
_check_mul
()
Define the mul method.
Define the mul method.
[ "Define", "the", "mul", "method", "." ]
def _check_mul(): """ Define the mul method. """ from importlib import import_module import numpy as np try: ms = import_module("mindspore") except ModuleNotFoundError: ms = None finally: pass print(f"MindSpore version: ", ms.__version__) input_x = ms.Tensor(np.array([1.0, 2.0, 3.0]), ms.float32) input_y = ms.Tensor(np.array([4.0, 5.0, 6.0]), ms.float32) mul = ms.ops.Mul() mul(input_x, input_y) print(f"The result of multiplication calculation is correct, MindSpore has been installed successfully!")
[ "def", "_check_mul", "(", ")", ":", "from", "importlib", "import", "import_module", "import", "numpy", "as", "np", "try", ":", "ms", "=", "import_module", "(", "\"mindspore\"", ")", "except", "ModuleNotFoundError", ":", "ms", "=", "None", "finally", ":", "pass", "print", "(", "f\"MindSpore version: \"", ",", "ms", ".", "__version__", ")", "input_x", "=", "ms", ".", "Tensor", "(", "np", ".", "array", "(", "[", "1.0", ",", "2.0", ",", "3.0", "]", ")", ",", "ms", ".", "float32", ")", "input_y", "=", "ms", ".", "Tensor", "(", "np", ".", "array", "(", "[", "4.0", ",", "5.0", ",", "6.0", "]", ")", ",", "ms", ".", "float32", ")", "mul", "=", "ms", ".", "ops", ".", "Mul", "(", ")", "mul", "(", "input_x", ",", "input_y", ")", "print", "(", "f\"The result of multiplication calculation is correct, MindSpore has been installed successfully!\"", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/run_check/run_check.py#L23-L43
raymondlu/super-animation-samples
04234269112ff0dc32447f27a761dbbb00b8ba17
samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Type.is_function_variadic
(self)
return conf.lib.clang_isFunctionTypeVariadic(self)
Determine whether this function Type is a variadic function type.
Determine whether this function Type is a variadic function type.
[ "Determine", "whether", "this", "function", "Type", "is", "a", "variadic", "function", "type", "." ]
def is_function_variadic(self): """Determine whether this function Type is a variadic function type.""" assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self)
[ "def", "is_function_variadic", "(", "self", ")", ":", "assert", "self", ".", "kind", "==", "TypeKind", ".", "FUNCTIONPROTO", "return", "conf", ".", "lib", ".", "clang_isFunctionTypeVariadic", "(", "self", ")" ]
https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1760-L1764
epam/Indigo
30e40b4b1eb9bae0207435a26cfcb81ddcc42be1
api/python/indigo/__init__.py
python
IndigoObject.cmlFooter
(self)
return self.dispatcher._checkResult( Indigo._lib.indigoCmlFooter(self.id) )
CML builder adds footer information Returns: int: 1 if there are no errors
CML builder adds footer information
[ "CML", "builder", "adds", "footer", "information" ]
def cmlFooter(self): """CML builder adds footer information Returns: int: 1 if there are no errors """ self.dispatcher._setSessionId() return self.dispatcher._checkResult( Indigo._lib.indigoCmlFooter(self.id) )
[ "def", "cmlFooter", "(", "self", ")", ":", "self", ".", "dispatcher", ".", "_setSessionId", "(", ")", "return", "self", ".", "dispatcher", ".", "_checkResult", "(", "Indigo", ".", "_lib", ".", "indigoCmlFooter", "(", "self", ".", "id", ")", ")" ]
https://github.com/epam/Indigo/blob/30e40b4b1eb9bae0207435a26cfcb81ddcc42be1/api/python/indigo/__init__.py#L3721-L3730
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/boolean.py
python
BooleanArray.any
(self, skipna: bool = True, **kwargs)
Return whether any element is True. Returns False unless there is at least one element that is True. By default, NAs are skipped. If ``skipna=False`` is specified and missing values are present, similar :ref:`Kleene logic <boolean.kleene>` is used as for logical operations. Parameters ---------- skipna : bool, default True Exclude NA values. If the entire array is NA and `skipna` is True, then the result will be False, as for an empty array. If `skipna` is False, the result will still be True if there is at least one element that is True, otherwise NA will be returned if there are NA's present. **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- bool or :attr:`pandas.NA` See Also -------- numpy.any : Numpy version of this method. BooleanArray.all : Return whether all elements are True. Examples -------- The result indicates whether any element is True (and by default skips NAs): >>> pd.array([True, False, True]).any() True >>> pd.array([True, False, pd.NA]).any() True >>> pd.array([False, False, pd.NA]).any() False >>> pd.array([], dtype="boolean").any() False >>> pd.array([pd.NA], dtype="boolean").any() False With ``skipna=False``, the result can be NA if this is logically required (whether ``pd.NA`` is True or False influences the result): >>> pd.array([True, False, pd.NA]).any(skipna=False) True >>> pd.array([False, False, pd.NA]).any(skipna=False) <NA>
Return whether any element is True.
[ "Return", "whether", "any", "element", "is", "True", "." ]
def any(self, skipna: bool = True, **kwargs): """ Return whether any element is True. Returns False unless there is at least one element that is True. By default, NAs are skipped. If ``skipna=False`` is specified and missing values are present, similar :ref:`Kleene logic <boolean.kleene>` is used as for logical operations. Parameters ---------- skipna : bool, default True Exclude NA values. If the entire array is NA and `skipna` is True, then the result will be False, as for an empty array. If `skipna` is False, the result will still be True if there is at least one element that is True, otherwise NA will be returned if there are NA's present. **kwargs : any, default None Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns ------- bool or :attr:`pandas.NA` See Also -------- numpy.any : Numpy version of this method. BooleanArray.all : Return whether all elements are True. Examples -------- The result indicates whether any element is True (and by default skips NAs): >>> pd.array([True, False, True]).any() True >>> pd.array([True, False, pd.NA]).any() True >>> pd.array([False, False, pd.NA]).any() False >>> pd.array([], dtype="boolean").any() False >>> pd.array([pd.NA], dtype="boolean").any() False With ``skipna=False``, the result can be NA if this is logically required (whether ``pd.NA`` is True or False influences the result): >>> pd.array([True, False, pd.NA]).any(skipna=False) True >>> pd.array([False, False, pd.NA]).any(skipna=False) <NA> """ kwargs.pop("axis", None) nv.validate_any((), kwargs) values = self._data.copy() np.putmask(values, self._mask, False) result = values.any() if skipna: return result else: if result or len(self) == 0: return result else: return self.dtype.na_value
[ "def", "any", "(", "self", ",", "skipna", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "pop", "(", "\"axis\"", ",", "None", ")", "nv", ".", "validate_any", "(", "(", ")", ",", "kwargs", ")", "values", "=", "self", ".", "_data", ".", "copy", "(", ")", "np", ".", "putmask", "(", "values", ",", "self", ".", "_mask", ",", "False", ")", "result", "=", "values", ".", "any", "(", ")", "if", "skipna", ":", "return", "result", "else", ":", "if", "result", "or", "len", "(", "self", ")", "==", "0", ":", "return", "result", "else", ":", "return", "self", ".", "dtype", ".", "na_value" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/boolean.py#L450-L517
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/results_tab_widget/results_tab_model.py
python
ResultsTabModel.on_new_fit_performed
(self)
Called when a new fit has been added to the context. The function name is set to the name fit if it is the first time
Called when a new fit has been added to the context. The function name is set to the name fit if it is the first time
[ "Called", "when", "a", "new", "fit", "has", "been", "added", "to", "the", "context", ".", "The", "function", "name", "is", "set", "to", "the", "name", "fit", "if", "it", "is", "the", "first", "time" ]
def on_new_fit_performed(self): """Called when a new fit has been added to the context. The function name is set to the name fit if it is the first time""" self._update_selected_fit_function()
[ "def", "on_new_fit_performed", "(", "self", ")", ":", "self", ".", "_update_selected_fit_function", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/results_tab_widget/results_tab_model.py#L302-L305
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/chigger/geometric/CylinderSource.py
python
CylinderSource.update
(self, **kwargs)
Set the options for this cylinder. (public)
Set the options for this cylinder. (public)
[ "Set", "the", "options", "for", "this", "cylinder", ".", "(", "public", ")" ]
def update(self, **kwargs): """ Set the options for this cylinder. (public) """ super(CylinderSource, self).update(**kwargs) if self.isOptionValid('height'): self._vtksource.SetHeight(self.getOption('height')) if self.isOptionValid('radius'): self._vtksource.SetRadius(self.getOption('radius')) if self.isOptionValid('resolution'): self._vtksource.SetResolution(self.getOption('resolution')) if self.isOptionValid('capping'): self._vtksource.CappingOn()
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "CylinderSource", ",", "self", ")", ".", "update", "(", "*", "*", "kwargs", ")", "if", "self", ".", "isOptionValid", "(", "'height'", ")", ":", "self", ".", "_vtksource", ".", "SetHeight", "(", "self", ".", "getOption", "(", "'height'", ")", ")", "if", "self", ".", "isOptionValid", "(", "'radius'", ")", ":", "self", ".", "_vtksource", ".", "SetRadius", "(", "self", ".", "getOption", "(", "'radius'", ")", ")", "if", "self", ".", "isOptionValid", "(", "'resolution'", ")", ":", "self", ".", "_vtksource", ".", "SetResolution", "(", "self", ".", "getOption", "(", "'resolution'", ")", ")", "if", "self", ".", "isOptionValid", "(", "'capping'", ")", ":", "self", ".", "_vtksource", ".", "CappingOn", "(", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/geometric/CylinderSource.py#L33-L46
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
utils/vim-lldb/python-vim-lldb/vim_panes.py
python
PaneLayout.prepare
(self, panes=[])
Draw panes on screen. If empty list is provided, show all.
Draw panes on screen. If empty list is provided, show all.
[ "Draw", "panes", "on", "screen", ".", "If", "empty", "list", "is", "provided", "show", "all", "." ]
def prepare(self, panes=[]): """ Draw panes on screen. If empty list is provided, show all. """ # If we can't select a window contained in the layout, we are doing a # first draw first_draw = not self.selectWindow(True) did_first_draw = False # Prepare each registered pane for name in self.panes: if name in panes or len(panes) == 0: if first_draw: # First window in layout will be created with :vsp, and # closed later vim.command(":vsp") first_draw = False did_first_draw = True self.panes[name].prepare() if did_first_draw: # Close the split window vim.command(":q") self.selectWindow(False)
[ "def", "prepare", "(", "self", ",", "panes", "=", "[", "]", ")", ":", "# If we can't select a window contained in the layout, we are doing a", "# first draw", "first_draw", "=", "not", "self", ".", "selectWindow", "(", "True", ")", "did_first_draw", "=", "False", "# Prepare each registered pane", "for", "name", "in", "self", ".", "panes", ":", "if", "name", "in", "panes", "or", "len", "(", "panes", ")", "==", "0", ":", "if", "first_draw", ":", "# First window in layout will be created with :vsp, and", "# closed later", "vim", ".", "command", "(", "\":vsp\"", ")", "first_draw", "=", "False", "did_first_draw", "=", "True", "self", ".", "panes", "[", "name", "]", ".", "prepare", "(", ")", "if", "did_first_draw", ":", "# Close the split window", "vim", ".", "command", "(", "\":q\"", ")", "self", ".", "selectWindow", "(", "False", ")" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/vim-lldb/python-vim-lldb/vim_panes.py#L155-L178
NicknineTheEagle/TF2-Base
20459c5a7fbc995b6bf54fa85c2f62a101e9fb64
src/thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py
python
FileDescriptor.__init__
(self, name, package, options=None, serialized_pb=None)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, name, package, options=None, serialized_pb=None): """Constructor.""" super(FileDescriptor, self).__init__(options, 'FileOptions') self.name = name self.package = package self.serialized_pb = serialized_pb
[ "def", "__init__", "(", "self", ",", "name", ",", "package", ",", "options", "=", "None", ",", "serialized_pb", "=", "None", ")", ":", "super", "(", "FileDescriptor", ",", "self", ")", ".", "__init__", "(", "options", ",", "'FileOptions'", ")", "self", ".", "name", "=", "name", "self", ".", "package", "=", "package", "self", ".", "serialized_pb", "=", "serialized_pb" ]
https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py#L566-L572
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_rotate.py
python
Rotate.action
(self, arg)
Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view.
Handle the 3D scene events.
[ "Handle", "the", "3D", "scene", "events", "." ]
def action(self, arg): """Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view. """ if arg["Type"] == "SoKeyboardEvent" and arg["Key"] == "ESCAPE": self.finish() elif arg["Type"] == "SoLocation2Event": self.handle_mouse_move_event(arg) elif (arg["Type"] == "SoMouseButtonEvent" and arg["State"] == "DOWN" and arg["Button"] == "BUTTON1"): self.handle_mouse_click_event(arg)
[ "def", "action", "(", "self", ",", "arg", ")", ":", "if", "arg", "[", "\"Type\"", "]", "==", "\"SoKeyboardEvent\"", "and", "arg", "[", "\"Key\"", "]", "==", "\"ESCAPE\"", ":", "self", ".", "finish", "(", ")", "elif", "arg", "[", "\"Type\"", "]", "==", "\"SoLocation2Event\"", ":", "self", ".", "handle_mouse_move_event", "(", "arg", ")", "elif", "(", "arg", "[", "\"Type\"", "]", "==", "\"SoMouseButtonEvent\"", "and", "arg", "[", "\"State\"", "]", "==", "\"DOWN\"", "and", "arg", "[", "\"Button\"", "]", "==", "\"BUTTON1\"", ")", ":", "self", ".", "handle_mouse_click_event", "(", "arg", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_rotate.py#L101-L119
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/AIstate.py
python
AIstate.log_alliance_request
(self, initiating_empire_id, recipient_empire_id)
Keep a record of alliance requests made or received by this empire.
Keep a record of alliance requests made or received by this empire.
[ "Keep", "a", "record", "of", "alliance", "requests", "made", "or", "received", "by", "this", "empire", "." ]
def log_alliance_request(self, initiating_empire_id, recipient_empire_id): """Keep a record of alliance requests made or received by this empire.""" alliance_requests = self.diplomatic_logs.setdefault("alliance_requests", {}) log_index = (initiating_empire_id, recipient_empire_id) alliance_requests.setdefault(log_index, []).append(fo.currentTurn())
[ "def", "log_alliance_request", "(", "self", ",", "initiating_empire_id", ",", "recipient_empire_id", ")", ":", "alliance_requests", "=", "self", ".", "diplomatic_logs", ".", "setdefault", "(", "\"alliance_requests\"", ",", "{", "}", ")", "log_index", "=", "(", "initiating_empire_id", ",", "recipient_empire_id", ")", "alliance_requests", ".", "setdefault", "(", "log_index", ",", "[", "]", ")", ".", "append", "(", "fo", ".", "currentTurn", "(", ")", ")" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/AIstate.py#L1053-L1058
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStrUtil_IsLatinStr
(*args)
return _snap.TStrUtil_IsLatinStr(*args)
TStrUtil_IsLatinStr(TChA Str, double const & MinAlFrac) -> bool Parameters: Str: TChA const & MinAlFrac: double const &
TStrUtil_IsLatinStr(TChA Str, double const & MinAlFrac) -> bool
[ "TStrUtil_IsLatinStr", "(", "TChA", "Str", "double", "const", "&", "MinAlFrac", ")", "-", ">", "bool" ]
def TStrUtil_IsLatinStr(*args): """ TStrUtil_IsLatinStr(TChA Str, double const & MinAlFrac) -> bool Parameters: Str: TChA const & MinAlFrac: double const & """ return _snap.TStrUtil_IsLatinStr(*args)
[ "def", "TStrUtil_IsLatinStr", "(", "*", "args", ")", ":", "return", "_snap", ".", "TStrUtil_IsLatinStr", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L7456-L7465
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/slim/python/slim/data/data_provider.py
python
DataProvider.num_samples
(self)
return self._num_samples
Returns the number of data samples in the dataset. Returns: a positive whole number.
Returns the number of data samples in the dataset.
[ "Returns", "the", "number", "of", "data", "samples", "in", "the", "dataset", "." ]
def num_samples(self): """Returns the number of data samples in the dataset. Returns: a positive whole number. """ return self._num_samples
[ "def", "num_samples", "(", "self", ")", ":", "return", "self", ".", "_num_samples" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/slim/python/slim/data/data_provider.py#L90-L96
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/make_distrib.py
python
combine_libs
(platform, build_dir, libs, dest_lib)
Combine multiple static libraries into a single static library.
Combine multiple static libraries into a single static library.
[ "Combine", "multiple", "static", "libraries", "into", "a", "single", "static", "library", "." ]
def combine_libs(platform, build_dir, libs, dest_lib): """ Combine multiple static libraries into a single static library. """ intermediate_obj = None if platform == 'windows': cmdline = 'msvs_env.bat win%s "%s" combine_libs.py -o "%s"' % ( platform_arch, sys.executable, dest_lib) elif platform == 'mac': # Find CEF_EXPORT symbols from libcef_sandbox.a (include/cef_sandbox_mac.h) # Export only symbols that include these strings. symbol_match = [ '_cef_', # C symbols 'Cef', # C++ symbols ] print('Finding exported symbols...') assert 'libcef_sandbox.a' in libs[0], libs[0] symbols = [] for symbol in get_exported_symbols(os.path.join(build_dir, libs[0])): for match in symbol_match: if symbol.find(match) >= 0: symbols.append(symbol) break assert len(symbols) > 0 # Create an intermediate object file that combines all other object files. # Symbols not identified above will be made private (local). intermediate_obj = os.path.splitext(dest_lib)[0] + '.o' arch = 'arm64' if options.arm64build else 'x86_64' cmdline = 'ld -arch %s -r -o "%s"' % (arch, intermediate_obj) for symbol in symbols: cmdline += ' -exported_symbol %s' % symbol for lib in libs: lib_path = os.path.join(build_dir, lib) for path in get_files(lib_path): # Expand wildcards in |lib_path|. if not path_exists(path): raise Exception('File not found: ' + path) cmdline += ' "%s"' % path run(cmdline, os.path.join(cef_dir, 'tools')) if not intermediate_obj is None: # Create an archive file containing the new object file. cmdline = 'libtool -static -o "%s" "%s"' % (dest_lib, intermediate_obj) run(cmdline, os.path.join(cef_dir, 'tools')) remove_file(intermediate_obj) # Verify that only the expected symbols are exported from the archive file. print('Verifying exported symbols...') result_symbols = get_exported_symbols(dest_lib) if set(symbols) != set(result_symbols): print('Expected', symbols) print('Got', result_symbols) raise Exception('Failure verifying exported symbols') # Verify that no C++ symbols are imported by the archive file. If the # archive imports C++ symbols and the client app links an incompatible C++ # library, the result will be undefined behavior. # For example, to avoid importing libc++ symbols the cef_sandbox target # should have a dependency on libc++abi. This dependency can be verified # with the following command: # gn path out/[config] //cef:cef_sandbox //buildtools/third_party/libc++abi print('Verifying imported (undefined) symbols...') undefined_symbols = get_undefined_symbols(dest_lib) cpp_symbols = list( filter(lambda symbol: symbol.startswith('__Z'), undefined_symbols)) if cpp_symbols: print('Found C++ symbols:', cpp_symbols) raise Exception('Failure verifying imported (undefined) symbols')
[ "def", "combine_libs", "(", "platform", ",", "build_dir", ",", "libs", ",", "dest_lib", ")", ":", "intermediate_obj", "=", "None", "if", "platform", "==", "'windows'", ":", "cmdline", "=", "'msvs_env.bat win%s \"%s\" combine_libs.py -o \"%s\"'", "%", "(", "platform_arch", ",", "sys", ".", "executable", ",", "dest_lib", ")", "elif", "platform", "==", "'mac'", ":", "# Find CEF_EXPORT symbols from libcef_sandbox.a (include/cef_sandbox_mac.h)", "# Export only symbols that include these strings.", "symbol_match", "=", "[", "'_cef_'", ",", "# C symbols", "'Cef'", ",", "# C++ symbols", "]", "print", "(", "'Finding exported symbols...'", ")", "assert", "'libcef_sandbox.a'", "in", "libs", "[", "0", "]", ",", "libs", "[", "0", "]", "symbols", "=", "[", "]", "for", "symbol", "in", "get_exported_symbols", "(", "os", ".", "path", ".", "join", "(", "build_dir", ",", "libs", "[", "0", "]", ")", ")", ":", "for", "match", "in", "symbol_match", ":", "if", "symbol", ".", "find", "(", "match", ")", ">=", "0", ":", "symbols", ".", "append", "(", "symbol", ")", "break", "assert", "len", "(", "symbols", ")", ">", "0", "# Create an intermediate object file that combines all other object files.", "# Symbols not identified above will be made private (local).", "intermediate_obj", "=", "os", ".", "path", ".", "splitext", "(", "dest_lib", ")", "[", "0", "]", "+", "'.o'", "arch", "=", "'arm64'", "if", "options", ".", "arm64build", "else", "'x86_64'", "cmdline", "=", "'ld -arch %s -r -o \"%s\"'", "%", "(", "arch", ",", "intermediate_obj", ")", "for", "symbol", "in", "symbols", ":", "cmdline", "+=", "' -exported_symbol %s'", "%", "symbol", "for", "lib", "in", "libs", ":", "lib_path", "=", "os", ".", "path", ".", "join", "(", "build_dir", ",", "lib", ")", "for", "path", "in", "get_files", "(", "lib_path", ")", ":", "# Expand wildcards in |lib_path|.", "if", "not", "path_exists", "(", "path", ")", ":", "raise", "Exception", "(", "'File not found: '", "+", "path", ")", "cmdline", "+=", "' \"%s\"'", "%", "path", "run", "(", "cmdline", ",", "os", ".", "path", ".", "join", "(", "cef_dir", ",", "'tools'", ")", ")", "if", "not", "intermediate_obj", "is", "None", ":", "# Create an archive file containing the new object file.", "cmdline", "=", "'libtool -static -o \"%s\" \"%s\"'", "%", "(", "dest_lib", ",", "intermediate_obj", ")", "run", "(", "cmdline", ",", "os", ".", "path", ".", "join", "(", "cef_dir", ",", "'tools'", ")", ")", "remove_file", "(", "intermediate_obj", ")", "# Verify that only the expected symbols are exported from the archive file.", "print", "(", "'Verifying exported symbols...'", ")", "result_symbols", "=", "get_exported_symbols", "(", "dest_lib", ")", "if", "set", "(", "symbols", ")", "!=", "set", "(", "result_symbols", ")", ":", "print", "(", "'Expected'", ",", "symbols", ")", "print", "(", "'Got'", ",", "result_symbols", ")", "raise", "Exception", "(", "'Failure verifying exported symbols'", ")", "# Verify that no C++ symbols are imported by the archive file. If the", "# archive imports C++ symbols and the client app links an incompatible C++", "# library, the result will be undefined behavior.", "# For example, to avoid importing libc++ symbols the cef_sandbox target", "# should have a dependency on libc++abi. This dependency can be verified", "# with the following command:", "# gn path out/[config] //cef:cef_sandbox //buildtools/third_party/libc++abi", "print", "(", "'Verifying imported (undefined) symbols...'", ")", "undefined_symbols", "=", "get_undefined_symbols", "(", "dest_lib", ")", "cpp_symbols", "=", "list", "(", "filter", "(", "lambda", "symbol", ":", "symbol", ".", "startswith", "(", "'__Z'", ")", ",", "undefined_symbols", ")", ")", "if", "cpp_symbols", ":", "print", "(", "'Found C++ symbols:'", ",", "cpp_symbols", ")", "raise", "Exception", "(", "'Failure verifying imported (undefined) symbols'", ")" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/make_distrib.py#L355-L422
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/metrics/regression.py
python
mean_absolute_error
(y_true, y_pred, sample_weight=None, multioutput='uniform_average')
return np.average(output_errors, weights=multioutput)
Mean absolute error regression loss Read more in the :ref:`User Guide <mean_absolute_error>`. Parameters ---------- y_true : array-like of shape = (n_samples) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape = (n_samples), optional Sample weights. multioutput : string in ['raw_values', 'uniform_average'] or array-like of shape (n_outputs) Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAE output is non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_error(y_true, y_pred) 0.75 >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') array([ 0.5, 1. ]) >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) ... # doctest: +ELLIPSIS 0.849...
Mean absolute error regression loss
[ "Mean", "absolute", "error", "regression", "loss" ]
def mean_absolute_error(y_true, y_pred, sample_weight=None, multioutput='uniform_average'): """Mean absolute error regression loss Read more in the :ref:`User Guide <mean_absolute_error>`. Parameters ---------- y_true : array-like of shape = (n_samples) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape = (n_samples), optional Sample weights. multioutput : string in ['raw_values', 'uniform_average'] or array-like of shape (n_outputs) Defines aggregating of multiple output values. Array-like value defines weights used to average errors. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Errors of all outputs are averaged with uniform weight. Returns ------- loss : float or ndarray of floats If multioutput is 'raw_values', then mean absolute error is returned for each output separately. If multioutput is 'uniform_average' or an ndarray of weights, then the weighted average of all output errors is returned. MAE output is non-negative floating point. The best value is 0.0. Examples -------- >>> from sklearn.metrics import mean_absolute_error >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> mean_absolute_error(y_true, y_pred) 0.5 >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> mean_absolute_error(y_true, y_pred) 0.75 >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') array([ 0.5, 1. ]) >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) ... # doctest: +ELLIPSIS 0.849... """ y_type, y_true, y_pred, multioutput = _check_reg_targets( y_true, y_pred, multioutput) output_errors = np.average(np.abs(y_pred - y_true), weights=sample_weight, axis=0) if isinstance(multioutput, string_types): if multioutput == 'raw_values': return output_errors elif multioutput == 'uniform_average': # pass None as weights to np.average: uniform mean multioutput = None return np.average(output_errors, weights=multioutput)
[ "def", "mean_absolute_error", "(", "y_true", ",", "y_pred", ",", "sample_weight", "=", "None", ",", "multioutput", "=", "'uniform_average'", ")", ":", "y_type", ",", "y_true", ",", "y_pred", ",", "multioutput", "=", "_check_reg_targets", "(", "y_true", ",", "y_pred", ",", "multioutput", ")", "output_errors", "=", "np", ".", "average", "(", "np", ".", "abs", "(", "y_pred", "-", "y_true", ")", ",", "weights", "=", "sample_weight", ",", "axis", "=", "0", ")", "if", "isinstance", "(", "multioutput", ",", "string_types", ")", ":", "if", "multioutput", "==", "'raw_values'", ":", "return", "output_errors", "elif", "multioutput", "==", "'uniform_average'", ":", "# pass None as weights to np.average: uniform mean", "multioutput", "=", "None", "return", "np", ".", "average", "(", "output_errors", ",", "weights", "=", "multioutput", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/metrics/regression.py#L105-L173
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/image_analysis/image_analysis.py
python
resize
(image, width, height, channels=None, decode=False, resample="nearest")
Resizes the image or SArray of Images to a specific width, height, and number of channels. Parameters ---------- image : turicreate.Image | SArray The image or SArray of images to be resized. width : int The width the image is resized to. height : int The height the image is resized to. channels : int, optional The number of channels the image is resized to. 1 channel corresponds to grayscale, 3 channels corresponds to RGB, and 4 channels corresponds to RGBA images. decode : bool, optional Whether to store the resized image in decoded format. Decoded takes more space, but makes the resize and future operations on the image faster. resample : 'nearest' or 'bilinear' Specify the resampling filter: - ``'nearest'``: Nearest neigbhor, extremely fast - ``'bilinear'``: Bilinear, fast and with less aliasing artifacts Returns ------- out : turicreate.Image Returns a resized Image object. Notes ----- Grayscale Images -> Images with one channel, representing a scale from white to black RGB Images -> Images with 3 channels, with each pixel having Green, Red, and Blue values. RGBA Images -> An RGB image with an opacity channel. Examples -------- Resize a single image >>> img = turicreate.Image('https://static.turi.com/datasets/images/sample.jpg') >>> resized_img = turicreate.image_analysis.resize(img,100,100,1) Resize an SArray of images >>> url ='https://static.turi.com/datasets/images/nested' >>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False, ... recursive=True) >>> image_sarray = image_sframe["image"] >>> resized_images = turicreate.image_analysis.resize(image_sarray, 100, 100, 1)
Resizes the image or SArray of Images to a specific width, height, and number of channels.
[ "Resizes", "the", "image", "or", "SArray", "of", "Images", "to", "a", "specific", "width", "height", "and", "number", "of", "channels", "." ]
def resize(image, width, height, channels=None, decode=False, resample="nearest"): """ Resizes the image or SArray of Images to a specific width, height, and number of channels. Parameters ---------- image : turicreate.Image | SArray The image or SArray of images to be resized. width : int The width the image is resized to. height : int The height the image is resized to. channels : int, optional The number of channels the image is resized to. 1 channel corresponds to grayscale, 3 channels corresponds to RGB, and 4 channels corresponds to RGBA images. decode : bool, optional Whether to store the resized image in decoded format. Decoded takes more space, but makes the resize and future operations on the image faster. resample : 'nearest' or 'bilinear' Specify the resampling filter: - ``'nearest'``: Nearest neigbhor, extremely fast - ``'bilinear'``: Bilinear, fast and with less aliasing artifacts Returns ------- out : turicreate.Image Returns a resized Image object. Notes ----- Grayscale Images -> Images with one channel, representing a scale from white to black RGB Images -> Images with 3 channels, with each pixel having Green, Red, and Blue values. RGBA Images -> An RGB image with an opacity channel. Examples -------- Resize a single image >>> img = turicreate.Image('https://static.turi.com/datasets/images/sample.jpg') >>> resized_img = turicreate.image_analysis.resize(img,100,100,1) Resize an SArray of images >>> url ='https://static.turi.com/datasets/images/nested' >>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False, ... recursive=True) >>> image_sarray = image_sframe["image"] >>> resized_images = turicreate.image_analysis.resize(image_sarray, 100, 100, 1) """ if height < 0 or width < 0: raise ValueError("Cannot resize to negative sizes") if resample not in ("nearest", "bilinear"): raise ValueError("Unknown resample option: '%s'" % resample) from ...data_structures.sarray import SArray as _SArray from ... import extensions as _extensions import turicreate as _tc if type(image) is _Image: assert resample in ("nearest", "bilinear") resample_method = 0 if resample == "nearest" else 1 if channels is None: channels = image.channels if channels <= 0: raise ValueError("cannot resize images to 0 or fewer channels") return _extensions.resize_image( image, width, height, channels, decode, resample_method ) elif type(image) is _SArray: if channels is None: channels = 3 if channels <= 0: raise ValueError("cannot resize images to 0 or fewer channels") return image.apply( lambda x: _tc.image_analysis.resize( x, width, height, channels, decode, resample ) ) else: raise ValueError( "Cannot call 'resize' on objects that are not either an Image or SArray of Images" )
[ "def", "resize", "(", "image", ",", "width", ",", "height", ",", "channels", "=", "None", ",", "decode", "=", "False", ",", "resample", "=", "\"nearest\"", ")", ":", "if", "height", "<", "0", "or", "width", "<", "0", ":", "raise", "ValueError", "(", "\"Cannot resize to negative sizes\"", ")", "if", "resample", "not", "in", "(", "\"nearest\"", ",", "\"bilinear\"", ")", ":", "raise", "ValueError", "(", "\"Unknown resample option: '%s'\"", "%", "resample", ")", "from", ".", ".", ".", "data_structures", ".", "sarray", "import", "SArray", "as", "_SArray", "from", ".", ".", ".", "import", "extensions", "as", "_extensions", "import", "turicreate", "as", "_tc", "if", "type", "(", "image", ")", "is", "_Image", ":", "assert", "resample", "in", "(", "\"nearest\"", ",", "\"bilinear\"", ")", "resample_method", "=", "0", "if", "resample", "==", "\"nearest\"", "else", "1", "if", "channels", "is", "None", ":", "channels", "=", "image", ".", "channels", "if", "channels", "<=", "0", ":", "raise", "ValueError", "(", "\"cannot resize images to 0 or fewer channels\"", ")", "return", "_extensions", ".", "resize_image", "(", "image", ",", "width", ",", "height", ",", "channels", ",", "decode", ",", "resample_method", ")", "elif", "type", "(", "image", ")", "is", "_SArray", ":", "if", "channels", "is", "None", ":", "channels", "=", "3", "if", "channels", "<=", "0", ":", "raise", "ValueError", "(", "\"cannot resize images to 0 or fewer channels\"", ")", "return", "image", ".", "apply", "(", "lambda", "x", ":", "_tc", ".", "image_analysis", ".", "resize", "(", "x", ",", "width", ",", "height", ",", "channels", ",", "decode", ",", "resample", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Cannot call 'resize' on objects that are not either an Image or SArray of Images\"", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/image_analysis/image_analysis.py#L100-L193
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
FileInclusion.is_input_file
(self)
return self.depth == 0
True if the included file is the input file.
True if the included file is the input file.
[ "True", "if", "the", "included", "file", "is", "the", "input", "file", "." ]
def is_input_file(self): """True if the included file is the input file.""" return self.depth == 0
[ "def", "is_input_file", "(", "self", ")", ":", "return", "self", ".", "depth", "==", "0" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L2359-L2361
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/configobj/validate.py
python
is_integer
(value, min=None, max=None)
return value
A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. >>> vtor.check('integer', '-1') -1 >>> vtor.check('integer', '0') 0 >>> vtor.check('integer', 9) 9 >>> vtor.check('integer', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('integer', '2.2') Traceback (most recent call last): VdtTypeError: the value "2.2" is of the wrong type. >>> vtor.check('integer(10)', '20') 20 >>> vtor.check('integer(max=20)', '15') 15 >>> vtor.check('integer(10)', '9') Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(10)', 9) Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(max=20)', '35') Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(max=20)', 35) Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(0, 9)', False) 0
A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. >>> vtor.check('integer', '-1') -1 >>> vtor.check('integer', '0') 0 >>> vtor.check('integer', 9) 9 >>> vtor.check('integer', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('integer', '2.2') Traceback (most recent call last): VdtTypeError: the value "2.2" is of the wrong type. >>> vtor.check('integer(10)', '20') 20 >>> vtor.check('integer(max=20)', '15') 15 >>> vtor.check('integer(10)', '9') Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(10)', 9) Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(max=20)', '35') Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(max=20)', 35) Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(0, 9)', False) 0
[ "A", "check", "that", "tests", "that", "a", "given", "value", "is", "an", "integer", "(", "int", "or", "long", ")", "and", "optionally", "between", "bounds", ".", "A", "negative", "value", "is", "accepted", "while", "a", "float", "will", "fail", ".", "If", "the", "value", "is", "a", "string", "then", "the", "conversion", "is", "done", "-", "if", "possible", ".", "Otherwise", "a", "VdtError", "is", "raised", ".", ">>>", "vtor", ".", "check", "(", "integer", "-", "1", ")", "-", "1", ">>>", "vtor", ".", "check", "(", "integer", "0", ")", "0", ">>>", "vtor", ".", "check", "(", "integer", "9", ")", "9", ">>>", "vtor", ".", "check", "(", "integer", "a", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "VdtTypeError", ":", "the", "value", "a", "is", "of", "the", "wrong", "type", ".", ">>>", "vtor", ".", "check", "(", "integer", "2", ".", "2", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "VdtTypeError", ":", "the", "value", "2", ".", "2", "is", "of", "the", "wrong", "type", ".", ">>>", "vtor", ".", "check", "(", "integer", "(", "10", ")", "20", ")", "20", ">>>", "vtor", ".", "check", "(", "integer", "(", "max", "=", "20", ")", "15", ")", "15", ">>>", "vtor", ".", "check", "(", "integer", "(", "10", ")", "9", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "VdtValueTooSmallError", ":", "the", "value", "9", "is", "too", "small", ".", ">>>", "vtor", ".", "check", "(", "integer", "(", "10", ")", "9", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "VdtValueTooSmallError", ":", "the", "value", "9", "is", "too", "small", ".", ">>>", "vtor", ".", "check", "(", "integer", "(", "max", "=", "20", ")", "35", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "VdtValueTooBigError", ":", "the", "value", "35", "is", "too", "big", ".", ">>>", "vtor", ".", "check", "(", "integer", "(", "max", "=", "20", ")", "35", ")", "Traceback", "(", "most", "recent", "call", "last", ")", ":", "VdtValueTooBigError", ":", "the", "value", "35", "is", "too", "big", ".", ">>>", "vtor", ".", "check", "(", "integer", "(", "0", "9", ")", "False", ")", "0" ]
def is_integer(value, min=None, max=None): """ A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. >>> vtor.check('integer', '-1') -1 >>> vtor.check('integer', '0') 0 >>> vtor.check('integer', 9) 9 >>> vtor.check('integer', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('integer', '2.2') Traceback (most recent call last): VdtTypeError: the value "2.2" is of the wrong type. >>> vtor.check('integer(10)', '20') 20 >>> vtor.check('integer(max=20)', '15') 15 >>> vtor.check('integer(10)', '9') Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(10)', 9) Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(max=20)', '35') Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(max=20)', 35) Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(0, 9)', False) 0 """ (min_val, max_val) = _is_num_param(('min', 'max'), (min, max)) if not isinstance(value, (int, long, basestring)): raise VdtTypeError(value) if isinstance(value, basestring): # if it's a string - does it represent an integer ? try: value = int(value) except ValueError: raise VdtTypeError(value) if (min_val is not None) and (value < min_val): raise VdtValueTooSmallError(value) if (max_val is not None) and (value > max_val): raise VdtValueTooBigError(value) return value
[ "def", "is_integer", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "(", "min_val", ",", "max_val", ")", "=", "_is_num_param", "(", "(", "'min'", ",", "'max'", ")", ",", "(", "min", ",", "max", ")", ")", "if", "not", "isinstance", "(", "value", ",", "(", "int", ",", "long", ",", "basestring", ")", ")", ":", "raise", "VdtTypeError", "(", "value", ")", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "# if it's a string - does it represent an integer ?", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "VdtTypeError", "(", "value", ")", "if", "(", "min_val", "is", "not", "None", ")", "and", "(", "value", "<", "min_val", ")", ":", "raise", "VdtValueTooSmallError", "(", "value", ")", "if", "(", "max_val", "is", "not", "None", ")", "and", "(", "value", ">", "max_val", ")", ":", "raise", "VdtValueTooBigError", "(", "value", ")", "return", "value" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/configobj/validate.py#L755-L808
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py
python
calldef_t._get__cmp__call_items
(self)
Implementation detail.
Implementation detail.
[ "Implementation", "detail", "." ]
def _get__cmp__call_items(self): """ Implementation detail. """ raise NotImplementedError()
[ "def", "_get__cmp__call_items", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py#L169-L175
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/nn/layer/transformer.py
python
TransformerEncoder.gen_cache
(self, src)
return cache
r""" Generates cache for `forward` usage. The generated cache is a list, and each element in it is `incremental_cache` produced by `TransformerEncoderLayer.gen_cache`. See `TransformerEncoderLayer.gen_cache` for more details. Parameters: src (Tensor): The input of Transformer encoder. It is a tensor with shape `[batch_size, source_length, d_model]`. The data type should be float32 or float64. Returns: list: It is a list, and each element in the list is `incremental_cache` produced by `TransformerEncoderLayer.gen_cache`. See `TransformerEncoderLayer.gen_cache` for more details.
r""" Generates cache for `forward` usage. The generated cache is a list, and each element in it is `incremental_cache` produced by `TransformerEncoderLayer.gen_cache`. See `TransformerEncoderLayer.gen_cache` for more details.
[ "r", "Generates", "cache", "for", "forward", "usage", ".", "The", "generated", "cache", "is", "a", "list", "and", "each", "element", "in", "it", "is", "incremental_cache", "produced", "by", "TransformerEncoderLayer", ".", "gen_cache", ".", "See", "TransformerEncoderLayer", ".", "gen_cache", "for", "more", "details", "." ]
def gen_cache(self, src): r""" Generates cache for `forward` usage. The generated cache is a list, and each element in it is `incremental_cache` produced by `TransformerEncoderLayer.gen_cache`. See `TransformerEncoderLayer.gen_cache` for more details. Parameters: src (Tensor): The input of Transformer encoder. It is a tensor with shape `[batch_size, source_length, d_model]`. The data type should be float32 or float64. Returns: list: It is a list, and each element in the list is `incremental_cache` produced by `TransformerEncoderLayer.gen_cache`. See `TransformerEncoderLayer.gen_cache` for more details. """ cache = [layer.gen_cache(src) for layer in self.layers] return cache
[ "def", "gen_cache", "(", "self", ",", "src", ")", ":", "cache", "=", "[", "layer", ".", "gen_cache", "(", "src", ")", "for", "layer", "in", "self", ".", "layers", "]", "return", "cache" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/layer/transformer.py#L709-L727
ap--/python-seabreeze
86e9145edf7a30cedd4dffd4658a142aeab2d2fc
src/seabreeze/pyseabreeze/devices.py
python
SeaBreezeDevice.is_open
(self)
return self._transport.is_open
returns if the spectrometer device usb connection is opened Returns ------- bool
returns if the spectrometer device usb connection is opened
[ "returns", "if", "the", "spectrometer", "device", "usb", "connection", "is", "opened" ]
def is_open(self) -> bool: """returns if the spectrometer device usb connection is opened Returns ------- bool """ return self._transport.is_open
[ "def", "is_open", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_transport", ".", "is_open" ]
https://github.com/ap--/python-seabreeze/blob/86e9145edf7a30cedd4dffd4658a142aeab2d2fc/src/seabreeze/pyseabreeze/devices.py#L395-L402
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pyedbglib/protocols/avr8protocol.py
python
Avr8Protocol.leave_progmode
(self)
Exits programming mode
Exits programming mode
[ "Exits", "programming", "mode" ]
def leave_progmode(self): """Exits programming mode""" self.logger.debug("Leave prog mode") self.check_response(self.jtagice3_command_response(bytearray([self.CMD_AVR8_PROG_MODE_LEAVE, self.CMD_VERSION0])))
[ "def", "leave_progmode", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Leave prog mode\"", ")", "self", ".", "check_response", "(", "self", ".", "jtagice3_command_response", "(", "bytearray", "(", "[", "self", ".", "CMD_AVR8_PROG_MODE_LEAVE", ",", "self", ".", "CMD_VERSION0", "]", ")", ")", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pyedbglib/protocols/avr8protocol.py#L297-L301
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/training/supervisor.py
python
Supervisor.start_standard_services
(self, sess)
return threads
Start the standard services for 'sess'. This starts services in the background. The services started depend on the parameters to the constructor and may include: - A Summary thread computing summaries every save_summaries_secs. - A Checkpoint thread saving the model every save_model_secs. - A StepCounter thread measure step time. Args: sess: A Session. Returns: A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join(<list of threads>) Raises: RuntimeError: If called with a non-chief Supervisor. ValueError: If not `logdir` was passed to the constructor as the services need a log directory.
Start the standard services for 'sess'.
[ "Start", "the", "standard", "services", "for", "sess", "." ]
def start_standard_services(self, sess): """Start the standard services for 'sess'. This starts services in the background. The services started depend on the parameters to the constructor and may include: - A Summary thread computing summaries every save_summaries_secs. - A Checkpoint thread saving the model every save_model_secs. - A StepCounter thread measure step time. Args: sess: A Session. Returns: A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join(<list of threads>) Raises: RuntimeError: If called with a non-chief Supervisor. ValueError: If not `logdir` was passed to the constructor as the services need a log directory. """ if not self._is_chief: raise RuntimeError("Only chief supervisor can start standard services. " "Because only chief supervisors can write events.") if not self._logdir: logging.warning("Standard services need a 'logdir' " "passed to the SessionManager") return if self._global_step is not None and self._summary_writer: # Only add the session log if we keep track of global step. # TensorBoard cannot use START message for purging expired events # if there is no step value. current_step = training_util.global_step(sess, self._global_step) self._summary_writer.add_session_log( SessionLog(status=SessionLog.START), current_step) threads = [] if self._save_summaries_secs and self._summary_writer: if self._summary_op is not None: threads.append(SVSummaryThread(self, sess)) if self._global_step is not None: threads.append(SVStepCounterThread(self, sess)) if self.saver and self._save_model_secs: threads.append(SVTimerCheckpointThread(self, sess)) for t in threads: t.start() return threads
[ "def", "start_standard_services", "(", "self", ",", "sess", ")", ":", "if", "not", "self", ".", "_is_chief", ":", "raise", "RuntimeError", "(", "\"Only chief supervisor can start standard services. \"", "\"Because only chief supervisors can write events.\"", ")", "if", "not", "self", ".", "_logdir", ":", "logging", ".", "warning", "(", "\"Standard services need a 'logdir' \"", "\"passed to the SessionManager\"", ")", "return", "if", "self", ".", "_global_step", "is", "not", "None", "and", "self", ".", "_summary_writer", ":", "# Only add the session log if we keep track of global step.", "# TensorBoard cannot use START message for purging expired events", "# if there is no step value.", "current_step", "=", "training_util", ".", "global_step", "(", "sess", ",", "self", ".", "_global_step", ")", "self", ".", "_summary_writer", ".", "add_session_log", "(", "SessionLog", "(", "status", "=", "SessionLog", ".", "START", ")", ",", "current_step", ")", "threads", "=", "[", "]", "if", "self", ".", "_save_summaries_secs", "and", "self", ".", "_summary_writer", ":", "if", "self", ".", "_summary_op", "is", "not", "None", ":", "threads", ".", "append", "(", "SVSummaryThread", "(", "self", ",", "sess", ")", ")", "if", "self", ".", "_global_step", "is", "not", "None", ":", "threads", ".", "append", "(", "SVStepCounterThread", "(", "self", ",", "sess", ")", ")", "if", "self", ".", "saver", "and", "self", ".", "_save_model_secs", ":", "threads", ".", "append", "(", "SVTimerCheckpointThread", "(", "self", ",", "sess", ")", ")", "for", "t", "in", "threads", ":", "t", ".", "start", "(", ")", "return", "threads" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/training/supervisor.py#L587-L638
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/incubate/fleet/base/role_maker.py
python
GeneralRoleMaker._server_num
(self)
return len(self._server_endpoints)
return the current number of server
return the current number of server
[ "return", "the", "current", "number", "of", "server" ]
def _server_num(self): """ return the current number of server """ if not self._role_is_generated: self.generate_role() return len(self._server_endpoints)
[ "def", "_server_num", "(", "self", ")", ":", "if", "not", "self", ".", "_role_is_generated", ":", "self", ".", "generate_role", "(", ")", "return", "len", "(", "self", ".", "_server_endpoints", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/base/role_maker.py#L892-L898
p4lang/behavioral-model
81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9
tools/runtime_CLI.py
python
RuntimeAPI.do_mc_node_dissociate
(self, line)
Dissociate node from multicast group: mc_node_associate <group handle> <node handle>
Dissociate node from multicast group: mc_node_associate <group handle> <node handle>
[ "Dissociate", "node", "from", "multicast", "group", ":", "mc_node_associate", "<group", "handle", ">", "<node", "handle", ">" ]
def do_mc_node_dissociate(self, line): "Dissociate node from multicast group: mc_node_associate <group handle> <node handle>" self.check_has_pre() args = line.split() self.exactly_n_args(args, 2) mgrp = self.get_mgrp(args[0]) l1_hdl = self.get_node_handle(args[1]) print("Dissociating node", l1_hdl, "from multicast group", mgrp) self.mc_client.bm_mc_node_dissociate(0, mgrp, l1_hdl)
[ "def", "do_mc_node_dissociate", "(", "self", ",", "line", ")", ":", "self", ".", "check_has_pre", "(", ")", "args", "=", "line", ".", "split", "(", ")", "self", ".", "exactly_n_args", "(", "args", ",", "2", ")", "mgrp", "=", "self", ".", "get_mgrp", "(", "args", "[", "0", "]", ")", "l1_hdl", "=", "self", ".", "get_node_handle", "(", "args", "[", "1", "]", ")", "print", "(", "\"Dissociating node\"", ",", "l1_hdl", ",", "\"from multicast group\"", ",", "mgrp", ")", "self", ".", "mc_client", ".", "bm_mc_node_dissociate", "(", "0", ",", "mgrp", ",", "l1_hdl", ")" ]
https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/runtime_CLI.py#L1822-L1830
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
Pythonwin/pywin/framework/scriptutils.py
python
GetActiveView
()
Gets the edit control (eg, EditView) with the focus, or None
Gets the edit control (eg, EditView) with the focus, or None
[ "Gets", "the", "edit", "control", "(", "eg", "EditView", ")", "with", "the", "focus", "or", "None" ]
def GetActiveView(): """Gets the edit control (eg, EditView) with the focus, or None""" try: childFrame, bIsMaximised = win32ui.GetMainFrame().MDIGetActive() return childFrame.GetActiveView() except win32ui.error: return None
[ "def", "GetActiveView", "(", ")", ":", "try", ":", "childFrame", ",", "bIsMaximised", "=", "win32ui", ".", "GetMainFrame", "(", ")", ".", "MDIGetActive", "(", ")", "return", "childFrame", ".", "GetActiveView", "(", ")", "except", "win32ui", ".", "error", ":", "return", "None" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/Pythonwin/pywin/framework/scriptutils.py#L133-L139
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py
python
_Timer.cancel
(self)
Stop the timer if it hasn't finished yet
Stop the timer if it hasn't finished yet
[ "Stop", "the", "timer", "if", "it", "hasn", "t", "finished", "yet" ]
def cancel(self): """Stop the timer if it hasn't finished yet""" self.finished.set()
[ "def", "cancel", "(", "self", ")", ":", "self", ".", "finished", ".", "set", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py#L1073-L1075
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py
python
_update_zipimporter_cache
(normalized_path, cache, updater=None)
Update zipimporter cache data for a given normalized path. Any sub-path entries are processed as well, i.e. those corresponding to zip archives embedded in other zip archives. Given updater is a callable taking a cache entry key and the original entry (after already removing the entry from the cache), and expected to update the entry and possibly return a new one to be inserted in its place. Returning None indicates that the entry should not be replaced with a new one. If no updater is given, the cache entries are simply removed without any additional processing, the same as if the updater simply returned None.
Update zipimporter cache data for a given normalized path.
[ "Update", "zipimporter", "cache", "data", "for", "a", "given", "normalized", "path", "." ]
def _update_zipimporter_cache(normalized_path, cache, updater=None): """ Update zipimporter cache data for a given normalized path. Any sub-path entries are processed as well, i.e. those corresponding to zip archives embedded in other zip archives. Given updater is a callable taking a cache entry key and the original entry (after already removing the entry from the cache), and expected to update the entry and possibly return a new one to be inserted in its place. Returning None indicates that the entry should not be replaced with a new one. If no updater is given, the cache entries are simply removed without any additional processing, the same as if the updater simply returned None. """ for p in _collect_zipimporter_cache_entries(normalized_path, cache): # N.B. pypy's custom zipimport._zip_directory_cache implementation does # not support the complete dict interface: # * Does not support item assignment, thus not allowing this function # to be used only for removing existing cache entries. # * Does not support the dict.pop() method, forcing us to use the # get/del patterns instead. For more detailed information see the # following links: # https://github.com/pypa/setuptools/issues/202#issuecomment-202913420 # http://bit.ly/2h9itJX old_entry = cache[p] del cache[p] new_entry = updater and updater(p, old_entry) if new_entry is not None: cache[p] = new_entry
[ "def", "_update_zipimporter_cache", "(", "normalized_path", ",", "cache", ",", "updater", "=", "None", ")", ":", "for", "p", "in", "_collect_zipimporter_cache_entries", "(", "normalized_path", ",", "cache", ")", ":", "# N.B. pypy's custom zipimport._zip_directory_cache implementation does", "# not support the complete dict interface:", "# * Does not support item assignment, thus not allowing this function", "# to be used only for removing existing cache entries.", "# * Does not support the dict.pop() method, forcing us to use the", "# get/del patterns instead. For more detailed information see the", "# following links:", "# https://github.com/pypa/setuptools/issues/202#issuecomment-202913420", "# http://bit.ly/2h9itJX", "old_entry", "=", "cache", "[", "p", "]", "del", "cache", "[", "p", "]", "new_entry", "=", "updater", "and", "updater", "(", "p", ",", "old_entry", ")", "if", "new_entry", "is", "not", "None", ":", "cache", "[", "p", "]", "=", "new_entry" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py#L1845-L1874
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/compiler.py
python
CodeGenerator.indent
(self)
Indent by one.
Indent by one.
[ "Indent", "by", "one", "." ]
def indent(self): """Indent by one.""" self._indentation += 1
[ "def", "indent", "(", "self", ")", ":", "self", ".", "_indentation", "+=", "1" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/compiler.py#L451-L453
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
utils/lit/lit/util.py
python
to_bytes
(s)
return s.encode('utf-8')
Return the parameter as type 'bytes', possibly encoding it. In Python2, the 'bytes' type is the same as 'str'. In Python3, they are distinct.
Return the parameter as type 'bytes', possibly encoding it.
[ "Return", "the", "parameter", "as", "type", "bytes", "possibly", "encoding", "it", "." ]
def to_bytes(s): """Return the parameter as type 'bytes', possibly encoding it. In Python2, the 'bytes' type is the same as 'str'. In Python3, they are distinct. """ if isinstance(s, bytes): # In Python2, this branch is taken for both 'str' and 'bytes'. # In Python3, this branch is taken only for 'bytes'. return s # In Python2, 's' is a 'unicode' object. # In Python3, 's' is a 'str' object. # Encode to UTF-8 to get 'bytes' data. return s.encode('utf-8')
[ "def", "to_bytes", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "# In Python2, this branch is taken for both 'str' and 'bytes'.", "# In Python3, this branch is taken only for 'bytes'.", "return", "s", "# In Python2, 's' is a 'unicode' object.", "# In Python3, 's' is a 'str' object.", "# Encode to UTF-8 to get 'bytes' data.", "return", "s", ".", "encode", "(", "'utf-8'", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/utils/lit/lit/util.py#L47-L61
mysql/mysql-workbench
2f35f9034f015cbcd22139a60e1baa2e3e8e795c
plugins/wb.admin/backend/wb_admin_perfschema_instrumentation_be.py
python
PSInstrumentGroup.set_initial_states
(self)
Deep first method to set the initial states of the hierarchy groups based on the status of the leaf elements
Deep first method to set the initial states of the hierarchy groups based on the status of the leaf elements
[ "Deep", "first", "method", "to", "set", "the", "initial", "states", "of", "the", "hierarchy", "groups", "based", "on", "the", "status", "of", "the", "leaf", "elements" ]
def set_initial_states(self): """ Deep first method to set the initial states of the hierarchy groups based on the status of the leaf elements """ if '_data_' not in self: for key in list(self.keys()): self[key].set_initial_states() self.set_state_from_children('enabled') self.set_state_from_children('timed')
[ "def", "set_initial_states", "(", "self", ")", ":", "if", "'_data_'", "not", "in", "self", ":", "for", "key", "in", "list", "(", "self", ".", "keys", "(", ")", ")", ":", "self", "[", "key", "]", ".", "set_initial_states", "(", ")", "self", ".", "set_state_from_children", "(", "'enabled'", ")", "self", ".", "set_state_from_children", "(", "'timed'", ")" ]
https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/plugins/wb.admin/backend/wb_admin_perfschema_instrumentation_be.py#L134-L145
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Context.py
python
Context.recurse
(self, dirs, name=None, mandatory=True, once=True)
Run user code from the supplied list of directories. The directories can be either absolute, or relative to the directory of the wscript file. The methods :py:meth:`waflib.Context.Context.pre_recurse` and :py:meth:`waflib.Context.Context.post_recurse` are called immediately before and after a script has been executed. :param dirs: List of directories to visit :type dirs: list of string or space-separated string :param name: Name of function to invoke from the wscript :type name: string :param mandatory: whether sub wscript files are required to exist :type mandatory: bool :param once: read the script file once for a particular context :type once: bool
Run user code from the supplied list of directories. The directories can be either absolute, or relative to the directory of the wscript file. The methods :py:meth:`waflib.Context.Context.pre_recurse` and :py:meth:`waflib.Context.Context.post_recurse` are called immediately before and after a script has been executed.
[ "Run", "user", "code", "from", "the", "supplied", "list", "of", "directories", ".", "The", "directories", "can", "be", "either", "absolute", "or", "relative", "to", "the", "directory", "of", "the", "wscript", "file", ".", "The", "methods", ":", "py", ":", "meth", ":", "waflib", ".", "Context", ".", "Context", ".", "pre_recurse", "and", ":", "py", ":", "meth", ":", "waflib", ".", "Context", ".", "Context", ".", "post_recurse", "are", "called", "immediately", "before", "and", "after", "a", "script", "has", "been", "executed", "." ]
def recurse(self, dirs, name=None, mandatory=True, once=True): """ Run user code from the supplied list of directories. The directories can be either absolute, or relative to the directory of the wscript file. The methods :py:meth:`waflib.Context.Context.pre_recurse` and :py:meth:`waflib.Context.Context.post_recurse` are called immediately before and after a script has been executed. :param dirs: List of directories to visit :type dirs: list of string or space-separated string :param name: Name of function to invoke from the wscript :type name: string :param mandatory: whether sub wscript files are required to exist :type mandatory: bool :param once: read the script file once for a particular context :type once: bool """ try: cache = self.recurse_cache except AttributeError: cache = self.recurse_cache = {} for d in Utils.to_list(dirs): if not os.path.isabs(d): # absolute paths only d = os.path.join(self.path.abspath(), d) WSCRIPT = os.path.join(d, WSCRIPT_FILE) WSCRIPT_FUN = WSCRIPT + '_' + (name or self.fun) node = self.root.find_node(WSCRIPT_FUN) if node and (not once or node not in cache): cache[node] = True self.pre_recurse(node) try: function_code = node.read('rU') exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict) finally: self.post_recurse(node) elif not node: node = self.root.find_node(WSCRIPT) tup = (node, name or self.fun) if node and (not once or tup not in cache): cache[tup] = True self.pre_recurse(node) try: wscript_module = load_module(node.abspath()) user_function = getattr(wscript_module, (name or self.fun), None) if not user_function: user_function = getattr(wscript_module, 'build', None) # Fall back to 'build' function if not user_function: if not mandatory: continue raise Errors.WafError('No function %s defined in %s' % (name or self.fun, node.abspath())) self.execute_user_function( user_function, wscript_module ) finally: self.post_recurse(node) elif not node: if not mandatory: continue raise Errors.WafError('No wscript file in directory %s' % d)
[ "def", "recurse", "(", "self", ",", "dirs", ",", "name", "=", "None", ",", "mandatory", "=", "True", ",", "once", "=", "True", ")", ":", "try", ":", "cache", "=", "self", ".", "recurse_cache", "except", "AttributeError", ":", "cache", "=", "self", ".", "recurse_cache", "=", "{", "}", "for", "d", "in", "Utils", ".", "to_list", "(", "dirs", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "d", ")", ":", "# absolute paths only", "d", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ".", "abspath", "(", ")", ",", "d", ")", "WSCRIPT", "=", "os", ".", "path", ".", "join", "(", "d", ",", "WSCRIPT_FILE", ")", "WSCRIPT_FUN", "=", "WSCRIPT", "+", "'_'", "+", "(", "name", "or", "self", ".", "fun", ")", "node", "=", "self", ".", "root", ".", "find_node", "(", "WSCRIPT_FUN", ")", "if", "node", "and", "(", "not", "once", "or", "node", "not", "in", "cache", ")", ":", "cache", "[", "node", "]", "=", "True", "self", ".", "pre_recurse", "(", "node", ")", "try", ":", "function_code", "=", "node", ".", "read", "(", "'rU'", ")", "exec", "(", "compile", "(", "function_code", ",", "node", ".", "abspath", "(", ")", ",", "'exec'", ")", ",", "self", ".", "exec_dict", ")", "finally", ":", "self", ".", "post_recurse", "(", "node", ")", "elif", "not", "node", ":", "node", "=", "self", ".", "root", ".", "find_node", "(", "WSCRIPT", ")", "tup", "=", "(", "node", ",", "name", "or", "self", ".", "fun", ")", "if", "node", "and", "(", "not", "once", "or", "tup", "not", "in", "cache", ")", ":", "cache", "[", "tup", "]", "=", "True", "self", ".", "pre_recurse", "(", "node", ")", "try", ":", "wscript_module", "=", "load_module", "(", "node", ".", "abspath", "(", ")", ")", "user_function", "=", "getattr", "(", "wscript_module", ",", "(", "name", "or", "self", ".", "fun", ")", ",", "None", ")", "if", "not", "user_function", ":", "user_function", "=", "getattr", "(", "wscript_module", ",", "'build'", ",", "None", ")", "# Fall back to 'build' function", "if", "not", "user_function", ":", "if", "not", "mandatory", ":", "continue", "raise", "Errors", ".", "WafError", "(", "'No function %s defined in %s'", "%", "(", "name", "or", "self", ".", "fun", ",", "node", ".", "abspath", "(", ")", ")", ")", "self", ".", "execute_user_function", "(", "user_function", ",", "wscript_module", ")", "finally", ":", "self", ".", "post_recurse", "(", "node", ")", "elif", "not", "node", ":", "if", "not", "mandatory", ":", "continue", "raise", "Errors", ".", "WafError", "(", "'No wscript file in directory %s'", "%", "d", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Context.py#L268-L331
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/indentation.py
python
IndentationRules.__init__
(self)
Initializes the IndentationRules checker.
Initializes the IndentationRules checker.
[ "Initializes", "the", "IndentationRules", "checker", "." ]
def __init__(self): """Initializes the IndentationRules checker.""" self._stack = [] # Map from line number to number of characters it is off in indentation. self._start_index_offset = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_stack", "=", "[", "]", "# Map from line number to number of characters it is off in indentation.", "self", ".", "_start_index_offset", "=", "{", "}" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/indentation.py#L113-L118
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/simnet/train/tf/losses/simnet_loss.py
python
PairwiseHingeLoss.__init__
(self, config)
init function
init function
[ "init", "function" ]
def __init__(self, config): """ init function """ self.margin = float(config["margin"])
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "self", ".", "margin", "=", "float", "(", "config", "[", "\"margin\"", "]", ")" ]
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/tf/losses/simnet_loss.py#L32-L36
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/photos/service.py
python
ConvertAtomTimestampToEpoch
(timestamp)
return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z'))
Helper function to convert a timestamp string, for instance from atom:updated or atom:published, to milliseconds since Unix epoch (a.k.a. POSIX time). `2007-07-22T00:45:10.000Z' ->
Helper function to convert a timestamp string, for instance from atom:updated or atom:published, to milliseconds since Unix epoch (a.k.a. POSIX time).
[ "Helper", "function", "to", "convert", "a", "timestamp", "string", "for", "instance", "from", "atom", ":", "updated", "or", "atom", ":", "published", "to", "milliseconds", "since", "Unix", "epoch", "(", "a", ".", "k", ".", "a", ".", "POSIX", "time", ")", "." ]
def ConvertAtomTimestampToEpoch(timestamp): """Helper function to convert a timestamp string, for instance from atom:updated or atom:published, to milliseconds since Unix epoch (a.k.a. POSIX time). `2007-07-22T00:45:10.000Z' -> """ return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z'))
[ "def", "ConvertAtomTimestampToEpoch", "(", "timestamp", ")", ":", "return", "time", ".", "mktime", "(", "time", ".", "strptime", "(", "timestamp", ",", "'%Y-%m-%dT%H:%M:%S.000Z'", ")", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/photos/service.py#L673-L679
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/optimize/_differentialevolution.py
python
DifferentialEvolutionSolver._ensure_constraint
(self, trial)
make sure the parameters lie between the limits
make sure the parameters lie between the limits
[ "make", "sure", "the", "parameters", "lie", "between", "the", "limits" ]
def _ensure_constraint(self, trial): """ make sure the parameters lie between the limits """ for index, param in enumerate(trial): if param > 1 or param < 0: trial[index] = self.random_number_generator.rand()
[ "def", "_ensure_constraint", "(", "self", ",", "trial", ")", ":", "for", "index", ",", "param", "in", "enumerate", "(", "trial", ")", ":", "if", "param", ">", "1", "or", "param", "<", "0", ":", "trial", "[", "index", "]", "=", "self", ".", "random_number_generator", ".", "rand", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/_differentialevolution.py#L682-L688
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py
python
StreamingDataFeeder.__init__
(self, x, y, n_classes, batch_size)
Initializes a StreamingDataFeeder instance. Args: x: iterator each element of which returns one feature sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices. y: iterator each element of which returns one label sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices with 1 or many classes regression values. n_classes: indicator of how many classes the corresponding label sample has for the purposes of one-hot conversion of label. In case where `y` is a dictionary, `n_classes` must be dictionary (with same keys as `y`) of how many classes there are in each label in `y`. If key is present in `y` and missing in `n_classes`, the value is assumed `None` and no one-hot conversion will be applied to the label with that key. batch_size: Mini batch size to accumulate samples in one batch. If set `None`, then assumes that iterator to return already batched element. Attributes: x: input features (or dictionary of input features). y: input label (or dictionary of output features). n_classes: number of classes. batch_size: mini batch size to accumulate. input_shape: shape of the input (can be dictionary depending on `x`). output_shape: shape of the output (can be dictionary depending on `y`). input_dtype: dtype of input (can be dictionary depending on `x`). output_dtype: dtype of output (can be dictionary depending on `y`).
Initializes a StreamingDataFeeder instance.
[ "Initializes", "a", "StreamingDataFeeder", "instance", "." ]
def __init__(self, x, y, n_classes, batch_size): """Initializes a StreamingDataFeeder instance. Args: x: iterator each element of which returns one feature sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices. y: iterator each element of which returns one label sample. Sample can be a Nd numpy matrix or dictionary of Nd numpy matrices with 1 or many classes regression values. n_classes: indicator of how many classes the corresponding label sample has for the purposes of one-hot conversion of label. In case where `y` is a dictionary, `n_classes` must be dictionary (with same keys as `y`) of how many classes there are in each label in `y`. If key is present in `y` and missing in `n_classes`, the value is assumed `None` and no one-hot conversion will be applied to the label with that key. batch_size: Mini batch size to accumulate samples in one batch. If set `None`, then assumes that iterator to return already batched element. Attributes: x: input features (or dictionary of input features). y: input label (or dictionary of output features). n_classes: number of classes. batch_size: mini batch size to accumulate. input_shape: shape of the input (can be dictionary depending on `x`). output_shape: shape of the output (can be dictionary depending on `y`). input_dtype: dtype of input (can be dictionary depending on `x`). output_dtype: dtype of output (can be dictionary depending on `y`). """ # pylint: disable=invalid-name,super-init-not-called x_first_el = six.next(x) self._x = itertools.chain([x_first_el], x) if y is not None: y_first_el = six.next(y) self._y = itertools.chain([y_first_el], y) else: y_first_el = None self._y = None self.n_classes = n_classes x_is_dict = isinstance(x_first_el, dict) y_is_dict = y is not None and isinstance(y_first_el, dict) if y_is_dict and n_classes is not None: assert isinstance(n_classes, dict) # extract shapes for first_elements if x_is_dict: x_first_el_shape = dict( [(k, [1] + list(v.shape)) for k, v in list(x_first_el.items())]) else: x_first_el_shape = [1] + list(x_first_el.shape) if y_is_dict: y_first_el_shape = dict( [(k, [1] + list(v.shape)) for k, v in list(y_first_el.items())]) elif y is None: y_first_el_shape = None else: y_first_el_shape = ([1] + list(y_first_el[0].shape if isinstance( y_first_el, list) else y_first_el.shape)) self.input_shape, self.output_shape, self._batch_size = _get_in_out_shape( x_first_el_shape, y_first_el_shape, n_classes, batch_size) # Input dtype of x_first_el. if x_is_dict: self._input_dtype = dict( [(k, _check_dtype(v.dtype)) for k, v in list(x_first_el.items())]) else: self._input_dtype = _check_dtype(x_first_el.dtype) # Output dtype of y_first_el. def check_y_dtype(el): if isinstance(el, np.ndarray): return el.dtype elif isinstance(el, list): return check_y_dtype(el[0]) else: return _check_dtype(np.dtype(type(el))) # Output types are floats, due to both softmaxes and regression req. if n_classes is not None and (y is None or not y_is_dict) and n_classes > 0: self._output_dtype = np.float32 elif y_is_dict: self._output_dtype = dict( [(k, check_y_dtype(v)) for k, v in list(y_first_el.items())]) elif y is None: self._output_dtype = None else: self._output_dtype = check_y_dtype(y_first_el)
[ "def", "__init__", "(", "self", ",", "x", ",", "y", ",", "n_classes", ",", "batch_size", ")", ":", "# pylint: disable=invalid-name,super-init-not-called", "x_first_el", "=", "six", ".", "next", "(", "x", ")", "self", ".", "_x", "=", "itertools", ".", "chain", "(", "[", "x_first_el", "]", ",", "x", ")", "if", "y", "is", "not", "None", ":", "y_first_el", "=", "six", ".", "next", "(", "y", ")", "self", ".", "_y", "=", "itertools", ".", "chain", "(", "[", "y_first_el", "]", ",", "y", ")", "else", ":", "y_first_el", "=", "None", "self", ".", "_y", "=", "None", "self", ".", "n_classes", "=", "n_classes", "x_is_dict", "=", "isinstance", "(", "x_first_el", ",", "dict", ")", "y_is_dict", "=", "y", "is", "not", "None", "and", "isinstance", "(", "y_first_el", ",", "dict", ")", "if", "y_is_dict", "and", "n_classes", "is", "not", "None", ":", "assert", "isinstance", "(", "n_classes", ",", "dict", ")", "# extract shapes for first_elements", "if", "x_is_dict", ":", "x_first_el_shape", "=", "dict", "(", "[", "(", "k", ",", "[", "1", "]", "+", "list", "(", "v", ".", "shape", ")", ")", "for", "k", ",", "v", "in", "list", "(", "x_first_el", ".", "items", "(", ")", ")", "]", ")", "else", ":", "x_first_el_shape", "=", "[", "1", "]", "+", "list", "(", "x_first_el", ".", "shape", ")", "if", "y_is_dict", ":", "y_first_el_shape", "=", "dict", "(", "[", "(", "k", ",", "[", "1", "]", "+", "list", "(", "v", ".", "shape", ")", ")", "for", "k", ",", "v", "in", "list", "(", "y_first_el", ".", "items", "(", ")", ")", "]", ")", "elif", "y", "is", "None", ":", "y_first_el_shape", "=", "None", "else", ":", "y_first_el_shape", "=", "(", "[", "1", "]", "+", "list", "(", "y_first_el", "[", "0", "]", ".", "shape", "if", "isinstance", "(", "y_first_el", ",", "list", ")", "else", "y_first_el", ".", "shape", ")", ")", "self", ".", "input_shape", ",", "self", ".", "output_shape", ",", "self", ".", "_batch_size", "=", "_get_in_out_shape", "(", "x_first_el_shape", ",", "y_first_el_shape", ",", "n_classes", ",", "batch_size", ")", "# Input dtype of x_first_el.", "if", "x_is_dict", ":", "self", ".", "_input_dtype", "=", "dict", "(", "[", "(", "k", ",", "_check_dtype", "(", "v", ".", "dtype", ")", ")", "for", "k", ",", "v", "in", "list", "(", "x_first_el", ".", "items", "(", ")", ")", "]", ")", "else", ":", "self", ".", "_input_dtype", "=", "_check_dtype", "(", "x_first_el", ".", "dtype", ")", "# Output dtype of y_first_el.", "def", "check_y_dtype", "(", "el", ")", ":", "if", "isinstance", "(", "el", ",", "np", ".", "ndarray", ")", ":", "return", "el", ".", "dtype", "elif", "isinstance", "(", "el", ",", "list", ")", ":", "return", "check_y_dtype", "(", "el", "[", "0", "]", ")", "else", ":", "return", "_check_dtype", "(", "np", ".", "dtype", "(", "type", "(", "el", ")", ")", ")", "# Output types are floats, due to both softmaxes and regression req.", "if", "n_classes", "is", "not", "None", "and", "(", "y", "is", "None", "or", "not", "y_is_dict", ")", "and", "n_classes", ">", "0", ":", "self", ".", "_output_dtype", "=", "np", ".", "float32", "elif", "y_is_dict", ":", "self", ".", "_output_dtype", "=", "dict", "(", "[", "(", "k", ",", "check_y_dtype", "(", "v", ")", ")", "for", "k", ",", "v", "in", "list", "(", "y_first_el", ".", "items", "(", ")", ")", "]", ")", "elif", "y", "is", "None", ":", "self", ".", "_output_dtype", "=", "None", "else", ":", "self", ".", "_output_dtype", "=", "check_y_dtype", "(", "y_first_el", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/learn_io/data_feeder.py#L561-L649
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
LayerNormBasicLSTMCell.__init__
(self, num_units, forget_bias=1.0, input_size=None, activation=math_ops.tanh, layer_norm=True, norm_gain=1.0, norm_shift=0.0, dropout_keep_prob=1.0, dropout_prob_seed=None, reuse=None)
Initializes the basic LSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (see above). input_size: Deprecated and unused. activation: Activation function of the inner states. layer_norm: If `True`, layer normalization will be applied. norm_gain: float, The layer normalization gain initial value. If `layer_norm` has been set to `False`, this argument will be ignored. norm_shift: float, The layer normalization shift initial value. If `layer_norm` has been set to `False`, this argument will be ignored. dropout_keep_prob: unit Tensor or float between 0 and 1 representing the recurrent dropout probability value. If float and 1.0, no dropout will be applied. dropout_prob_seed: (optional) integer, the randomness seed. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised.
Initializes the basic LSTM cell.
[ "Initializes", "the", "basic", "LSTM", "cell", "." ]
def __init__(self, num_units, forget_bias=1.0, input_size=None, activation=math_ops.tanh, layer_norm=True, norm_gain=1.0, norm_shift=0.0, dropout_keep_prob=1.0, dropout_prob_seed=None, reuse=None): """Initializes the basic LSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (see above). input_size: Deprecated and unused. activation: Activation function of the inner states. layer_norm: If `True`, layer normalization will be applied. norm_gain: float, The layer normalization gain initial value. If `layer_norm` has been set to `False`, this argument will be ignored. norm_shift: float, The layer normalization shift initial value. If `layer_norm` has been set to `False`, this argument will be ignored. dropout_keep_prob: unit Tensor or float between 0 and 1 representing the recurrent dropout probability value. If float and 1.0, no dropout will be applied. dropout_prob_seed: (optional) integer, the randomness seed. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. """ super(LayerNormBasicLSTMCell, self).__init__(_reuse=reuse) if input_size is not None: logging.warn("%s: The input_size parameter is deprecated.", self) self._num_units = num_units self._activation = activation self._forget_bias = forget_bias self._keep_prob = dropout_keep_prob self._seed = dropout_prob_seed self._layer_norm = layer_norm self._g = norm_gain self._b = norm_shift self._reuse = reuse
[ "def", "__init__", "(", "self", ",", "num_units", ",", "forget_bias", "=", "1.0", ",", "input_size", "=", "None", ",", "activation", "=", "math_ops", ".", "tanh", ",", "layer_norm", "=", "True", ",", "norm_gain", "=", "1.0", ",", "norm_shift", "=", "0.0", ",", "dropout_keep_prob", "=", "1.0", ",", "dropout_prob_seed", "=", "None", ",", "reuse", "=", "None", ")", ":", "super", "(", "LayerNormBasicLSTMCell", ",", "self", ")", ".", "__init__", "(", "_reuse", "=", "reuse", ")", "if", "input_size", "is", "not", "None", ":", "logging", ".", "warn", "(", "\"%s: The input_size parameter is deprecated.\"", ",", "self", ")", "self", ".", "_num_units", "=", "num_units", "self", ".", "_activation", "=", "activation", "self", ".", "_forget_bias", "=", "forget_bias", "self", ".", "_keep_prob", "=", "dropout_keep_prob", "self", ".", "_seed", "=", "dropout_prob_seed", "self", ".", "_layer_norm", "=", "layer_norm", "self", ".", "_g", "=", "norm_gain", "self", ".", "_b", "=", "norm_shift", "self", ".", "_reuse", "=", "reuse" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1257-L1295
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/schedule.py
python
Schedule.reshape
(self, target, shape)
Reshape a Tensor to a specified new shape Parameters ---------- target : Tensor The tensor to be reshaped shape : tuple of int The new shape of the tensor
Reshape a Tensor to a specified new shape
[ "Reshape", "a", "Tensor", "to", "a", "specified", "new", "shape" ]
def reshape(self, target, shape): """Reshape a Tensor to a specified new shape Parameters ---------- target : Tensor The tensor to be reshaped shape : tuple of int The new shape of the tensor """ try: target = target.tensor except (AttributeError, ValueError): try: target = target._op except AttributeError: pass _api_internal._ScheduleReshape(self.sch, target, shape)
[ "def", "reshape", "(", "self", ",", "target", ",", "shape", ")", ":", "try", ":", "target", "=", "target", ".", "tensor", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "try", ":", "target", "=", "target", ".", "_op", "except", "AttributeError", ":", "pass", "_api_internal", ".", "_ScheduleReshape", "(", "self", ".", "sch", ",", "target", ",", "shape", ")" ]
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/schedule.py#L654-L672
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/posixpath.py
python
ismount
(path)
return False
Test whether a path is a mount point
Test whether a path is a mount point
[ "Test", "whether", "a", "path", "is", "a", "mount", "point" ]
def ismount(path): """Test whether a path is a mount point""" try: s1 = os.lstat(path) except OSError: # It doesn't exist -- so not a mount point. :-) return False else: # A symlink can never be a mount point if stat.S_ISLNK(s1.st_mode): return False if isinstance(path, bytes): parent = join(path, b'..') else: parent = join(path, '..') parent = realpath(parent) try: s2 = os.lstat(parent) except OSError: return False dev1 = s1.st_dev dev2 = s2.st_dev if dev1 != dev2: return True # path/.. on a different device as path ino1 = s1.st_ino ino2 = s2.st_ino if ino1 == ino2: return True # path/.. is the same i-node as path return False
[ "def", "ismount", "(", "path", ")", ":", "try", ":", "s1", "=", "os", ".", "lstat", "(", "path", ")", "except", "OSError", ":", "# It doesn't exist -- so not a mount point. :-)", "return", "False", "else", ":", "# A symlink can never be a mount point", "if", "stat", ".", "S_ISLNK", "(", "s1", ".", "st_mode", ")", ":", "return", "False", "if", "isinstance", "(", "path", ",", "bytes", ")", ":", "parent", "=", "join", "(", "path", ",", "b'..'", ")", "else", ":", "parent", "=", "join", "(", "path", ",", "'..'", ")", "parent", "=", "realpath", "(", "parent", ")", "try", ":", "s2", "=", "os", ".", "lstat", "(", "parent", ")", "except", "OSError", ":", "return", "False", "dev1", "=", "s1", ".", "st_dev", "dev2", "=", "s2", ".", "st_dev", "if", "dev1", "!=", "dev2", ":", "return", "True", "# path/.. on a different device as path", "ino1", "=", "s1", ".", "st_ino", "ino2", "=", "s2", ".", "st_ino", "if", "ino1", "==", "ino2", ":", "return", "True", "# path/.. is the same i-node as path", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/posixpath.py#L190-L220
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
docs/nbdoc/nbdoc.py
python
NbProcessor.fetch_binder_list
(self, file_format: str = 'txt')
Funtion that fetches list of notebooks with binder buttons :param file_format: Format of file containing list of notebooks with button. Defaults to 'txt' :type file_format: str :return: List of notebooks conaining binder buttons :rtype: list
Funtion that fetches list of notebooks with binder buttons
[ "Funtion", "that", "fetches", "list", "of", "notebooks", "with", "binder", "buttons" ]
def fetch_binder_list(self, file_format: str = 'txt') -> list: """Funtion that fetches list of notebooks with binder buttons :param file_format: Format of file containing list of notebooks with button. Defaults to 'txt' :type file_format: str :return: List of notebooks conaining binder buttons :rtype: list """ list_of_buttons = glob(f"{self.nb_path}/*.{file_format}") if list_of_buttons: with open(list_of_buttons[0]) as file: list_of_buttons = file.read().splitlines() return list_of_buttons else: return []
[ "def", "fetch_binder_list", "(", "self", ",", "file_format", ":", "str", "=", "'txt'", ")", "->", "list", ":", "list_of_buttons", "=", "glob", "(", "f\"{self.nb_path}/*.{file_format}\"", ")", "if", "list_of_buttons", ":", "with", "open", "(", "list_of_buttons", "[", "0", "]", ")", "as", "file", ":", "list_of_buttons", "=", "file", ".", "read", "(", ")", ".", "splitlines", "(", ")", "return", "list_of_buttons", "else", ":", "return", "[", "]" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/docs/nbdoc/nbdoc.py#L101-L115
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/ide/activegrid/tool/SVNService.py
python
ReadSvnUrlList
()
return urlList
Read in list of SNV repository URLs. First in list is the last one path used.
Read in list of SNV repository URLs. First in list is the last one path used.
[ "Read", "in", "list", "of", "SNV", "repository", "URLs", ".", "First", "in", "list", "is", "the", "last", "one", "path", "used", "." ]
def ReadSvnUrlList(): """ Read in list of SNV repository URLs. First in list is the last one path used. """ config = wx.ConfigBase_Get() urlStringList = config.Read(SVN_REPOSITORY_URL) if len(urlStringList): urlList = eval(urlStringList) else: urlList = [] if len(urlList) == 0: svnService = wx.GetApp().GetService(SVNService) if svnService and hasattr(svnService, "_defaultURL"): urlList.append(svnService._defaultURL) return urlList
[ "def", "ReadSvnUrlList", "(", ")", ":", "config", "=", "wx", ".", "ConfigBase_Get", "(", ")", "urlStringList", "=", "config", ".", "Read", "(", "SVN_REPOSITORY_URL", ")", "if", "len", "(", "urlStringList", ")", ":", "urlList", "=", "eval", "(", "urlStringList", ")", "else", ":", "urlList", "=", "[", "]", "if", "len", "(", "urlList", ")", "==", "0", ":", "svnService", "=", "wx", ".", "GetApp", "(", ")", ".", "GetService", "(", "SVNService", ")", "if", "svnService", "and", "hasattr", "(", "svnService", ",", "\"_defaultURL\"", ")", ":", "urlList", ".", "append", "(", "svnService", ".", "_defaultURL", ")", "return", "urlList" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/ide/activegrid/tool/SVNService.py#L1039-L1051