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
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/appdirs.py
python
user_cache_dir
(appname=None, appauthor=None, version=None, opinion=True)
return path
r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option.
r"""Return full path to the user-specific cache dir for this application.
[ "r", "Return", "full", "path", "to", "the", "user", "-", "specific", "cache", "dir", "for", "this", "application", "." ]
def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): r"""Return full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be "<major>.<minor>". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: Mac OS X: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\<ProfileName>\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. """ if system == "win32": if appauthor is None: appauthor = appname path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) if appname: if appauthor is not False: path = os.path.join(path, appauthor, appname) else: path = os.path.join(path, appname) if opinion: path = os.path.join(path, "Cache") elif system == 'darwin': path = os.path.expanduser('~/Library/Caches') if appname: path = os.path.join(path, appname) else: path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) if appname: path = os.path.join(path, appname) if appname and version: path = os.path.join(path, version) return path
[ "def", "user_cache_dir", "(", "appname", "=", "None", ",", "appauthor", "=", "None", ",", "version", "=", "None", ",", "opinion", "=", "True", ")", ":", "if", "system", "==", "\"win32\"", ":", "if", "appauthor", "is", "None", ":", "appauthor", "=", "appname", "path", "=", "os", ".", "path", ".", "normpath", "(", "_get_win_folder", "(", "\"CSIDL_LOCAL_APPDATA\"", ")", ")", "if", "appname", ":", "if", "appauthor", "is", "not", "False", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appauthor", ",", "appname", ")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "if", "opinion", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"Cache\"", ")", "elif", "system", "==", "'darwin'", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/Library/Caches'", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "else", ":", "path", "=", "os", ".", "getenv", "(", "'XDG_CACHE_HOME'", ",", "os", ".", "path", ".", "expanduser", "(", "'~/.cache'", ")", ")", "if", "appname", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "appname", ")", "if", "appname", "and", "version", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "version", ")", "return", "path" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/appdirs.py#L257-L311
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py
python
ReplaceAll
(pattern, rep, s)
return _regexp_compile_cache[pattern].sub(rep, s)
Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements)
Replaces instances of pattern in a string with a replacement.
[ "Replaces", "instances", "of", "pattern", "in", "a", "string", "with", "a", "replacement", "." ]
def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s)
[ "def", "ReplaceAll", "(", "pattern", ",", "rep", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "sub", "(", "rep", ",", "s", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py#L798-L813
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBInstruction.DumpEmulation
(self, triple)
return _lldb.SBInstruction_DumpEmulation(self, triple)
DumpEmulation(SBInstruction self, char const * triple) -> bool
DumpEmulation(SBInstruction self, char const * triple) -> bool
[ "DumpEmulation", "(", "SBInstruction", "self", "char", "const", "*", "triple", ")", "-", ">", "bool" ]
def DumpEmulation(self, triple): """DumpEmulation(SBInstruction self, char const * triple) -> bool""" return _lldb.SBInstruction_DumpEmulation(self, triple)
[ "def", "DumpEmulation", "(", "self", ",", "triple", ")", ":", "return", "_lldb", ".", "SBInstruction_DumpEmulation", "(", "self", ",", "triple", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L6233-L6235
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
AuiNotebook.GetImageList
(self)
return self._imageList
Returns the associated image list (if any).
Returns the associated image list (if any).
[ "Returns", "the", "associated", "image", "list", "(", "if", "any", ")", "." ]
def GetImageList(self): """ Returns the associated image list (if any). """ return self._imageList
[ "def", "GetImageList", "(", "self", ")", ":", "return", "self", ".", "_imageList" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L3719-L3722
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/parse-lisp-expression.py
python
Solution.evaluate
(self, expression)
return int(tokens[0])
:type expression: str :rtype: int
:type expression: str :rtype: int
[ ":", "type", "expression", ":", "str", ":", "rtype", ":", "int" ]
def evaluate(self, expression): """ :type expression: str :rtype: int """ def getval(lookup, x): return lookup.get(x, x) def evaluate(tokens, lookup): if tokens[0] in ('add', 'mult'): a, b = map(int, map(lambda x: getval(lookup, x), tokens[1:])) return str(a+b if tokens[0] == 'add' else a*b) for i in xrange(1, len(tokens)-1, 2): if tokens[i+1]: lookup[tokens[i]] = getval(lookup, tokens[i+1]) return getval(lookup, tokens[-1]) tokens, lookup, stk = [''], {}, [] for c in expression: if c == '(': if tokens[0] == 'let': evaluate(tokens, lookup) stk.append((tokens, dict(lookup))) tokens = [''] elif c == ' ': tokens.append('') elif c == ')': val = evaluate(tokens, lookup) tokens, lookup = stk.pop() tokens[-1] += val else: tokens[-1] += c return int(tokens[0])
[ "def", "evaluate", "(", "self", ",", "expression", ")", ":", "def", "getval", "(", "lookup", ",", "x", ")", ":", "return", "lookup", ".", "get", "(", "x", ",", "x", ")", "def", "evaluate", "(", "tokens", ",", "lookup", ")", ":", "if", "tokens", "[", "0", "]", "in", "(", "'add'", ",", "'mult'", ")", ":", "a", ",", "b", "=", "map", "(", "int", ",", "map", "(", "lambda", "x", ":", "getval", "(", "lookup", ",", "x", ")", ",", "tokens", "[", "1", ":", "]", ")", ")", "return", "str", "(", "a", "+", "b", "if", "tokens", "[", "0", "]", "==", "'add'", "else", "a", "*", "b", ")", "for", "i", "in", "xrange", "(", "1", ",", "len", "(", "tokens", ")", "-", "1", ",", "2", ")", ":", "if", "tokens", "[", "i", "+", "1", "]", ":", "lookup", "[", "tokens", "[", "i", "]", "]", "=", "getval", "(", "lookup", ",", "tokens", "[", "i", "+", "1", "]", ")", "return", "getval", "(", "lookup", ",", "tokens", "[", "-", "1", "]", ")", "tokens", ",", "lookup", ",", "stk", "=", "[", "''", "]", ",", "{", "}", ",", "[", "]", "for", "c", "in", "expression", ":", "if", "c", "==", "'('", ":", "if", "tokens", "[", "0", "]", "==", "'let'", ":", "evaluate", "(", "tokens", ",", "lookup", ")", "stk", ".", "append", "(", "(", "tokens", ",", "dict", "(", "lookup", ")", ")", ")", "tokens", "=", "[", "''", "]", "elif", "c", "==", "' '", ":", "tokens", ".", "append", "(", "''", ")", "elif", "c", "==", "')'", ":", "val", "=", "evaluate", "(", "tokens", ",", "lookup", ")", "tokens", ",", "lookup", "=", "stk", ".", "pop", "(", ")", "tokens", "[", "-", "1", "]", "+=", "val", "else", ":", "tokens", "[", "-", "1", "]", "+=", "c", "return", "int", "(", "tokens", "[", "0", "]", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/parse-lisp-expression.py#L5-L37
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.ComputeExportEnvString
(self, env)
return ' '.join(export_str)
Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.
Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.
[ "Given", "an", "environment", "returns", "a", "string", "looking", "like", "export", "FOO", "=", "foo", ";", "export", "BAR", "=", "$", "{", "FOO", "}", "bar", ";", "that", "exports", "|env|", "to", "the", "shell", "." ]
def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append('export %s=%s;' % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))) return ' '.join(export_str)
[ "def", "ComputeExportEnvString", "(", "self", ",", "env", ")", ":", "export_str", "=", "[", "]", "for", "k", ",", "v", "in", "env", ":", "export_str", ".", "append", "(", "'export %s=%s;'", "%", "(", "k", ",", "ninja_syntax", ".", "escape", "(", "gyp", ".", "common", ".", "EncodePOSIXShellArgument", "(", "v", ")", ")", ")", ")", "return", "' '", ".", "join", "(", "export_str", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/generator/ninja.py#L1472-L1480
facebookresearch/habitat-sim
63b6c71d9ca8adaefb140b198196f5d0ca1f1e34
src_python/habitat_sim/robots/robot_interface.py
python
RobotInterface.get_link_and_joint_names
(self)
return link_joint_names
Get a string listing all robot link and joint names for debugging purposes.
Get a string listing all robot link and joint names for debugging purposes.
[ "Get", "a", "string", "listing", "all", "robot", "link", "and", "joint", "names", "for", "debugging", "purposes", "." ]
def get_link_and_joint_names(self) -> str: """Get a string listing all robot link and joint names for debugging purposes.""" link_joint_names = "" # print relevant joint/link info for debugging for link_id in self.sim_obj.get_link_ids(): link_joint_names += f"{link_id} = {self.sim_obj.get_link_name(link_id)} | {self.sim_obj.get_link_joint_name(link_id)} :: type = {self.sim_obj.get_link_joint_type(link_id)} \n" return link_joint_names
[ "def", "get_link_and_joint_names", "(", "self", ")", "->", "str", ":", "link_joint_names", "=", "\"\"", "# print relevant joint/link info for debugging", "for", "link_id", "in", "self", ".", "sim_obj", ".", "get_link_ids", "(", ")", ":", "link_joint_names", "+=", "f\"{link_id} = {self.sim_obj.get_link_name(link_id)} | {self.sim_obj.get_link_joint_name(link_id)} :: type = {self.sim_obj.get_link_joint_type(link_id)} \\n\"", "return", "link_joint_names" ]
https://github.com/facebookresearch/habitat-sim/blob/63b6c71d9ca8adaefb140b198196f5d0ca1f1e34/src_python/habitat_sim/robots/robot_interface.py#L30-L36
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/compat/chainmap_impl.py
python
recursive_repr
(fillvalue='...')
return decorating_function
Decorator to make a repr function return fillvalue for a recursive call
Decorator to make a repr function return fillvalue for a recursive call
[ "Decorator", "to", "make", "a", "repr", "function", "return", "fillvalue", "for", "a", "recursive", "call" ]
def recursive_repr(fillvalue='...'): 'Decorator to make a repr function return fillvalue for a recursive call' def decorating_function(user_function): repr_running = set() def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result # Can't use functools.wraps() here because of bootstrap issues wrapper.__module__ = getattr(user_function, '__module__') wrapper.__doc__ = getattr(user_function, '__doc__') wrapper.__name__ = getattr(user_function, '__name__') return wrapper return decorating_function
[ "def", "recursive_repr", "(", "fillvalue", "=", "'...'", ")", ":", "def", "decorating_function", "(", "user_function", ")", ":", "repr_running", "=", "set", "(", ")", "def", "wrapper", "(", "self", ")", ":", "key", "=", "id", "(", "self", ")", ",", "get_ident", "(", ")", "if", "key", "in", "repr_running", ":", "return", "fillvalue", "repr_running", ".", "add", "(", "key", ")", "try", ":", "result", "=", "user_function", "(", "self", ")", "finally", ":", "repr_running", ".", "discard", "(", "key", ")", "return", "result", "# Can't use functools.wraps() here because of bootstrap issues", "wrapper", ".", "__module__", "=", "getattr", "(", "user_function", ",", "'__module__'", ")", "wrapper", ".", "__doc__", "=", "getattr", "(", "user_function", ",", "'__doc__'", ")", "wrapper", ".", "__name__", "=", "getattr", "(", "user_function", ",", "'__name__'", ")", "return", "wrapper", "return", "decorating_function" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/compat/chainmap_impl.py#L16-L39
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
SplashScreen.__init__
(self, *args, **kwargs)
__init__(self, Bitmap bitmap, long splashStyle, int milliseconds, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxSIMPLE_BORDER|wxFRAME_NO_TASKBAR|wxSTAY_ON_TOP) -> SplashScreen
__init__(self, Bitmap bitmap, long splashStyle, int milliseconds, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxSIMPLE_BORDER|wxFRAME_NO_TASKBAR|wxSTAY_ON_TOP) -> SplashScreen
[ "__init__", "(", "self", "Bitmap", "bitmap", "long", "splashStyle", "int", "milliseconds", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "wxSIMPLE_BORDER|wxFRAME_NO_TASKBAR|wxSTAY_ON_TOP", ")", "-", ">", "SplashScreen" ]
def __init__(self, *args, **kwargs): """ __init__(self, Bitmap bitmap, long splashStyle, int milliseconds, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxSIMPLE_BORDER|wxFRAME_NO_TASKBAR|wxSTAY_ON_TOP) -> SplashScreen """ _windows_.SplashScreen_swiginit(self,_windows_.new_SplashScreen(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_windows_", ".", "SplashScreen_swiginit", "(", "self", ",", "_windows_", ".", "new_SplashScreen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L1136-L1143
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/pdftex.py
python
PDFTeXLaTeXFunction
(target = None, source= None, env=None)
return result
A builder for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then executes the appropriate program.
A builder for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then executes the appropriate program.
[ "A", "builder", "for", "TeX", "and", "LaTeX", "that", "scans", "the", "source", "file", "to", "decide", "the", "flavor", "of", "the", "source", "and", "then", "executes", "the", "appropriate", "program", "." ]
def PDFTeXLaTeXFunction(target = None, source= None, env=None): """A builder for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then executes the appropriate program.""" basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) if SCons.Tool.tex.is_LaTeX(source,env,abspath): result = PDFLaTeXAuxAction(target,source,env) if result != 0: SCons.Tool.tex.check_file_error_message(env['PDFLATEX']) else: result = PDFTeXAction(target,source,env) if result != 0: SCons.Tool.tex.check_file_error_message(env['PDFTEX']) return result
[ "def", "PDFTeXLaTeXFunction", "(", "target", "=", "None", ",", "source", "=", "None", ",", "env", "=", "None", ")", ":", "basedir", "=", "os", ".", "path", ".", "split", "(", "str", "(", "source", "[", "0", "]", ")", ")", "[", "0", "]", "abspath", "=", "os", ".", "path", ".", "abspath", "(", "basedir", ")", "if", "SCons", ".", "Tool", ".", "tex", ".", "is_LaTeX", "(", "source", ",", "env", ",", "abspath", ")", ":", "result", "=", "PDFLaTeXAuxAction", "(", "target", ",", "source", ",", "env", ")", "if", "result", "!=", "0", ":", "SCons", ".", "Tool", ".", "tex", ".", "check_file_error_message", "(", "env", "[", "'PDFLATEX'", "]", ")", "else", ":", "result", "=", "PDFTeXAction", "(", "target", ",", "source", ",", "env", ")", "if", "result", "!=", "0", ":", "SCons", ".", "Tool", ".", "tex", ".", "check_file_error_message", "(", "env", "[", "'PDFTEX'", "]", ")", "return", "result" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/pdftex.py#L52-L67
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/imaplib.py
python
Time2Internaldate
(date_time)
return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"'
Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
Convert 'date_time' to IMAP4 INTERNALDATE representation.
[ "Convert", "date_time", "to", "IMAP4", "INTERNALDATE", "representation", "." ]
def Time2Internaldate(date_time): """Convert 'date_time' to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"' """ if isinstance(date_time, (int, float)): tt = time.localtime(date_time) elif isinstance(date_time, (tuple, time.struct_time)): tt = date_time elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'): return date_time # Assume in correct format else: raise ValueError("date_time not of a known type") dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"'
[ "def", "Time2Internaldate", "(", "date_time", ")", ":", "if", "isinstance", "(", "date_time", ",", "(", "int", ",", "float", ")", ")", ":", "tt", "=", "time", ".", "localtime", "(", "date_time", ")", "elif", "isinstance", "(", "date_time", ",", "(", "tuple", ",", "time", ".", "struct_time", ")", ")", ":", "tt", "=", "date_time", "elif", "isinstance", "(", "date_time", ",", "str", ")", "and", "(", "date_time", "[", "0", "]", ",", "date_time", "[", "-", "1", "]", ")", "==", "(", "'\"'", ",", "'\"'", ")", ":", "return", "date_time", "# Assume in correct format", "else", ":", "raise", "ValueError", "(", "\"date_time not of a known type\"", ")", "dt", "=", "time", ".", "strftime", "(", "\"%d-%b-%Y %H:%M:%S\"", ",", "tt", ")", "if", "dt", "[", "0", "]", "==", "'0'", ":", "dt", "=", "' '", "+", "dt", "[", "1", ":", "]", "if", "time", ".", "daylight", "and", "tt", "[", "-", "1", "]", ":", "zone", "=", "-", "time", ".", "altzone", "else", ":", "zone", "=", "-", "time", ".", "timezone", "return", "'\"'", "+", "dt", "+", "\" %+03d%02d\"", "%", "divmod", "(", "zone", "//", "60", ",", "60", ")", "+", "'\"'" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/imaplib.py#L1381-L1404
tensorflow/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
deepmath/deephol/io_util.py
python
options_reader
(options_proto, options_proto_path: Text, overwrite: Optional[Text])
return ret
Generic options reader, which can also be easily saved as protos. Arguments: options_proto: Type of the options proto object. options_proto_path: Path to file containing an options_proto. overwrite: A string containing options proto object. Returns: An options_proto proto containing parsed options.
Generic options reader, which can also be easily saved as protos.
[ "Generic", "options", "reader", "which", "can", "also", "be", "easily", "saved", "as", "protos", "." ]
def options_reader(options_proto, options_proto_path: Text, overwrite: Optional[Text]): """Generic options reader, which can also be easily saved as protos. Arguments: options_proto: Type of the options proto object. options_proto_path: Path to file containing an options_proto. overwrite: A string containing options proto object. Returns: An options_proto proto containing parsed options. """ ret = load_text_proto(options_proto_path, options_proto) if overwrite: text_format.Merge(overwrite, ret) tf.logging.info('Options:\n\n%s\n\n', ret) return ret
[ "def", "options_reader", "(", "options_proto", ",", "options_proto_path", ":", "Text", ",", "overwrite", ":", "Optional", "[", "Text", "]", ")", ":", "ret", "=", "load_text_proto", "(", "options_proto_path", ",", "options_proto", ")", "if", "overwrite", ":", "text_format", ".", "Merge", "(", "overwrite", ",", "ret", ")", "tf", ".", "logging", ".", "info", "(", "'Options:\\n\\n%s\\n\\n'", ",", "ret", ")", "return", "ret" ]
https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/io_util.py#L199-L215
yun-liu/RCF
91bfb054ad04187dbbe21e539e165ad9bd3ff00b
scripts/cpp_lint.py
python
_OutputFormat
()
return _cpplint_state.output_format
Gets the module's output format.
Gets the module's output format.
[ "Gets", "the", "module", "s", "output", "format", "." ]
def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format
[ "def", "_OutputFormat", "(", ")", ":", "return", "_cpplint_state", ".", "output_format" ]
https://github.com/yun-liu/RCF/blob/91bfb054ad04187dbbe21e539e165ad9bd3ff00b/scripts/cpp_lint.py#L767-L769
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlWindow.SetPage
(*args, **kwargs)
return _html.HtmlWindow_SetPage(*args, **kwargs)
SetPage(self, String source) -> bool
SetPage(self, String source) -> bool
[ "SetPage", "(", "self", "String", "source", ")", "-", ">", "bool" ]
def SetPage(*args, **kwargs): """SetPage(self, String source) -> bool""" return _html.HtmlWindow_SetPage(*args, **kwargs)
[ "def", "SetPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlWindow_SetPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L986-L988
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PolDiffILLReduction.py
python
PolDiffILLReduction._apply_polarisation_corrections
(self, ws, pol_eff_ws)
return ws
Applies the polarisation correction based on the output from quartz reduction.
Applies the polarisation correction based on the output from quartz reduction.
[ "Applies", "the", "polarisation", "correction", "based", "on", "the", "output", "from", "quartz", "reduction", "." ]
def _apply_polarisation_corrections(self, ws, pol_eff_ws): """Applies the polarisation correction based on the output from quartz reduction.""" nPolarisations = None singleCorrectionPerPOL = False if mtd[ws].getNumberOfEntries() != 2*mtd[pol_eff_ws].getNumberOfEntries(): singleCorrectionPerPOL = True nMeasurements = self._data_structure_helper() nPolarisations = math.floor(nMeasurements / 2.0) if mtd[pol_eff_ws].getNumberOfEntries() != nPolarisations: raise RuntimeError("Incompatible number of polarisations between quartz input and sample.") CreateSingleValuedWorkspace(DataValue=1.0, OutputWorkspace='unity') CreateSingleValuedWorkspace(DataValue=2.0, OutputWorkspace='double_fp') to_clean = ['unity', 'double_fp'] for entry_no in range(mtd[ws].getNumberOfEntries()): if entry_no % 2 != 0: continue polarisation_entry_no = int(entry_no/2) if singleCorrectionPerPOL: polarisation_entry_no = int(polarisation_entry_no % nPolarisations) phi = mtd[pol_eff_ws][polarisation_entry_no].name() intensity_0 = mtd[ws][entry_no].name() intensity_1 = mtd[ws][entry_no+1].name() tmp_names = [intensity_0 + '_tmp', intensity_1 + '_tmp'] # helper ws Minus(LHSWorkspace='unity', RHSWorkspace=phi, Outputworkspace='one_m_pol') Plus(LHSWorkspace='unity', RHSWorkspace=phi, Outputworkspace='one_p_pol') # spin-flip: Multiply(LHSWorkspace=intensity_0, RHSWorkspace='one_p_pol', OutputWorkspace='lhs_nominator') Multiply(LHSWorkspace=intensity_1, RHSWorkspace='one_m_pol', OutputWorkspace='rhs_nominator') Minus(LHSWorkspace='lhs_nominator', RHSWorkspace='rhs_nominator', OutputWorkspace='nominator') Multiply(LHSWorkspace=phi, RHSWorkspace='double_fp', OutputWorkspace='denominator') Divide(LHSWorkspace='nominator', RHSWorkspace='denominator', OutputWorkspace=tmp_names[0]) # non-spin-flip: Multiply(LHSWorkspace=intensity_0, RHSWorkspace='one_m_pol', OutputWorkspace='lhs_nominator') Multiply(LHSWorkspace=intensity_1, RHSWorkspace='one_p_pol', OutputWorkspace='rhs_nominator') Minus(LHSWorkspace='rhs_nominator', RHSWorkspace='lhs_nominator', OutputWorkspace='nominator') Divide(LHSWorkspace='nominator', RHSWorkspace='denominator', OutputWorkspace=tmp_names[1]) RenameWorkspace(tmp_names[0], intensity_0) RenameWorkspace(tmp_names[1], intensity_1) to_clean += ['one_m_pol', 'one_p_pol', 'lhs_nominator', 'rhs_nominator', 'nominator', 'denominator'] DeleteWorkspaces(WorkspaceList=to_clean) if self._debug: clone_name = '{}_pol_corrected'.format(ws) CloneWorkspace(InputWorkspace=ws, OutputWorkspace=clone_name) return ws
[ "def", "_apply_polarisation_corrections", "(", "self", ",", "ws", ",", "pol_eff_ws", ")", ":", "nPolarisations", "=", "None", "singleCorrectionPerPOL", "=", "False", "if", "mtd", "[", "ws", "]", ".", "getNumberOfEntries", "(", ")", "!=", "2", "*", "mtd", "[", "pol_eff_ws", "]", ".", "getNumberOfEntries", "(", ")", ":", "singleCorrectionPerPOL", "=", "True", "nMeasurements", "=", "self", ".", "_data_structure_helper", "(", ")", "nPolarisations", "=", "math", ".", "floor", "(", "nMeasurements", "/", "2.0", ")", "if", "mtd", "[", "pol_eff_ws", "]", ".", "getNumberOfEntries", "(", ")", "!=", "nPolarisations", ":", "raise", "RuntimeError", "(", "\"Incompatible number of polarisations between quartz input and sample.\"", ")", "CreateSingleValuedWorkspace", "(", "DataValue", "=", "1.0", ",", "OutputWorkspace", "=", "'unity'", ")", "CreateSingleValuedWorkspace", "(", "DataValue", "=", "2.0", ",", "OutputWorkspace", "=", "'double_fp'", ")", "to_clean", "=", "[", "'unity'", ",", "'double_fp'", "]", "for", "entry_no", "in", "range", "(", "mtd", "[", "ws", "]", ".", "getNumberOfEntries", "(", ")", ")", ":", "if", "entry_no", "%", "2", "!=", "0", ":", "continue", "polarisation_entry_no", "=", "int", "(", "entry_no", "/", "2", ")", "if", "singleCorrectionPerPOL", ":", "polarisation_entry_no", "=", "int", "(", "polarisation_entry_no", "%", "nPolarisations", ")", "phi", "=", "mtd", "[", "pol_eff_ws", "]", "[", "polarisation_entry_no", "]", ".", "name", "(", ")", "intensity_0", "=", "mtd", "[", "ws", "]", "[", "entry_no", "]", ".", "name", "(", ")", "intensity_1", "=", "mtd", "[", "ws", "]", "[", "entry_no", "+", "1", "]", ".", "name", "(", ")", "tmp_names", "=", "[", "intensity_0", "+", "'_tmp'", ",", "intensity_1", "+", "'_tmp'", "]", "# helper ws", "Minus", "(", "LHSWorkspace", "=", "'unity'", ",", "RHSWorkspace", "=", "phi", ",", "Outputworkspace", "=", "'one_m_pol'", ")", "Plus", "(", "LHSWorkspace", "=", "'unity'", ",", "RHSWorkspace", "=", "phi", ",", "Outputworkspace", "=", "'one_p_pol'", ")", "# spin-flip:", "Multiply", "(", "LHSWorkspace", "=", "intensity_0", ",", "RHSWorkspace", "=", "'one_p_pol'", ",", "OutputWorkspace", "=", "'lhs_nominator'", ")", "Multiply", "(", "LHSWorkspace", "=", "intensity_1", ",", "RHSWorkspace", "=", "'one_m_pol'", ",", "OutputWorkspace", "=", "'rhs_nominator'", ")", "Minus", "(", "LHSWorkspace", "=", "'lhs_nominator'", ",", "RHSWorkspace", "=", "'rhs_nominator'", ",", "OutputWorkspace", "=", "'nominator'", ")", "Multiply", "(", "LHSWorkspace", "=", "phi", ",", "RHSWorkspace", "=", "'double_fp'", ",", "OutputWorkspace", "=", "'denominator'", ")", "Divide", "(", "LHSWorkspace", "=", "'nominator'", ",", "RHSWorkspace", "=", "'denominator'", ",", "OutputWorkspace", "=", "tmp_names", "[", "0", "]", ")", "# non-spin-flip:", "Multiply", "(", "LHSWorkspace", "=", "intensity_0", ",", "RHSWorkspace", "=", "'one_m_pol'", ",", "OutputWorkspace", "=", "'lhs_nominator'", ")", "Multiply", "(", "LHSWorkspace", "=", "intensity_1", ",", "RHSWorkspace", "=", "'one_p_pol'", ",", "OutputWorkspace", "=", "'rhs_nominator'", ")", "Minus", "(", "LHSWorkspace", "=", "'rhs_nominator'", ",", "RHSWorkspace", "=", "'lhs_nominator'", ",", "OutputWorkspace", "=", "'nominator'", ")", "Divide", "(", "LHSWorkspace", "=", "'nominator'", ",", "RHSWorkspace", "=", "'denominator'", ",", "OutputWorkspace", "=", "tmp_names", "[", "1", "]", ")", "RenameWorkspace", "(", "tmp_names", "[", "0", "]", ",", "intensity_0", ")", "RenameWorkspace", "(", "tmp_names", "[", "1", "]", ",", "intensity_1", ")", "to_clean", "+=", "[", "'one_m_pol'", ",", "'one_p_pol'", ",", "'lhs_nominator'", ",", "'rhs_nominator'", ",", "'nominator'", ",", "'denominator'", "]", "DeleteWorkspaces", "(", "WorkspaceList", "=", "to_clean", ")", "if", "self", ".", "_debug", ":", "clone_name", "=", "'{}_pol_corrected'", ".", "format", "(", "ws", ")", "CloneWorkspace", "(", "InputWorkspace", "=", "ws", ",", "OutputWorkspace", "=", "clone_name", ")", "return", "ws" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PolDiffILLReduction.py#L1031-L1078
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/character/character_module.py
python
Trait.preferred_discount_multiplier
(self, alternatives)
return None
Select a discount multiplier from the alternatives provided for use in evaluate planet in Colonisation.py to scale pilot rating and a long list of technologies.
Select a discount multiplier from the alternatives provided for use in evaluate planet in Colonisation.py to scale pilot rating and a long list of technologies.
[ "Select", "a", "discount", "multiplier", "from", "the", "alternatives", "provided", "for", "use", "in", "evaluate", "planet", "in", "Colonisation", ".", "py", "to", "scale", "pilot", "rating", "and", "a", "long", "list", "of", "technologies", "." ]
def preferred_discount_multiplier(self, alternatives): # pylint: disable=no-self-use,unused-argument """Select a discount multiplier from the alternatives provided for use in evaluate planet in Colonisation.py to scale pilot rating and a long list of technologies. """ # TODO Remove this tap it is one of the empire id dependent taps. See EmpireIDTrait. return None
[ "def", "preferred_discount_multiplier", "(", "self", ",", "alternatives", ")", ":", "# pylint: disable=no-self-use,unused-argument", "# TODO Remove this tap it is one of the empire id dependent taps. See EmpireIDTrait.", "return", "None" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/character/character_module.py#L194-L200
genn-team/genn
75e1eb218cafa228bf36ae4613d1ce26e877b12c
pygenn/genn_model.py
python
GeNNModel.pull_connectivity_from_device
(self, pop_name)
Pull connectivity from the device for a given population
Pull connectivity from the device for a given population
[ "Pull", "connectivity", "from", "the", "device", "for", "a", "given", "population" ]
def pull_connectivity_from_device(self, pop_name): """Pull connectivity from the device for a given population""" if not self._loaded: raise Exception("GeNN model has to be loaded before pulling") self._slm.pull_connectivity_from_device(pop_name)
[ "def", "pull_connectivity_from_device", "(", "self", ",", "pop_name", ")", ":", "if", "not", "self", ".", "_loaded", ":", "raise", "Exception", "(", "\"GeNN model has to be loaded before pulling\"", ")", "self", ".", "_slm", ".", "pull_connectivity_from_device", "(", "pop_name", ")" ]
https://github.com/genn-team/genn/blob/75e1eb218cafa228bf36ae4613d1ce26e877b12c/pygenn/genn_model.py#L741-L746
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/grit/grit/scons.py
python
_ProcessNodes
(grd, base_dir, lang_folders)
return (structure_outputs, translated_files, static_files)
Processes the GRD nodes to figure out file dependencies. Args: grd: An open GRD reader. base_dir: The base directory for filenames. lang_folders: THe output language folders. Returns: A tuple of (structure_outputs, translated_files, static_files): structure_outputs: Structures marked as sconsdep. translated_files: Files that are structures or skeletons, and get translated by GRIT. static_files: Files that are includes, and are used directly by res files.
Processes the GRD nodes to figure out file dependencies.
[ "Processes", "the", "GRD", "nodes", "to", "figure", "out", "file", "dependencies", "." ]
def _ProcessNodes(grd, base_dir, lang_folders): """Processes the GRD nodes to figure out file dependencies. Args: grd: An open GRD reader. base_dir: The base directory for filenames. lang_folders: THe output language folders. Returns: A tuple of (structure_outputs, translated_files, static_files): structure_outputs: Structures marked as sconsdep. translated_files: Files that are structures or skeletons, and get translated by GRIT. static_files: Files that are includes, and are used directly by res files. """ structure_outputs = [] translated_files = [] static_files = [] # Go through nodes, figuring out resources. Also output certain resources # as build targets, based on the sconsdep flag. for node in grd.ActiveDescendants(): with node: file = node.ToRealPath(node.GetInputPath()) if node.name == 'structure': translated_files.append(os.path.abspath(file)) # TODO(joi) Should remove the "if sconsdep is true" thing as it is a # hack - see grit/node/structure.py if node.HasFileForLanguage() and node.attrs['sconsdep'] == 'true': for lang in lang_folders: path = node.FileForLanguage(lang, lang_folders[lang], create_file=False, return_if_not_generated=False) if path: structure_outputs.append(path) if _IsDebugEnabled(): print 'GRIT: Added target %s' % path elif (node.name == 'skeleton' or (node.name == 'file' and node.parent and node.parent.name == 'translations')): translated_files.append(os.path.abspath(file)) elif node.name == 'include': # If it's added by file name and the file isn't easy to find, don't make # it a dependency. This could add some build flakiness, but it doesn't # work otherwise. if node.attrs['filenameonly'] != 'true' or os.path.exists(file): static_files.append(os.path.abspath(file)) # If it's output from mk, look in the output directory. elif node.attrs['mkoutput'] == 'true': static_files.append(os.path.join(base_dir, os.path.basename(file))) return (structure_outputs, translated_files, static_files)
[ "def", "_ProcessNodes", "(", "grd", ",", "base_dir", ",", "lang_folders", ")", ":", "structure_outputs", "=", "[", "]", "translated_files", "=", "[", "]", "static_files", "=", "[", "]", "# Go through nodes, figuring out resources. Also output certain resources", "# as build targets, based on the sconsdep flag.", "for", "node", "in", "grd", ".", "ActiveDescendants", "(", ")", ":", "with", "node", ":", "file", "=", "node", ".", "ToRealPath", "(", "node", ".", "GetInputPath", "(", ")", ")", "if", "node", ".", "name", "==", "'structure'", ":", "translated_files", ".", "append", "(", "os", ".", "path", ".", "abspath", "(", "file", ")", ")", "# TODO(joi) Should remove the \"if sconsdep is true\" thing as it is a", "# hack - see grit/node/structure.py", "if", "node", ".", "HasFileForLanguage", "(", ")", "and", "node", ".", "attrs", "[", "'sconsdep'", "]", "==", "'true'", ":", "for", "lang", "in", "lang_folders", ":", "path", "=", "node", ".", "FileForLanguage", "(", "lang", ",", "lang_folders", "[", "lang", "]", ",", "create_file", "=", "False", ",", "return_if_not_generated", "=", "False", ")", "if", "path", ":", "structure_outputs", ".", "append", "(", "path", ")", "if", "_IsDebugEnabled", "(", ")", ":", "print", "'GRIT: Added target %s'", "%", "path", "elif", "(", "node", ".", "name", "==", "'skeleton'", "or", "(", "node", ".", "name", "==", "'file'", "and", "node", ".", "parent", "and", "node", ".", "parent", ".", "name", "==", "'translations'", ")", ")", ":", "translated_files", ".", "append", "(", "os", ".", "path", ".", "abspath", "(", "file", ")", ")", "elif", "node", ".", "name", "==", "'include'", ":", "# If it's added by file name and the file isn't easy to find, don't make", "# it a dependency. This could add some build flakiness, but it doesn't", "# work otherwise.", "if", "node", ".", "attrs", "[", "'filenameonly'", "]", "!=", "'true'", "or", "os", ".", "path", ".", "exists", "(", "file", ")", ":", "static_files", ".", "append", "(", "os", ".", "path", ".", "abspath", "(", "file", ")", ")", "# If it's output from mk, look in the output directory.", "elif", "node", ".", "attrs", "[", "'mkoutput'", "]", "==", "'true'", ":", "static_files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "os", ".", "path", ".", "basename", "(", "file", ")", ")", ")", "return", "(", "structure_outputs", ",", "translated_files", ",", "static_files", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/grit/grit/scons.py#L116-L166
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/msgpack/ext.py
python
Timestamp.to_datetime
(self)
return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta( seconds=self.to_unix() )
Get the timestamp as a UTC datetime. Python 2 is not supported. :rtype: datetime.
Get the timestamp as a UTC datetime.
[ "Get", "the", "timestamp", "as", "a", "UTC", "datetime", "." ]
def to_datetime(self): """Get the timestamp as a UTC datetime. Python 2 is not supported. :rtype: datetime. """ return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta( seconds=self.to_unix() )
[ "def", "to_datetime", "(", "self", ")", ":", "return", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "0", ",", "_utc", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "self", ".", "to_unix", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/msgpack/ext.py#L347-L365
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPML_PCR_SELECTION.initFromTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def initFromTpm(self, buf): """ TpmMarshaller method """ self.pcrSelections = buf.readObjArr(TPMS_PCR_SELECTION)
[ "def", "initFromTpm", "(", "self", ",", "buf", ")", ":", "self", ".", "pcrSelections", "=", "buf", ".", "readObjArr", "(", "TPMS_PCR_SELECTION", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4680-L4682
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/saved_model/signature_serialization.py
python
create_signature_map
(signatures)
return signature_map
Creates an object containing `signatures`.
Creates an object containing `signatures`.
[ "Creates", "an", "object", "containing", "signatures", "." ]
def create_signature_map(signatures): """Creates an object containing `signatures`.""" signature_map = _SignatureMap() for name, func in signatures.items(): # This true of any signature that came from canonicalize_signatures. Here as # a sanity check on saving; crashing on load (e.g. in _add_signature) would # be more problematic in case future export changes violated these # assertions. assert isinstance(func, defun.ConcreteFunction) assert isinstance(func.structured_outputs, collections_abc.Mapping) # pylint: disable=protected-access if len(func._arg_keywords) == 1: assert 1 == func._num_positional_args else: assert 0 == func._num_positional_args signature_map._add_signature(name, func) # pylint: enable=protected-access return signature_map
[ "def", "create_signature_map", "(", "signatures", ")", ":", "signature_map", "=", "_SignatureMap", "(", ")", "for", "name", ",", "func", "in", "signatures", ".", "items", "(", ")", ":", "# This true of any signature that came from canonicalize_signatures. Here as", "# a sanity check on saving; crashing on load (e.g. in _add_signature) would", "# be more problematic in case future export changes violated these", "# assertions.", "assert", "isinstance", "(", "func", ",", "defun", ".", "ConcreteFunction", ")", "assert", "isinstance", "(", "func", ".", "structured_outputs", ",", "collections_abc", ".", "Mapping", ")", "# pylint: disable=protected-access", "if", "len", "(", "func", ".", "_arg_keywords", ")", "==", "1", ":", "assert", "1", "==", "func", ".", "_num_positional_args", "else", ":", "assert", "0", "==", "func", ".", "_num_positional_args", "signature_map", ".", "_add_signature", "(", "name", ",", "func", ")", "# pylint: enable=protected-access", "return", "signature_map" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/saved_model/signature_serialization.py#L282-L299
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/doc/pattern_tools/svgfig.py
python
template
(fileName, svg, replaceme="REPLACEME")
return output
Loads an SVG image from a file, replacing instances of <REPLACEME /> with a given svg object. fileName required name of the template SVG svg required SVG object for replacement replaceme default="REPLACEME" fake SVG element to be replaced by the given object >>> print load("template.svg") None <svg (2 sub) style=u'stroke:black; fill:none; stroke-width:0.5pt; stroke-linejoi [0] <rect height=u'100' width=u'100' stroke=u'none' y=u'0' x=u'0' fill=u'yellow' [1] <REPLACEME /> >>> >>> print template("template.svg", SVG("circle", cx=50, cy=50, r=30)) None <svg (2 sub) style=u'stroke:black; fill:none; stroke-width:0.5pt; stroke-linejoi [0] <rect height=u'100' width=u'100' stroke=u'none' y=u'0' x=u'0' fill=u'yellow' [1] <circle cy=50 cx=50 r=30 />
Loads an SVG image from a file, replacing instances of <REPLACEME /> with a given svg object.
[ "Loads", "an", "SVG", "image", "from", "a", "file", "replacing", "instances", "of", "<REPLACEME", "/", ">", "with", "a", "given", "svg", "object", "." ]
def template(fileName, svg, replaceme="REPLACEME"): """Loads an SVG image from a file, replacing instances of <REPLACEME /> with a given svg object. fileName required name of the template SVG svg required SVG object for replacement replaceme default="REPLACEME" fake SVG element to be replaced by the given object >>> print load("template.svg") None <svg (2 sub) style=u'stroke:black; fill:none; stroke-width:0.5pt; stroke-linejoi [0] <rect height=u'100' width=u'100' stroke=u'none' y=u'0' x=u'0' fill=u'yellow' [1] <REPLACEME /> >>> >>> print template("template.svg", SVG("circle", cx=50, cy=50, r=30)) None <svg (2 sub) style=u'stroke:black; fill:none; stroke-width:0.5pt; stroke-linejoi [0] <rect height=u'100' width=u'100' stroke=u'none' y=u'0' x=u'0' fill=u'yellow' [1] <circle cy=50 cx=50 r=30 /> """ output = load(fileName) for ti, s in output: if isinstance(s, SVG) and s.t == replaceme: output[ti] = svg return output
[ "def", "template", "(", "fileName", ",", "svg", ",", "replaceme", "=", "\"REPLACEME\"", ")", ":", "output", "=", "load", "(", "fileName", ")", "for", "ti", ",", "s", "in", "output", ":", "if", "isinstance", "(", "s", ",", "SVG", ")", "and", "s", ".", "t", "==", "replaceme", ":", "output", "[", "ti", "]", "=", "svg", "return", "output" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/doc/pattern_tools/svgfig.py#L567-L589
HKUST-Aerial-Robotics/Fast-Planner
2ddd7793eecd573dbb5b47e2c985aa06606df3cf
uav_simulator/Utils/odom_visualization/build/devel/_setup_util.py
python
_get_workspaces
(environ, include_fuerte=False, include_non_existing=False)
return workspaces
Based on CMAKE_PREFIX_PATH return all catkin workspaces. :param include_fuerte: The flag if paths starting with '/opt/ros/fuerte' should be considered workspaces, ``bool``
Based on CMAKE_PREFIX_PATH return all catkin workspaces.
[ "Based", "on", "CMAKE_PREFIX_PATH", "return", "all", "catkin", "workspaces", "." ]
def _get_workspaces(environ, include_fuerte=False, include_non_existing=False): ''' Based on CMAKE_PREFIX_PATH return all catkin workspaces. :param include_fuerte: The flag if paths starting with '/opt/ros/fuerte' should be considered workspaces, ``bool`` ''' # get all cmake prefix paths env_name = 'CMAKE_PREFIX_PATH' value = environ[env_name] if env_name in environ else '' paths = [path for path in value.split(os.pathsep) if path] # remove non-workspace paths workspaces = [path for path in paths if os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE)) or (include_fuerte and path.startswith('/opt/ros/fuerte')) or (include_non_existing and not os.path.exists(path))] return workspaces
[ "def", "_get_workspaces", "(", "environ", ",", "include_fuerte", "=", "False", ",", "include_non_existing", "=", "False", ")", ":", "# get all cmake prefix paths", "env_name", "=", "'CMAKE_PREFIX_PATH'", "value", "=", "environ", "[", "env_name", "]", "if", "env_name", "in", "environ", "else", "''", "paths", "=", "[", "path", "for", "path", "in", "value", ".", "split", "(", "os", ".", "pathsep", ")", "if", "path", "]", "# remove non-workspace paths", "workspaces", "=", "[", "path", "for", "path", "in", "paths", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "CATKIN_MARKER_FILE", ")", ")", "or", "(", "include_fuerte", "and", "path", ".", "startswith", "(", "'/opt/ros/fuerte'", ")", ")", "or", "(", "include_non_existing", "and", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ")", "]", "return", "workspaces" ]
https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/odom_visualization/build/devel/_setup_util.py#L114-L126
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
third_party/cpplint.py
python
CheckBracesSpacing
(filename, clean_lines, linenum, nesting_state, error)
Checks for horizontal spacing near commas. 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 horizontal spacing near commas.
[ "Checks", "for", "horizontal", "spacing", "near", "commas", "." ]
def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for horizontal spacing near commas. 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] # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces when they are delimiting blocks, classes, namespaces etc. # And since you should never have braces at the beginning of a line, # this is an easy test. Except that braces used for initialization don't # follow the same rule; we often don't want spaces before those. match = Match(r'^(.*[^ ({>]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # ternary = expr ? new type{} : nullptr; # OuterTemplate<InnerTemplateConstructor<Type>{}> # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<>]:". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. leading_text = match.group(1) (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in range(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] # We also suppress warnings for `uint64_t{expression}` etc., as the style # guide recommends brace initialization for integral types to avoid # overflow/truncation. if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text) and not _IsType(clean_lines, nesting_state, leading_text)): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.')
[ "def", "CheckBracesSpacing", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Except after an opening paren, or after another opening brace (in case of", "# an initializer list, for instance), you should have spaces before your", "# braces when they are delimiting blocks, classes, namespaces etc.", "# And since you should never have braces at the beginning of a line,", "# this is an easy test. Except that braces used for initialization don't", "# follow the same rule; we often don't want spaces before those.", "match", "=", "Match", "(", "r'^(.*[^ ({>]){'", ",", "line", ")", "if", "match", ":", "# Try a bit harder to check for brace initialization. This", "# happens in one of the following forms:", "# Constructor() : initializer_list_{} { ... }", "# Constructor{}.MemberFunction()", "# Type variable{};", "# FunctionCall(type{}, ...);", "# LastArgument(..., type{});", "# LOG(INFO) << type{} << \" ...\";", "# map_of_type[{...}] = ...;", "# ternary = expr ? new type{} : nullptr;", "# OuterTemplate<InnerTemplateConstructor<Type>{}>", "#", "# We check for the character following the closing brace, and", "# silence the warning if it's one of those listed above, i.e.", "# \"{.;,)<>]:\".", "#", "# To account for nested initializer list, we allow any number of", "# closing braces up to \"{;,)<\". We can't simply silence the", "# warning on first sight of closing brace, because that would", "# cause false negatives for things that are not initializer lists.", "# Silence this: But not this:", "# Outer{ if (...) {", "# Inner{...} if (...){ // Missing space before {", "# }; }", "#", "# There is a false negative with this approach if people inserted", "# spurious semicolons, e.g. \"if (cond){};\", but we will catch the", "# spurious semicolon with a separate check.", "leading_text", "=", "match", ".", "group", "(", "1", ")", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "trailing_text", "=", "''", "if", "endpos", ">", "-", "1", ":", "trailing_text", "=", "endline", "[", "endpos", ":", "]", "for", "offset", "in", "range", "(", "endlinenum", "+", "1", ",", "min", "(", "endlinenum", "+", "3", ",", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ")", ")", ":", "trailing_text", "+=", "clean_lines", ".", "elided", "[", "offset", "]", "# We also suppress warnings for `uint64_t{expression}` etc., as the style", "# guide recommends brace initialization for integral types to avoid", "# overflow/truncation.", "if", "(", "not", "Match", "(", "r'^[\\s}]*[{.;,)<>\\]:]'", ",", "trailing_text", ")", "and", "not", "_IsType", "(", "clean_lines", ",", "nesting_state", ",", "leading_text", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before {'", ")", "# Make sure '} else {' has spaces.", "if", "Search", "(", "r'}else'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/braces'", ",", "5", ",", "'Missing space before else'", ")", "# You shouldn't have a space before a semicolon at the end of the line.", "# There's a special case for \"for\" since the style guide allows space before", "# the semicolon there.", "if", "Search", "(", "r':\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Semicolon defining empty statement. Use {} instead.'", ")", "elif", "Search", "(", "r'^\\s*;\\s*$'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Line contains only semicolon. If this should be an empty statement, '", "'use {} instead.'", ")", "elif", "(", "Search", "(", "r'\\s+;\\s*$'", ",", "line", ")", "and", "not", "Search", "(", "r'\\bfor\\b'", ",", "line", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/semicolon'", ",", "5", ",", "'Extra space before last semicolon. If this should be an empty '", "'statement, use {} instead.'", ")" ]
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/third_party/cpplint.py#L3548-L3634
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHandler.py
python
IdleConf.GetHighlight
(self, theme, element, fgBg=None)
return individual highlighting theme elements. fgBg - string ('fg'or'bg') or None, if None return a dictionary containing fg and bg colours (appropriate for passing to Tkinter in, e.g., a tag_config call), otherwise fg or bg colour only as specified.
return individual highlighting theme elements. fgBg - string ('fg'or'bg') or None, if None return a dictionary containing fg and bg colours (appropriate for passing to Tkinter in, e.g., a tag_config call), otherwise fg or bg colour only as specified.
[ "return", "individual", "highlighting", "theme", "elements", ".", "fgBg", "-", "string", "(", "fg", "or", "bg", ")", "or", "None", "if", "None", "return", "a", "dictionary", "containing", "fg", "and", "bg", "colours", "(", "appropriate", "for", "passing", "to", "Tkinter", "in", "e", ".", "g", ".", "a", "tag_config", "call", ")", "otherwise", "fg", "or", "bg", "colour", "only", "as", "specified", "." ]
def GetHighlight(self, theme, element, fgBg=None): """ return individual highlighting theme elements. fgBg - string ('fg'or'bg') or None, if None return a dictionary containing fg and bg colours (appropriate for passing to Tkinter in, e.g., a tag_config call), otherwise fg or bg colour only as specified. """ if self.defaultCfg['highlight'].has_section(theme): themeDict=self.GetThemeDict('default',theme) else: themeDict=self.GetThemeDict('user',theme) fore=themeDict[element+'-foreground'] if element=='cursor': #there is no config value for cursor bg back=themeDict['normal-background'] else: back=themeDict[element+'-background'] highlight={"foreground": fore,"background": back} if not fgBg: #return dict of both colours return highlight else: #return specified colour only if fgBg == 'fg': return highlight["foreground"] if fgBg == 'bg': return highlight["background"] else: raise InvalidFgBg, 'Invalid fgBg specified'
[ "def", "GetHighlight", "(", "self", ",", "theme", ",", "element", ",", "fgBg", "=", "None", ")", ":", "if", "self", ".", "defaultCfg", "[", "'highlight'", "]", ".", "has_section", "(", "theme", ")", ":", "themeDict", "=", "self", ".", "GetThemeDict", "(", "'default'", ",", "theme", ")", "else", ":", "themeDict", "=", "self", ".", "GetThemeDict", "(", "'user'", ",", "theme", ")", "fore", "=", "themeDict", "[", "element", "+", "'-foreground'", "]", "if", "element", "==", "'cursor'", ":", "#there is no config value for cursor bg", "back", "=", "themeDict", "[", "'normal-background'", "]", "else", ":", "back", "=", "themeDict", "[", "element", "+", "'-background'", "]", "highlight", "=", "{", "\"foreground\"", ":", "fore", ",", "\"background\"", ":", "back", "}", "if", "not", "fgBg", ":", "#return dict of both colours", "return", "highlight", "else", ":", "#return specified colour only", "if", "fgBg", "==", "'fg'", ":", "return", "highlight", "[", "\"foreground\"", "]", "if", "fgBg", "==", "'bg'", ":", "return", "highlight", "[", "\"background\"", "]", "else", ":", "raise", "InvalidFgBg", ",", "'Invalid fgBg specified'" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configHandler.py#L297-L322
Samsung/veles
95ed733c2e49bc011ad98ccf2416ecec23fbf352
libVeles/cpplint.py
python
FindNextMatchingAngleBracket
(clean_lines, linenum, init_suffix)
return True
Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists.
Find the corresponding > to close a template.
[ "Find", "the", "corresponding", ">", "to", "close", "a", "template", "." ]
def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): """Find the corresponding > to close a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_suffix: Remainder of the current line after the initial <. Returns: True if a matching bracket exists. """ line = init_suffix nesting_stack = ['<'] while True: # Find the next operator that can tell us whether < is used as an # opening bracket or as a less-than operator. We only want to # warn on the latter case. # # We could also check all other operators and terminate the search # early, e.g. if we got something like this "a<b+c", the "<" is # most likely a less-than operator, but then we will get false # positives for default arguments (e.g. http://go/prccd) and # other template expressions (e.g. http://go/oxcjq). match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) if match: # Found an operator, update nesting stack operator = match.group(1) line = match.group(2) if nesting_stack[-1] == '<': # Expecting closing angle bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator == '>': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma after a bracket, this is most likely a template # argument. We have not seen a closing angle bracket yet, but # it's probably a few lines later if we look for it, so just # return early here. return True else: # Got some other operator. return False else: # Expecting closing parenthesis or closing bracket if operator in ('<', '(', '['): nesting_stack.append(operator) elif operator in (')', ']'): # We don't bother checking for matching () or []. If we got # something like (] or [), it would have been a syntax error. nesting_stack.pop() else: # Scan the next line linenum += 1 if linenum >= len(clean_lines.elided): break line = clean_lines.elided[linenum] # Exhausted all remaining lines and still no matching angle bracket. # Most likely the input was incomplete, otherwise we should have # seen a semicolon and returned early. return True
[ "def", "FindNextMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_suffix", ")", ":", "line", "=", "init_suffix", "nesting_stack", "=", "[", "'<'", "]", "while", "True", ":", "# Find the next operator that can tell us whether < is used as an", "# opening bracket or as a less-than operator. We only want to", "# warn on the latter case.", "#", "# We could also check all other operators and terminate the search", "# early, e.g. if we got something like this \"a<b+c\", the \"<\" is", "# most likely a less-than operator, but then we will get false", "# positives for default arguments (e.g. http://go/prccd) and", "# other template expressions (e.g. http://go/oxcjq).", "match", "=", "Search", "(", "r'^[^<>(),;\\[\\]]*([<>(),;\\[\\]])(.*)$'", ",", "line", ")", "if", "match", ":", "# Found an operator, update nesting stack", "operator", "=", "match", ".", "group", "(", "1", ")", "line", "=", "match", ".", "group", "(", "2", ")", "if", "nesting_stack", "[", "-", "1", "]", "==", "'<'", ":", "# Expecting closing angle bracket", "if", "operator", "in", "(", "'<'", ",", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "==", "'>'", ":", "nesting_stack", ".", "pop", "(", ")", "if", "not", "nesting_stack", ":", "# Found matching angle bracket", "return", "True", "elif", "operator", "==", "','", ":", "# Got a comma after a bracket, this is most likely a template", "# argument. We have not seen a closing angle bracket yet, but", "# it's probably a few lines later if we look for it, so just", "# return early here.", "return", "True", "else", ":", "# Got some other operator.", "return", "False", "else", ":", "# Expecting closing parenthesis or closing bracket", "if", "operator", "in", "(", "'<'", ",", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "in", "(", "')'", ",", "']'", ")", ":", "# We don't bother checking for matching () or []. If we got", "# something like (] or [), it would have been a syntax error.", "nesting_stack", ".", "pop", "(", ")", "else", ":", "# Scan the next line", "linenum", "+=", "1", "if", "linenum", ">=", "len", "(", "clean_lines", ".", "elided", ")", ":", "break", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Exhausted all remaining lines and still no matching angle bracket.", "# Most likely the input was incomplete, otherwise we should have", "# seen a semicolon and returned early.", "return", "True" ]
https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/libVeles/cpplint.py#L2074-L2141
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/resmokelib/core/programs.py
python
_apply_set_parameters
(args, set_parameter)
Converts key-value pairs from 'kwargs' into --setParameter key=value arguments to an executable and appends them to 'args'.
Converts key-value pairs from 'kwargs' into --setParameter key=value arguments to an executable and appends them to 'args'.
[ "Converts", "key", "-", "value", "pairs", "from", "kwargs", "into", "--", "setParameter", "key", "=", "value", "arguments", "to", "an", "executable", "and", "appends", "them", "to", "args", "." ]
def _apply_set_parameters(args, set_parameter): """ Converts key-value pairs from 'kwargs' into --setParameter key=value arguments to an executable and appends them to 'args'. """ for param_name in set_parameter: param_value = set_parameter[param_name] # --setParameter takes boolean values as lowercase strings. if isinstance(param_value, bool): param_value = "true" if param_value else "false" args.append("--setParameter") args.append("%s=%s" % (param_name, param_value))
[ "def", "_apply_set_parameters", "(", "args", ",", "set_parameter", ")", ":", "for", "param_name", "in", "set_parameter", ":", "param_value", "=", "set_parameter", "[", "param_name", "]", "# --setParameter takes boolean values as lowercase strings.", "if", "isinstance", "(", "param_value", ",", "bool", ")", ":", "param_value", "=", "\"true\"", "if", "param_value", "else", "\"false\"", "args", ".", "append", "(", "\"--setParameter\"", ")", "args", ".", "append", "(", "\"%s=%s\"", "%", "(", "param_name", ",", "param_value", ")", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/resmokelib/core/programs.py#L334-L346
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py
python
Context.to_sci_string
(self, a)
return a.__str__(context=self)
Converts a number to a string, using scientific notation. The operation is not affected by the context.
Converts a number to a string, using scientific notation.
[ "Converts", "a", "number", "to", "a", "string", "using", "scientific", "notation", "." ]
def to_sci_string(self, a): """Converts a number to a string, using scientific notation. The operation is not affected by the context. """ a = _convert_other(a, raiseit=True) return a.__str__(context=self)
[ "def", "to_sci_string", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "__str__", "(", "context", "=", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pydecimal.py#L5544-L5550
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/gdb/mongo_printers.py
python
MongoPrettyPrinterCollection.__init__
(self)
Initialize MongoPrettyPrinterCollection.
Initialize MongoPrettyPrinterCollection.
[ "Initialize", "MongoPrettyPrinterCollection", "." ]
def __init__(self): """Initialize MongoPrettyPrinterCollection.""" super(MongoPrettyPrinterCollection, self).__init__("mongo", [])
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "MongoPrettyPrinterCollection", ",", "self", ")", ".", "__init__", "(", "\"mongo\"", ",", "[", "]", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/gdb/mongo_printers.py#L616-L618
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/yply/yparse.py
python
p_definition_token
(p)
definition : toktype opttype idlist optsemi
definition : toktype opttype idlist optsemi
[ "definition", ":", "toktype", "opttype", "idlist", "optsemi" ]
def p_definition_token(p): '''definition : toktype opttype idlist optsemi ''' for i in p[3]: if i[0] not in "'\"": tokenlist.append(i) if p[1] == '%left': preclist.append(('left',) + tuple(p[3])) elif p[1] == '%right': preclist.append(('right',) + tuple(p[3])) elif p[1] == '%nonassoc': preclist.append(('nonassoc',)+ tuple(p[3]))
[ "def", "p_definition_token", "(", "p", ")", ":", "for", "i", "in", "p", "[", "3", "]", ":", "if", "i", "[", "0", "]", "not", "in", "\"'\\\"\"", ":", "tokenlist", ".", "append", "(", "i", ")", "if", "p", "[", "1", "]", "==", "'%left'", ":", "preclist", ".", "append", "(", "(", "'left'", ",", ")", "+", "tuple", "(", "p", "[", "3", "]", ")", ")", "elif", "p", "[", "1", "]", "==", "'%right'", ":", "preclist", ".", "append", "(", "(", "'right'", ",", ")", "+", "tuple", "(", "p", "[", "3", "]", ")", ")", "elif", "p", "[", "1", "]", "==", "'%nonassoc'", ":", "preclist", ".", "append", "(", "(", "'nonassoc'", ",", ")", "+", "tuple", "(", "p", "[", "3", "]", ")", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/yply/yparse.py#L48-L58
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/writers/ComponentWriterBase.py
python
ComponentWriterBase.buildFileName
(self, obj)
return filename
Build the file name
Build the file name
[ "Build", "the", "file", "name" ]
def buildFileName(self, obj): """ Build the file name """ if self.config("component", "XMLDefaultFileName") == "True": filename = ( obj.get_namespace() + obj.get_name() + self.config("component", self.__writer) ) DEBUG.info( "Generating code filename: %s, using XML namespace and name attributes..." % filename ) else: xml_file = obj.get_xml_filename() x = xml_file.split(".") s = self.config("component", "ComponentXML").split(".") l = len(s[0]) if (x[0][-l:] == s[0]) & (x[1] == s[1]): filename = x[0].split(s[0])[0] + self.config("component", self.__writer) DEBUG.info("Generating code filename: %s..." % filename) else: msg = ( "XML file naming format not allowed (must be XXXComponentAi.xml), Filename: %s" % xml_file ) PRINT.info(msg) raise ValueError(msg) return filename
[ "def", "buildFileName", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "config", "(", "\"component\"", ",", "\"XMLDefaultFileName\"", ")", "==", "\"True\"", ":", "filename", "=", "(", "obj", ".", "get_namespace", "(", ")", "+", "obj", ".", "get_name", "(", ")", "+", "self", ".", "config", "(", "\"component\"", ",", "self", ".", "__writer", ")", ")", "DEBUG", ".", "info", "(", "\"Generating code filename: %s, using XML namespace and name attributes...\"", "%", "filename", ")", "else", ":", "xml_file", "=", "obj", ".", "get_xml_filename", "(", ")", "x", "=", "xml_file", ".", "split", "(", "\".\"", ")", "s", "=", "self", ".", "config", "(", "\"component\"", ",", "\"ComponentXML\"", ")", ".", "split", "(", "\".\"", ")", "l", "=", "len", "(", "s", "[", "0", "]", ")", "if", "(", "x", "[", "0", "]", "[", "-", "l", ":", "]", "==", "s", "[", "0", "]", ")", "&", "(", "x", "[", "1", "]", "==", "s", "[", "1", "]", ")", ":", "filename", "=", "x", "[", "0", "]", ".", "split", "(", "s", "[", "0", "]", ")", "[", "0", "]", "+", "self", ".", "config", "(", "\"component\"", ",", "self", ".", "__writer", ")", "DEBUG", ".", "info", "(", "\"Generating code filename: %s...\"", "%", "filename", ")", "else", ":", "msg", "=", "(", "\"XML file naming format not allowed (must be XXXComponentAi.xml), Filename: %s\"", "%", "xml_file", ")", "PRINT", ".", "info", "(", "msg", ")", "raise", "ValueError", "(", "msg", ")", "return", "filename" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/writers/ComponentWriterBase.py#L84-L113
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/config.py
python
read_configuration
( filepath, find_others=False, ignore_option_errors=False)
return configuration_to_dict(handlers)
Read given configuration file and returns options from it as a dict. :param str|unicode filepath: Path to configuration file to get options from. :param bool find_others: Whether to search for other configuration files which could be on in various places. :param bool ignore_option_errors: Whether to silently ignore options, values of which could not be resolved (e.g. due to exceptions in directives such as file:, attr:, etc.). If False exceptions are propagated as expected. :rtype: dict
Read given configuration file and returns options from it as a dict.
[ "Read", "given", "configuration", "file", "and", "returns", "options", "from", "it", "as", "a", "dict", "." ]
def read_configuration( filepath, find_others=False, ignore_option_errors=False): """Read given configuration file and returns options from it as a dict. :param str|unicode filepath: Path to configuration file to get options from. :param bool find_others: Whether to search for other configuration files which could be on in various places. :param bool ignore_option_errors: Whether to silently ignore options, values of which could not be resolved (e.g. due to exceptions in directives such as file:, attr:, etc.). If False exceptions are propagated as expected. :rtype: dict """ from setuptools.dist import Distribution, _Distribution filepath = os.path.abspath(filepath) if not os.path.isfile(filepath): raise DistutilsFileError( 'Configuration file %s does not exist.' % filepath) current_directory = os.getcwd() os.chdir(os.path.dirname(filepath)) try: dist = Distribution() filenames = dist.find_config_files() if find_others else [] if filepath not in filenames: filenames.append(filepath) _Distribution.parse_config_files(dist, filenames=filenames) handlers = parse_configuration( dist, dist.command_options, ignore_option_errors=ignore_option_errors) finally: os.chdir(current_directory) return configuration_to_dict(handlers)
[ "def", "read_configuration", "(", "filepath", ",", "find_others", "=", "False", ",", "ignore_option_errors", "=", "False", ")", ":", "from", "setuptools", ".", "dist", "import", "Distribution", ",", "_Distribution", "filepath", "=", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "filepath", ")", ":", "raise", "DistutilsFileError", "(", "'Configuration file %s does not exist.'", "%", "filepath", ")", "current_directory", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ")", "try", ":", "dist", "=", "Distribution", "(", ")", "filenames", "=", "dist", ".", "find_config_files", "(", ")", "if", "find_others", "else", "[", "]", "if", "filepath", "not", "in", "filenames", ":", "filenames", ".", "append", "(", "filepath", ")", "_Distribution", ".", "parse_config_files", "(", "dist", ",", "filenames", "=", "filenames", ")", "handlers", "=", "parse_configuration", "(", "dist", ",", "dist", ".", "command_options", ",", "ignore_option_errors", "=", "ignore_option_errors", ")", "finally", ":", "os", ".", "chdir", "(", "current_directory", ")", "return", "configuration_to_dict", "(", "handlers", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/config.py#L22-L66
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/api.py
python
_memory_size_from_info
(shape, strides, itemsize)
return e - s
Get the byte size of a contiguous memory buffer given the shape, strides and itemsize.
Get the byte size of a contiguous memory buffer given the shape, strides and itemsize.
[ "Get", "the", "byte", "size", "of", "a", "contiguous", "memory", "buffer", "given", "the", "shape", "strides", "and", "itemsize", "." ]
def _memory_size_from_info(shape, strides, itemsize): """Get the byte size of a contiguous memory buffer given the shape, strides and itemsize. """ assert len(shape) == len(strides), "# dim mismatch" ndim = len(shape) s, e = mviewbuf.memoryview_get_extents_info(shape, strides, ndim, itemsize) return e - s
[ "def", "_memory_size_from_info", "(", "shape", ",", "strides", ",", "itemsize", ")", ":", "assert", "len", "(", "shape", ")", "==", "len", "(", "strides", ")", ",", "\"# dim mismatch\"", "ndim", "=", "len", "(", "shape", ")", "s", ",", "e", "=", "mviewbuf", ".", "memoryview_get_extents_info", "(", "shape", ",", "strides", ",", "ndim", ",", "itemsize", ")", "return", "e", "-", "s" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/api.py#L159-L166
mgbellemare/Arcade-Learning-Environment
0af0ff4a49a981d113c67b866fa152dbc7a1c0a7
src/gym/envs/atari/environment.py
python
AtariEnv.restore_full_state
(self, state: ALEState)
Restore emulator state w/ system state including pseudorandomness.
Restore emulator state w/ system state including pseudorandomness.
[ "Restore", "emulator", "state", "w", "/", "system", "state", "including", "pseudorandomness", "." ]
def restore_full_state(self, state: ALEState) -> None: """Restore emulator state w/ system state including pseudorandomness.""" logger.warn( "restore_full_state() is deprecated and will be removed in a future release of `ale-py`. " "Please use `restore_state(state)` which will restore the state regardless of being a full or partial state. " ) self.ale.restoreSystemState(state)
[ "def", "restore_full_state", "(", "self", ",", "state", ":", "ALEState", ")", "->", "None", ":", "logger", ".", "warn", "(", "\"restore_full_state() is deprecated and will be removed in a future release of `ale-py`. \"", "\"Please use `restore_state(state)` which will restore the state regardless of being a full or partial state. \"", ")", "self", ".", "ale", ".", "restoreSystemState", "(", "state", ")" ]
https://github.com/mgbellemare/Arcade-Learning-Environment/blob/0af0ff4a49a981d113c67b866fa152dbc7a1c0a7/src/gym/envs/atari/environment.py#L359-L365
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pprint.py
python
pprint
(object, stream=None, indent=1, width=80, depth=None)
Pretty-print a Python object to a stream [default is sys.stdout].
Pretty-print a Python object to a stream [default is sys.stdout].
[ "Pretty", "-", "print", "a", "Python", "object", "to", "a", "stream", "[", "default", "is", "sys", ".", "stdout", "]", "." ]
def pprint(object, stream=None, indent=1, width=80, depth=None): """Pretty-print a Python object to a stream [default is sys.stdout].""" printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object)
[ "def", "pprint", "(", "object", ",", "stream", "=", "None", ",", "indent", "=", "1", ",", "width", "=", "80", ",", "depth", "=", "None", ")", ":", "printer", "=", "PrettyPrinter", "(", "stream", "=", "stream", ",", "indent", "=", "indent", ",", "width", "=", "width", ",", "depth", "=", "depth", ")", "printer", ".", "pprint", "(", "object", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/pprint.py#L55-L59
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pydocview.py
python
ChildDocTemplate.CreateDocument
(self, path, flags, data=None, parentDocument=None)
Called when a ChildDocument is to be created and does the minimum such that the ChildDocument looks like a real Document to the framework.
Called when a ChildDocument is to be created and does the minimum such that the ChildDocument looks like a real Document to the framework.
[ "Called", "when", "a", "ChildDocument", "is", "to", "be", "created", "and", "does", "the", "minimum", "such", "that", "the", "ChildDocument", "looks", "like", "a", "real", "Document", "to", "the", "framework", "." ]
def CreateDocument(self, path, flags, data=None, parentDocument=None): """ Called when a ChildDocument is to be created and does the minimum such that the ChildDocument looks like a real Document to the framework. """ doc = self._docType() doc.SetFilename(path) doc.SetData(data) doc.SetParentDocument(parentDocument) doc.SetDocumentTemplate(self) self.GetDocumentManager().AddDocument(doc) doc.SetCommandProcessor(doc.OnCreateCommandProcessor()) if doc.OnCreate(path, flags): return doc else: if doc in self.GetDocumentManager().GetDocuments(): doc.DeleteAllViews() return None
[ "def", "CreateDocument", "(", "self", ",", "path", ",", "flags", ",", "data", "=", "None", ",", "parentDocument", "=", "None", ")", ":", "doc", "=", "self", ".", "_docType", "(", ")", "doc", ".", "SetFilename", "(", "path", ")", "doc", ".", "SetData", "(", "data", ")", "doc", ".", "SetParentDocument", "(", "parentDocument", ")", "doc", ".", "SetDocumentTemplate", "(", "self", ")", "self", ".", "GetDocumentManager", "(", ")", ".", "AddDocument", "(", "doc", ")", "doc", ".", "SetCommandProcessor", "(", "doc", ".", "OnCreateCommandProcessor", "(", ")", ")", "if", "doc", ".", "OnCreate", "(", "path", ",", "flags", ")", ":", "return", "doc", "else", ":", "if", "doc", "in", "self", ".", "GetDocumentManager", "(", ")", ".", "GetDocuments", "(", ")", ":", "doc", ".", "DeleteAllViews", "(", ")", "return", "None" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pydocview.py#L2823-L2840
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py
python
BasicFittingPresenter.initialize_model_options
(self)
Initialise the model with the default fitting options.
Initialise the model with the default fitting options.
[ "Initialise", "the", "model", "with", "the", "default", "fitting", "options", "." ]
def initialize_model_options(self) -> None: """Initialise the model with the default fitting options.""" self.model.minimizer = self.view.minimizer self.model.evaluation_type = self.view.evaluation_type self.model.fit_to_raw = self.view.fit_to_raw
[ "def", "initialize_model_options", "(", "self", ")", "->", "None", ":", "self", ".", "model", ".", "minimizer", "=", "self", ".", "view", ".", "minimizer", "self", ".", "model", ".", "evaluation_type", "=", "self", ".", "view", ".", "evaluation_type", "self", ".", "model", ".", "fit_to_raw", "=", "self", ".", "view", ".", "fit_to_raw" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_presenter.py#L89-L93
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/sort-module.py
python
main
(file_paths)
Args: @param: file_paths: List of paths to SQL files, where each path is of the form: '.../modules/<module_name>/...'.
Args:
[ "Args", ":" ]
def main(file_paths): """ Args: @param: file_paths: List of paths to SQL files, where each path is of the form: '.../modules/<module_name>/...'. """ file_order = sorted(file_paths, key=find_order) print " ".join(file_order)
[ "def", "main", "(", "file_paths", ")", ":", "file_order", "=", "sorted", "(", "file_paths", ",", "key", "=", "find_order", ")", "print", "\" \"", ".", "join", "(", "file_order", ")" ]
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/sort-module.py#L60-L67
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/cpp.py
python
PreProcessor.start_handling_includes
(self, t=None)
Causes the PreProcessor object to start processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates True, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated False.
Causes the PreProcessor object to start processing #import, #include and #include_next lines.
[ "Causes", "the", "PreProcessor", "object", "to", "start", "processing", "#import", "#include", "and", "#include_next", "lines", "." ]
def start_handling_includes(self, t=None): """ Causes the PreProcessor object to start processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates True, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated False. """ d = self.dispatch_table p = self.stack[-1] if self.stack else self.default_table for k in ('import', 'include', 'include_next', 'define', 'undef'): d[k] = p[k]
[ "def", "start_handling_includes", "(", "self", ",", "t", "=", "None", ")", ":", "d", "=", "self", ".", "dispatch_table", "p", "=", "self", ".", "stack", "[", "-", "1", "]", "if", "self", ".", "stack", "else", "self", ".", "default_table", "for", "k", "in", "(", "'import'", ",", "'include'", ",", "'include_next'", ",", "'define'", ",", "'undef'", ")", ":", "d", "[", "k", "]", "=", "p", "[", "k", "]" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/cpp.py#L425-L440
rougier/CPP-Crash-Course
e85478d296890cf657198ba961227f63e54278f3
rst2html.py
python
Lexer.__iter__
(self)
Parse self.code and yield "classified" tokens
Parse self.code and yield "classified" tokens
[ "Parse", "self", ".", "code", "and", "yield", "classified", "tokens" ]
def __iter__(self): """Parse self.code and yield "classified" tokens """ codestring = u'\n'.join(self.code) if self.lexer is None: yield [('', codestring)] return tokens = pygments.lex(codestring, self.lexer) for ttype, value in self.merge(tokens): # yield (ttype, value) # token type objects yield (_get_ttype_class(ttype), value)
[ "def", "__iter__", "(", "self", ")", ":", "codestring", "=", "u'\\n'", ".", "join", "(", "self", ".", "code", ")", "if", "self", ".", "lexer", "is", "None", ":", "yield", "[", "(", "''", ",", "codestring", ")", "]", "return", "tokens", "=", "pygments", ".", "lex", "(", "codestring", ",", "self", ".", "lexer", ")", "for", "ttype", ",", "value", "in", "self", ".", "merge", "(", "tokens", ")", ":", "# yield (ttype, value) # token type objects", "yield", "(", "_get_ttype_class", "(", "ttype", ")", ",", "value", ")" ]
https://github.com/rougier/CPP-Crash-Course/blob/e85478d296890cf657198ba961227f63e54278f3/rst2html.py#L117-L127
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
tools/clang/tools/scan-build-py/libscanbuild/intercept.py
python
entry_hash
(entry)
return '<>'.join([filename, directory, command])
Implement unique hash method for compilation database entries.
Implement unique hash method for compilation database entries.
[ "Implement", "unique", "hash", "method", "for", "compilation", "database", "entries", "." ]
def entry_hash(entry): """ Implement unique hash method for compilation database entries. """ # For faster lookup in set filename is reverted filename = entry['file'][::-1] # For faster lookup in set directory is reverted directory = entry['directory'][::-1] # On OS X the 'cc' and 'c++' compilers are wrappers for # 'clang' therefore both call would be logged. To avoid # this the hash does not contain the first word of the # command. command = ' '.join(decode(entry['command'])[1:]) return '<>'.join([filename, directory, command])
[ "def", "entry_hash", "(", "entry", ")", ":", "# For faster lookup in set filename is reverted", "filename", "=", "entry", "[", "'file'", "]", "[", ":", ":", "-", "1", "]", "# For faster lookup in set directory is reverted", "directory", "=", "entry", "[", "'directory'", "]", "[", ":", ":", "-", "1", "]", "# On OS X the 'cc' and 'c++' compilers are wrappers for", "# 'clang' therefore both call would be logged. To avoid", "# this the hash does not contain the first word of the", "# command.", "command", "=", "' '", ".", "join", "(", "decode", "(", "entry", "[", "'command'", "]", ")", "[", "1", ":", "]", ")", "return", "'<>'", ".", "join", "(", "[", "filename", ",", "directory", ",", "command", "]", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/tools/scan-build-py/libscanbuild/intercept.py#L250-L263
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/requireprovidesorter.py
python
RequireProvideSorter._GetRequireOrProvideTokens
(self, token, token_string)
return tokens
Gets all goog.provide or goog.require tokens in the given token stream. Args: token: The first token in the token stream. token_string: One of 'goog.provide' or 'goog.require' to indicate which tokens to find. Returns: A list of goog.provide or goog.require tokens in the order they appear in the token stream.
Gets all goog.provide or goog.require tokens in the given token stream.
[ "Gets", "all", "goog", ".", "provide", "or", "goog", ".", "require", "tokens", "in", "the", "given", "token", "stream", "." ]
def _GetRequireOrProvideTokens(self, token, token_string): """Gets all goog.provide or goog.require tokens in the given token stream. Args: token: The first token in the token stream. token_string: One of 'goog.provide' or 'goog.require' to indicate which tokens to find. Returns: A list of goog.provide or goog.require tokens in the order they appear in the token stream. """ tokens = [] while token: if token.type == Type.IDENTIFIER: if token.string == token_string: tokens.append(token) elif token.string not in [ 'goog.provide', 'goog.require', 'goog.setTestOnly']: # These 3 identifiers are at the top of the file. So if any other # identifier is encountered, return. # TODO(user): Once it's decided what ordering goog.require # should use, add 'goog.module' to the list above and implement the # decision. break token = token.next return tokens
[ "def", "_GetRequireOrProvideTokens", "(", "self", ",", "token", ",", "token_string", ")", ":", "tokens", "=", "[", "]", "while", "token", ":", "if", "token", ".", "type", "==", "Type", ".", "IDENTIFIER", ":", "if", "token", ".", "string", "==", "token_string", ":", "tokens", ".", "append", "(", "token", ")", "elif", "token", ".", "string", "not", "in", "[", "'goog.provide'", ",", "'goog.require'", ",", "'goog.setTestOnly'", "]", ":", "# These 3 identifiers are at the top of the file. So if any other", "# identifier is encountered, return.", "# TODO(user): Once it's decided what ordering goog.require", "# should use, add 'goog.module' to the list above and implement the", "# decision.", "break", "token", "=", "token", ".", "next", "return", "tokens" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/requireprovidesorter.py#L153-L180
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/utils.py
python
check_header_validity
(header)
Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value).
Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection.
[ "Verifies", "that", "header", "value", "is", "a", "string", "which", "doesn", "t", "contain", "leading", "whitespace", "or", "return", "characters", ".", "This", "prevents", "unintended", "header", "injection", "." ]
def check_header_validity(header): """Verifies that header value is a string which doesn't contain leading whitespace or return characters. This prevents unintended header injection. :param header: tuple, in the format (name, value). """ name, value = header if isinstance(value, bytes): pat = _CLEAN_HEADER_REGEX_BYTE else: pat = _CLEAN_HEADER_REGEX_STR try: if not pat.match(value): raise InvalidHeader("Invalid return character or leading space in header: %s" % name) except TypeError: raise InvalidHeader("Value for header {%s: %s} must be of type str or " "bytes, not %s" % (name, value, type(value)))
[ "def", "check_header_validity", "(", "header", ")", ":", "name", ",", "value", "=", "header", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "pat", "=", "_CLEAN_HEADER_REGEX_BYTE", "else", ":", "pat", "=", "_CLEAN_HEADER_REGEX_STR", "try", ":", "if", "not", "pat", ".", "match", "(", "value", ")", ":", "raise", "InvalidHeader", "(", "\"Invalid return character or leading space in header: %s\"", "%", "name", ")", "except", "TypeError", ":", "raise", "InvalidHeader", "(", "\"Value for header {%s: %s} must be of type str or \"", "\"bytes, not %s\"", "%", "(", "name", ",", "value", ",", "type", "(", "value", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/utils.py#L932-L950
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/tools/clang/utils/creduce-clang-crash.py
python
check_cmd
(cmd_name, cmd_dir, cmd_path=None)
Returns absolute path to cmd_path if it is given, or absolute path to cmd_dir/cmd_name.
Returns absolute path to cmd_path if it is given, or absolute path to cmd_dir/cmd_name.
[ "Returns", "absolute", "path", "to", "cmd_path", "if", "it", "is", "given", "or", "absolute", "path", "to", "cmd_dir", "/", "cmd_name", "." ]
def check_cmd(cmd_name, cmd_dir, cmd_path=None): """ Returns absolute path to cmd_path if it is given, or absolute path to cmd_dir/cmd_name. """ if cmd_path: cmd = find_executable(cmd_path) if cmd: return cmd sys.exit("ERROR: executable `%s` not found" % (cmd_path)) cmd = find_executable(cmd_name, path=cmd_dir) if cmd: return cmd if not cmd_dir: cmd_dir = "$PATH" sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
[ "def", "check_cmd", "(", "cmd_name", ",", "cmd_dir", ",", "cmd_path", "=", "None", ")", ":", "if", "cmd_path", ":", "cmd", "=", "find_executable", "(", "cmd_path", ")", "if", "cmd", ":", "return", "cmd", "sys", ".", "exit", "(", "\"ERROR: executable `%s` not found\"", "%", "(", "cmd_path", ")", ")", "cmd", "=", "find_executable", "(", "cmd_name", ",", "path", "=", "cmd_dir", ")", "if", "cmd", ":", "return", "cmd", "if", "not", "cmd_dir", ":", "cmd_dir", "=", "\"$PATH\"", "sys", ".", "exit", "(", "\"ERROR: `%s` not found in %s\"", "%", "(", "cmd_name", ",", "cmd_dir", ")", ")" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/utils/creduce-clang-crash.py#L37-L54
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py
python
ParserElement.__ror__
(self, other )
return other | self
Implementation of | operator when left operand is not a C{L{ParserElement}}
Implementation of | operator when left operand is not a C{L{ParserElement}}
[ "Implementation", "of", "|", "operator", "when", "left", "operand", "is", "not", "a", "C", "{", "L", "{", "ParserElement", "}}" ]
def __ror__(self, other ): """ Implementation of | operator when left operand is not a C{L{ParserElement}} """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other | self
[ "def", "__ror__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement", ")", ":", "warnings", ".", "warn", "(", "\"Cannot combine element of type %s with ParserElement\"", "%", "type", "(", "other", ")", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "return", "None", "return", "other", "|", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py#L1960-L1970
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/pipes.py
python
Template.reset
(self)
t.reset() restores a pipeline template to its initial state.
t.reset() restores a pipeline template to its initial state.
[ "t", ".", "reset", "()", "restores", "a", "pipeline", "template", "to", "its", "initial", "state", "." ]
def reset(self): """t.reset() restores a pipeline template to its initial state.""" self.steps = []
[ "def", "reset", "(", "self", ")", ":", "self", ".", "steps", "=", "[", "]" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pipes.py#L94-L96
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
cnx/broker/tickFillStrategy.py
python
DefaultStrategy.setSlippageModel
(self, slippageModel)
Set the slippage model to use. :param slippageModel: The slippage model. :type slippageModel: :class:`pyalgotrade.broker.slippage.SlippageModel`
Set the slippage model to use.
[ "Set", "the", "slippage", "model", "to", "use", "." ]
def setSlippageModel(self, slippageModel): """ Set the slippage model to use. :param slippageModel: The slippage model. :type slippageModel: :class:`pyalgotrade.broker.slippage.SlippageModel` """ self.__slippageModel = slippageModel
[ "def", "setSlippageModel", "(", "self", ",", "slippageModel", ")", ":", "self", ".", "__slippageModel", "=", "slippageModel" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/cnx/broker/tickFillStrategy.py#L291-L299
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/packaging/version.py
python
_parse_local_version
(local)
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
[ "Takes", "a", "string", "like", "abc", ".", "1", ".", "twelve", "and", "turns", "it", "into", "(", "abc", "1", "twelve", ")", "." ]
def _parse_local_version(local): """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) )
[ "def", "_parse_local_version", "(", "local", ")", ":", "if", "local", "is", "not", "None", ":", "return", "tuple", "(", "part", ".", "lower", "(", ")", "if", "not", "part", ".", "isdigit", "(", ")", "else", "int", "(", "part", ")", "for", "part", "in", "_local_version_separators", ".", "split", "(", "local", ")", ")" ]
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/packaging/version.py#L367-L375
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/generic_utils.py
python
to_list
(x)
return [x]
Normalizes a list/tensor into a list. If a tensor is passed, we return a list of size 1 containing the tensor. Arguments: x: target object to be normalized. Returns: A list.
Normalizes a list/tensor into a list.
[ "Normalizes", "a", "list", "/", "tensor", "into", "a", "list", "." ]
def to_list(x): """Normalizes a list/tensor into a list. If a tensor is passed, we return a list of size 1 containing the tensor. Arguments: x: target object to be normalized. Returns: A list. """ if isinstance(x, list): return x return [x]
[ "def", "to_list", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "return", "x", "return", "[", "x", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/generic_utils.py#L544-L558
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/core/protocol/paho/client.py
python
Client.connect_srv
(self, domain=None, keepalive=60, bind_address="")
Connect to a remote broker. domain is the DNS domain to search for SRV records; if None, try to determine local domain name. keepalive and bind_address are as for connect()
Connect to a remote broker.
[ "Connect", "to", "a", "remote", "broker", "." ]
def connect_srv(self, domain=None, keepalive=60, bind_address=""): """Connect to a remote broker. domain is the DNS domain to search for SRV records; if None, try to determine local domain name. keepalive and bind_address are as for connect() """ if HAVE_DNS is False: raise ValueError('No DNS resolver library found.') if domain is None: domain = socket.getfqdn() domain = domain[domain.find('.') + 1:] try: rr = '_mqtt._tcp.%s' % domain if self._ssl is not None: # IANA specifies secure-mqtt (not mqtts) for port 8883 rr = '_secure-mqtt._tcp.%s' % domain answers = [] for answer in dns.resolver.query(rr, dns.rdatatype.SRV): addr = answer.target.to_text()[:-1] answers.append((addr, answer.port, answer.priority, answer.weight)) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers): raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain)) # FIXME: doesn't account for weight for answer in answers: host, port, prio, weight = answer try: return self.connect(host, port, keepalive, bind_address) except: pass raise ValueError("No SRV hosts responded")
[ "def", "connect_srv", "(", "self", ",", "domain", "=", "None", ",", "keepalive", "=", "60", ",", "bind_address", "=", "\"\"", ")", ":", "if", "HAVE_DNS", "is", "False", ":", "raise", "ValueError", "(", "'No DNS resolver library found.'", ")", "if", "domain", "is", "None", ":", "domain", "=", "socket", ".", "getfqdn", "(", ")", "domain", "=", "domain", "[", "domain", ".", "find", "(", "'.'", ")", "+", "1", ":", "]", "try", ":", "rr", "=", "'_mqtt._tcp.%s'", "%", "domain", "if", "self", ".", "_ssl", "is", "not", "None", ":", "# IANA specifies secure-mqtt (not mqtts) for port 8883", "rr", "=", "'_secure-mqtt._tcp.%s'", "%", "domain", "answers", "=", "[", "]", "for", "answer", "in", "dns", ".", "resolver", ".", "query", "(", "rr", ",", "dns", ".", "rdatatype", ".", "SRV", ")", ":", "addr", "=", "answer", ".", "target", ".", "to_text", "(", ")", "[", ":", "-", "1", "]", "answers", ".", "append", "(", "(", "addr", ",", "answer", ".", "port", ",", "answer", ".", "priority", ",", "answer", ".", "weight", ")", ")", "except", "(", "dns", ".", "resolver", ".", "NXDOMAIN", ",", "dns", ".", "resolver", ".", "NoAnswer", ",", "dns", ".", "resolver", ".", "NoNameservers", ")", ":", "raise", "ValueError", "(", "\"No answer/NXDOMAIN for SRV in %s\"", "%", "(", "domain", ")", ")", "# FIXME: doesn't account for weight", "for", "answer", "in", "answers", ":", "host", ",", "port", ",", "prio", ",", "weight", "=", "answer", "try", ":", "return", "self", ".", "connect", "(", "host", ",", "port", ",", "keepalive", ",", "bind_address", ")", "except", ":", "pass", "raise", "ValueError", "(", "\"No SRV hosts responded\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemWebCommunicator/AWS/common-code/lib/AWSIoTPythonSDK/core/protocol/paho/client.py#L667-L703
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pyparsing/py2/pyparsing.py
python
ParserElement.setFailAction
(self, fn)
return self
Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments ``fn(s, loc, expr, err)`` where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw :class:`ParseFatalException` if it is desired to stop parsing immediately.
Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments ``fn(s, loc, expr, err)`` where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw :class:`ParseFatalException` if it is desired to stop parsing immediately.
[ "Define", "action", "to", "perform", "if", "parsing", "fails", "at", "this", "expression", ".", "Fail", "acton", "fn", "is", "a", "callable", "function", "that", "takes", "the", "arguments", "fn", "(", "s", "loc", "expr", "err", ")", "where", ":", "-", "s", "=", "string", "being", "parsed", "-", "loc", "=", "location", "where", "expression", "match", "was", "attempted", "and", "failed", "-", "expr", "=", "the", "parse", "expression", "that", "failed", "-", "err", "=", "the", "exception", "thrown", "The", "function", "returns", "no", "value", ".", "It", "may", "throw", ":", "class", ":", "ParseFatalException", "if", "it", "is", "desired", "to", "stop", "parsing", "immediately", "." ]
def setFailAction(self, fn): """Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments ``fn(s, loc, expr, err)`` where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw :class:`ParseFatalException` if it is desired to stop parsing immediately.""" self.failAction = fn return self
[ "def", "setFailAction", "(", "self", ",", "fn", ")", ":", "self", ".", "failAction", "=", "fn", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py2/pyparsing.py#L1602-L1613
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tempfile.py
python
gettempprefixb
()
return _os.fsencode(gettempprefix())
The default prefix for temporary directories as bytes.
The default prefix for temporary directories as bytes.
[ "The", "default", "prefix", "for", "temporary", "directories", "as", "bytes", "." ]
def gettempprefixb(): """The default prefix for temporary directories as bytes.""" return _os.fsencode(gettempprefix())
[ "def", "gettempprefixb", "(", ")", ":", "return", "_os", ".", "fsencode", "(", "gettempprefix", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tempfile.py#L281-L283
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/resources/factory.py
python
ResourceFactory._create_collection
(factory_self, resource_name, collection_model, service_context)
return property(get_collection)
Creates a new property on the resource to lazy-load a collection.
Creates a new property on the resource to lazy-load a collection.
[ "Creates", "a", "new", "property", "on", "the", "resource", "to", "lazy", "-", "load", "a", "collection", "." ]
def _create_collection(factory_self, resource_name, collection_model, service_context): """ Creates a new property on the resource to lazy-load a collection. """ cls = factory_self._collection_factory.load_from_definition( resource_name=resource_name, collection_model=collection_model, service_context=service_context, event_emitter=factory_self._emitter) def get_collection(self): return cls( collection_model=collection_model, parent=self, factory=factory_self, service_context=service_context) get_collection.__name__ = str(collection_model.name) get_collection.__doc__ = docstring.CollectionDocstring( collection_model=collection_model, include_signature=False) return property(get_collection)
[ "def", "_create_collection", "(", "factory_self", ",", "resource_name", ",", "collection_model", ",", "service_context", ")", ":", "cls", "=", "factory_self", ".", "_collection_factory", ".", "load_from_definition", "(", "resource_name", "=", "resource_name", ",", "collection_model", "=", "collection_model", ",", "service_context", "=", "service_context", ",", "event_emitter", "=", "factory_self", ".", "_emitter", ")", "def", "get_collection", "(", "self", ")", ":", "return", "cls", "(", "collection_model", "=", "collection_model", ",", "parent", "=", "self", ",", "factory", "=", "factory_self", ",", "service_context", "=", "service_context", ")", "get_collection", ".", "__name__", "=", "str", "(", "collection_model", ".", "name", ")", "get_collection", ".", "__doc__", "=", "docstring", ".", "CollectionDocstring", "(", "collection_model", "=", "collection_model", ",", "include_signature", "=", "False", ")", "return", "property", "(", "get_collection", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/resources/factory.py#L382-L400
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/kfac/python/ops/utils.py
python
column_to_tensors
(tensors_template, colvec)
return tensors
Converts a column vector back to the shape of the given template. Args: tensors_template: A tensor or list of tensors. colvec: A 2d column vector with the same shape as the value of tensors_to_column(tensors_template). Returns: X, where X is tensor or list of tensors with the properties: 1) tensors_to_column(X) = colvec 2) X (or its elements) have the same shape as tensors_template (or its elements)
Converts a column vector back to the shape of the given template.
[ "Converts", "a", "column", "vector", "back", "to", "the", "shape", "of", "the", "given", "template", "." ]
def column_to_tensors(tensors_template, colvec): """Converts a column vector back to the shape of the given template. Args: tensors_template: A tensor or list of tensors. colvec: A 2d column vector with the same shape as the value of tensors_to_column(tensors_template). Returns: X, where X is tensor or list of tensors with the properties: 1) tensors_to_column(X) = colvec 2) X (or its elements) have the same shape as tensors_template (or its elements) """ if isinstance(tensors_template, (tuple, list)): offset = 0 tensors = [] for tensor_template in tensors_template: sz = np.prod(tensor_template.shape.as_list(), dtype=np.int32) tensor = array_ops.reshape(colvec[offset:(offset + sz)], tensor_template.shape) tensors.append(tensor) offset += sz tensors = tuple(tensors) else: tensors = array_ops.reshape(colvec, tensors_template.shape) return tensors
[ "def", "column_to_tensors", "(", "tensors_template", ",", "colvec", ")", ":", "if", "isinstance", "(", "tensors_template", ",", "(", "tuple", ",", "list", ")", ")", ":", "offset", "=", "0", "tensors", "=", "[", "]", "for", "tensor_template", "in", "tensors_template", ":", "sz", "=", "np", ".", "prod", "(", "tensor_template", ".", "shape", ".", "as_list", "(", ")", ",", "dtype", "=", "np", ".", "int32", ")", "tensor", "=", "array_ops", ".", "reshape", "(", "colvec", "[", "offset", ":", "(", "offset", "+", "sz", ")", "]", ",", "tensor_template", ".", "shape", ")", "tensors", ".", "append", "(", "tensor", ")", "offset", "+=", "sz", "tensors", "=", "tuple", "(", "tensors", ")", "else", ":", "tensors", "=", "array_ops", ".", "reshape", "(", "colvec", ",", "tensors_template", ".", "shape", ")", "return", "tensors" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/kfac/python/ops/utils.py#L82-L110
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Tools/winres.py
python
configure
(conf)
Detect the programs RC or windres, depending on the C/C++ compiler in use
Detect the programs RC or windres, depending on the C/C++ compiler in use
[ "Detect", "the", "programs", "RC", "or", "windres", "depending", "on", "the", "C", "/", "C", "++", "compiler", "in", "use" ]
def configure(conf): """ Detect the programs RC or windres, depending on the C/C++ compiler in use """ v = conf.env v['WINRC_TGT_F'] = '-o' v['WINRC_SRC_F'] = '-i' # find rc.exe if not conf.env.WINRC: if v.CC_NAME == 'msvc': conf.find_program('RC', var='WINRC', path_list = v['PATH'], silent_output=True) v['WINRC_TGT_F'] = '/fo' v['WINRC_SRC_F'] = '' else: conf.find_program('windres', var='WINRC', path_list = v['PATH'], silent_output=True) if not conf.env.WINRC: conf.fatal('winrc was not found!') v['WINRCFLAGS'] = ['/nologo']
[ "def", "configure", "(", "conf", ")", ":", "v", "=", "conf", ".", "env", "v", "[", "'WINRC_TGT_F'", "]", "=", "'-o'", "v", "[", "'WINRC_SRC_F'", "]", "=", "'-i'", "# find rc.exe", "if", "not", "conf", ".", "env", ".", "WINRC", ":", "if", "v", ".", "CC_NAME", "==", "'msvc'", ":", "conf", ".", "find_program", "(", "'RC'", ",", "var", "=", "'WINRC'", ",", "path_list", "=", "v", "[", "'PATH'", "]", ",", "silent_output", "=", "True", ")", "v", "[", "'WINRC_TGT_F'", "]", "=", "'/fo'", "v", "[", "'WINRC_SRC_F'", "]", "=", "''", "else", ":", "conf", ".", "find_program", "(", "'windres'", ",", "var", "=", "'WINRC'", ",", "path_list", "=", "v", "[", "'PATH'", "]", ",", "silent_output", "=", "True", ")", "if", "not", "conf", ".", "env", ".", "WINRC", ":", "conf", ".", "fatal", "(", "'winrc was not found!'", ")", "v", "[", "'WINRCFLAGS'", "]", "=", "[", "'/nologo'", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/winres.py#L96-L115
tum-vision/fusenet
a1451be2971b348a01b0f525c2a3a7a0e215a591
scripts/cpp_lint.py
python
CheckCheck
(filename, clean_lines, linenum, error)
Checks the use of CHECK and EXPECT 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. error: The function to call with any errors found.
Checks the use of CHECK and EXPECT macros.
[ "Checks", "the", "use", "of", "CHECK", "and", "EXPECT", "macros", "." ]
def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT 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. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided check_macro = None start_pos = -1 for macro in _CHECK_MACROS: i = lines[linenum].find(macro) if i >= 0: check_macro = macro # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum]) if not matched: continue start_pos = len(matched.group(1)) break if not check_macro or start_pos < 0: # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')') if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator))
[ "def", "CheckCheck", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Decide the set of replacement macros that should be suggested", "lines", "=", "clean_lines", ".", "elided", "check_macro", "=", "None", "start_pos", "=", "-", "1", "for", "macro", "in", "_CHECK_MACROS", ":", "i", "=", "lines", "[", "linenum", "]", ".", "find", "(", "macro", ")", "if", "i", ">=", "0", ":", "check_macro", "=", "macro", "# Find opening parenthesis. Do a regular expression match here", "# to make sure that we are matching the expected CHECK macro, as", "# opposed to some other macro that happens to contain the CHECK", "# substring.", "matched", "=", "Match", "(", "r'^(.*\\b'", "+", "check_macro", "+", "r'\\s*)\\('", ",", "lines", "[", "linenum", "]", ")", "if", "not", "matched", ":", "continue", "start_pos", "=", "len", "(", "matched", ".", "group", "(", "1", ")", ")", "break", "if", "not", "check_macro", "or", "start_pos", "<", "0", ":", "# Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'", "return", "# Find end of the boolean expression by matching parentheses", "(", "last_line", ",", "end_line", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "start_pos", ")", "if", "end_pos", "<", "0", ":", "return", "if", "linenum", "==", "end_line", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "end_pos", "-", "1", "]", "else", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "]", "for", "i", "in", "xrange", "(", "linenum", "+", "1", ",", "end_line", ")", ":", "expression", "+=", "lines", "[", "i", "]", "expression", "+=", "last_line", "[", "0", ":", "end_pos", "-", "1", "]", "# Parse expression so that we can take parentheses into account.", "# This avoids false positives for inputs like \"CHECK((a < 4) == b)\",", "# which is not replaceable by CHECK_LE.", "lhs", "=", "''", "rhs", "=", "''", "operator", "=", "None", "while", "expression", ":", "matched", "=", "Match", "(", "r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'", "r'==|!=|>=|>|<=|<|\\()(.*)$'", ",", "expression", ")", "if", "matched", ":", "token", "=", "matched", ".", "group", "(", "1", ")", "if", "token", "==", "'('", ":", "# Parenthesized operand", "expression", "=", "matched", ".", "group", "(", "2", ")", "(", "end", ",", "_", ")", "=", "FindEndOfExpressionInLine", "(", "expression", ",", "0", ",", "1", ",", "'('", ",", "')'", ")", "if", "end", "<", "0", ":", "return", "# Unmatched parenthesis", "lhs", "+=", "'('", "+", "expression", "[", "0", ":", "end", "]", "expression", "=", "expression", "[", "end", ":", "]", "elif", "token", "in", "(", "'&&'", ",", "'||'", ")", ":", "# Logical and/or operators. This means the expression", "# contains more than one term, for example:", "# CHECK(42 < a && a < b);", "#", "# These are not replaceable with CHECK_LE, so bail out early.", "return", "elif", "token", "in", "(", "'<<'", ",", "'<<='", ",", "'>>'", ",", "'>>='", ",", "'->*'", ",", "'->'", ")", ":", "# Non-relational operator", "lhs", "+=", "token", "expression", "=", "matched", ".", "group", "(", "2", ")", "else", ":", "# Relational operator", "operator", "=", "token", "rhs", "=", "matched", ".", "group", "(", "2", ")", "break", "else", ":", "# Unparenthesized operand. Instead of appending to lhs one character", "# at a time, we do another regular expression match to consume several", "# characters at once if possible. Trivial benchmark shows that this", "# is more efficient when the operands are longer than a single", "# character, which is generally the case.", "matched", "=", "Match", "(", "r'^([^-=!<>()&|]+)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "matched", "=", "Match", "(", "r'^(\\s*\\S)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "break", "lhs", "+=", "matched", ".", "group", "(", "1", ")", "expression", "=", "matched", ".", "group", "(", "2", ")", "# Only apply checks if we got all parts of the boolean expression", "if", "not", "(", "lhs", "and", "operator", "and", "rhs", ")", ":", "return", "# Check that rhs do not contain logical operators. We already know", "# that lhs is fine since the loop above parses out && and ||.", "if", "rhs", ".", "find", "(", "'&&'", ")", ">", "-", "1", "or", "rhs", ".", "find", "(", "'||'", ")", ">", "-", "1", ":", "return", "# At least one of the operands must be a constant literal. This is", "# to avoid suggesting replacements for unprintable things like", "# CHECK(variable != iterator)", "#", "# The following pattern matches decimal, hex integers, strings, and", "# characters (in that order).", "lhs", "=", "lhs", ".", "strip", "(", ")", "rhs", "=", "rhs", ".", "strip", "(", ")", "match_constant", "=", "r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'", "if", "Match", "(", "match_constant", ",", "lhs", ")", "or", "Match", "(", "match_constant", ",", "rhs", ")", ":", "# Note: since we know both lhs and rhs, we can provide a more", "# descriptive error message like:", "# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)", "# Instead of:", "# Consider using CHECK_EQ instead of CHECK(a == b)", "#", "# We are still keeping the less descriptive message because if lhs", "# or rhs gets long, the error message might become unreadable.", "error", "(", "filename", ",", "linenum", ",", "'readability/check'", ",", "2", ",", "'Consider using %s instead of %s(a %s b)'", "%", "(", "_CHECK_REPLACEMENT", "[", "check_macro", "]", "[", "operator", "]", ",", "check_macro", ",", "operator", ")", ")" ]
https://github.com/tum-vision/fusenet/blob/a1451be2971b348a01b0f525c2a3a7a0e215a591/scripts/cpp_lint.py#L3278-L3402
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/serial/rfc2217.py
python
Serial.write
(self, data)
return len(data)
\ Output the given byte string over the serial port. Can block if the connection is blocked. May raise SerialException if the connection is closed.
\ Output the given byte string over the serial port. Can block if the connection is blocked. May raise SerialException if the connection is closed.
[ "\\", "Output", "the", "given", "byte", "string", "over", "the", "serial", "port", ".", "Can", "block", "if", "the", "connection", "is", "blocked", ".", "May", "raise", "SerialException", "if", "the", "connection", "is", "closed", "." ]
def write(self, data): """\ Output the given byte string over the serial port. Can block if the connection is blocked. May raise SerialException if the connection is closed. """ if not self.is_open: raise portNotOpenError # XXX use protocol_socket's write with self._write_lock: try: self._socket.sendall(to_bytes(data).replace(IAC, IAC_DOUBLED)) except socket.error as e: raise SerialException("connection failed (socket error): {}".format(e)) return len(data)
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "# XXX use protocol_socket's write", "with", "self", ".", "_write_lock", ":", "try", ":", "self", ".", "_socket", ".", "sendall", "(", "to_bytes", "(", "data", ")", ".", "replace", "(", "IAC", ",", "IAC_DOUBLED", ")", ")", "except", "socket", ".", "error", "as", "e", ":", "raise", "SerialException", "(", "\"connection failed (socket error): {}\"", ".", "format", "(", "e", ")", ")", "return", "len", "(", "data", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/serial/rfc2217.py#L623-L637
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/model/coordinates.py
python
Group.setRobotModel
(self,robotModel)
return
Sets this group to contain all links of a robot model
Sets this group to contain all links of a robot model
[ "Sets", "this", "group", "to", "contain", "all", "links", "of", "a", "robot", "model" ]
def setRobotModel(self,robotModel): """Sets this group to contain all links of a robot model""" root = self.frames['root'] for i in range(robotModel.numLinks()): p = robotModel.link(i).getParent() if p >= 0: Fp = self.frames[robotModel.link(p).getName()] else: Fp = root f = self.addFrame(robotModel.link(i).getName(),worldCoordinates=robotModel.link(i).getTransform(),parent=Fp) f._data = robotModel.link(i) return
[ "def", "setRobotModel", "(", "self", ",", "robotModel", ")", ":", "root", "=", "self", ".", "frames", "[", "'root'", "]", "for", "i", "in", "range", "(", "robotModel", ".", "numLinks", "(", ")", ")", ":", "p", "=", "robotModel", ".", "link", "(", "i", ")", ".", "getParent", "(", ")", "if", "p", ">=", "0", ":", "Fp", "=", "self", ".", "frames", "[", "robotModel", ".", "link", "(", "p", ")", ".", "getName", "(", ")", "]", "else", ":", "Fp", "=", "root", "f", "=", "self", ".", "addFrame", "(", "robotModel", ".", "link", "(", "i", ")", ".", "getName", "(", ")", ",", "worldCoordinates", "=", "robotModel", ".", "link", "(", "i", ")", ".", "getTransform", "(", ")", ",", "parent", "=", "Fp", ")", "f", ".", "_data", "=", "robotModel", ".", "link", "(", "i", ")", "return" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/coordinates.py#L260-L271
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/excel/_openpyxl.py
python
_OpenpyxlWriter._convert_to_color
(cls, color_spec)
Convert ``color_spec`` to an openpyxl v2 Color object. Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' 'indexed' 'auto' 'theme' 'tint' 'index' 'type' Returns ------- color : openpyxl.styles.Color
Convert ``color_spec`` to an openpyxl v2 Color object.
[ "Convert", "color_spec", "to", "an", "openpyxl", "v2", "Color", "object", "." ]
def _convert_to_color(cls, color_spec): """ Convert ``color_spec`` to an openpyxl v2 Color object. Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' 'indexed' 'auto' 'theme' 'tint' 'index' 'type' Returns ------- color : openpyxl.styles.Color """ from openpyxl.styles import Color if isinstance(color_spec, str): return Color(color_spec) else: return Color(**color_spec)
[ "def", "_convert_to_color", "(", "cls", ",", "color_spec", ")", ":", "from", "openpyxl", ".", "styles", "import", "Color", "if", "isinstance", "(", "color_spec", ",", "str", ")", ":", "return", "Color", "(", "color_spec", ")", "else", ":", "return", "Color", "(", "*", "*", "color_spec", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/excel/_openpyxl.py#L110-L137
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/autocomp/completer.py
python
BaseCompleter.GetChooseSingle
(self)
return self._choose_single
Get whether the completer should automatically choose a selection when there is only one symbol in the completion list. @return: bool
Get whether the completer should automatically choose a selection when there is only one symbol in the completion list. @return: bool
[ "Get", "whether", "the", "completer", "should", "automatically", "choose", "a", "selection", "when", "there", "is", "only", "one", "symbol", "in", "the", "completion", "list", ".", "@return", ":", "bool" ]
def GetChooseSingle(self): """Get whether the completer should automatically choose a selection when there is only one symbol in the completion list. @return: bool """ return self._choose_single
[ "def", "GetChooseSingle", "(", "self", ")", ":", "return", "self", ".", "_choose_single" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/autocomp/completer.py#L277-L283
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
tools/stats/scribe.py
python
rds_saved_query
(query_names: Union[str, List[str]])
return invoke_rds(events)
Execute a hardcoded RDS query by name. See https://github.com/pytorch/test-infra/blob/main/aws/lambda/rds-proxy/lambda_function.py#L52 for available queries or submit a PR there to add a new one.
Execute a hardcoded RDS query by name. See https://github.com/pytorch/test-infra/blob/main/aws/lambda/rds-proxy/lambda_function.py#L52 for available queries or submit a PR there to add a new one.
[ "Execute", "a", "hardcoded", "RDS", "query", "by", "name", ".", "See", "https", ":", "//", "github", ".", "com", "/", "pytorch", "/", "test", "-", "infra", "/", "blob", "/", "main", "/", "aws", "/", "lambda", "/", "rds", "-", "proxy", "/", "lambda_function", ".", "py#L52", "for", "available", "queries", "or", "submit", "a", "PR", "there", "to", "add", "a", "new", "one", "." ]
def rds_saved_query(query_names: Union[str, List[str]]) -> Any: """ Execute a hardcoded RDS query by name. See https://github.com/pytorch/test-infra/blob/main/aws/lambda/rds-proxy/lambda_function.py#L52 for available queries or submit a PR there to add a new one. """ if not isinstance(query_names, list): query_names = [query_names] events = [] for name in query_names: events.append({"read": {"saved_query_name": name}}) return invoke_rds(events)
[ "def", "rds_saved_query", "(", "query_names", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ")", "->", "Any", ":", "if", "not", "isinstance", "(", "query_names", ",", "list", ")", ":", "query_names", "=", "[", "query_names", "]", "events", "=", "[", "]", "for", "name", "in", "query_names", ":", "events", ".", "append", "(", "{", "\"read\"", ":", "{", "\"saved_query_name\"", ":", "name", "}", "}", ")", "return", "invoke_rds", "(", "events", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/stats/scribe.py#L146-L159
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SimpleHTTPServer.py
python
SimpleHTTPRequestHandler.copyfile
(self, source, outputfile)
Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well.
Copy all data between two file objects.
[ "Copy", "all", "data", "between", "two", "file", "objects", "." ]
def copyfile(self, source, outputfile): """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. """ shutil.copyfileobj(source, outputfile)
[ "def", "copyfile", "(", "self", ",", "source", ",", "outputfile", ")", ":", "shutil", ".", "copyfileobj", "(", "source", ",", "outputfile", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SimpleHTTPServer.py#L163-L177
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/ops.py
python
Operation.type
(self)
return self._node_def.op
The type of the op (e.g. `"MatMul"`).
The type of the op (e.g. `"MatMul"`).
[ "The", "type", "of", "the", "op", "(", "e", ".", "g", ".", "MatMul", ")", "." ]
def type(self): """The type of the op (e.g. `"MatMul"`).""" return self._node_def.op
[ "def", "type", "(", "self", ")", ":", "return", "self", ".", "_node_def", ".", "op" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/ops.py#L1476-L1478
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/sign.py
python
sign.is_atom_convex
(self)
return False
Is the atom convex?
Is the atom convex?
[ "Is", "the", "atom", "convex?" ]
def is_atom_convex(self) -> bool: """Is the atom convex? """ return False
[ "def", "is_atom_convex", "(", "self", ")", "->", "bool", ":", "return", "False" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/sign.py#L46-L49
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py
python
ParserElement.validate
( self, validateTrace=[] )
Check defined expressions for valid structure, check for infinite recursive definitions.
Check defined expressions for valid structure, check for infinite recursive definitions.
[ "Check", "defined", "expressions", "for", "valid", "structure", "check", "for", "infinite", "recursive", "definitions", "." ]
def validate( self, validateTrace=[] ): """ Check defined expressions for valid structure, check for infinite recursive definitions. """ self.checkRecursion( [] )
[ "def", "validate", "(", "self", ",", "validateTrace", "=", "[", "]", ")", ":", "self", ".", "checkRecursion", "(", "[", "]", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L2167-L2171
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexers.py
python
is_empty_indexer
(indexer, arr_value: np.ndarray)
return False
Check if we have an empty indexer. Parameters ---------- indexer : object arr_value : np.ndarray Returns ------- bool
Check if we have an empty indexer.
[ "Check", "if", "we", "have", "an", "empty", "indexer", "." ]
def is_empty_indexer(indexer, arr_value: np.ndarray) -> bool: """ Check if we have an empty indexer. Parameters ---------- indexer : object arr_value : np.ndarray Returns ------- bool """ if is_list_like(indexer) and not len(indexer): return True if arr_value.ndim == 1: if not isinstance(indexer, tuple): indexer = tuple([indexer]) return any(isinstance(idx, np.ndarray) and len(idx) == 0 for idx in indexer) return False
[ "def", "is_empty_indexer", "(", "indexer", ",", "arr_value", ":", "np", ".", "ndarray", ")", "->", "bool", ":", "if", "is_list_like", "(", "indexer", ")", "and", "not", "len", "(", "indexer", ")", ":", "return", "True", "if", "arr_value", ".", "ndim", "==", "1", ":", "if", "not", "isinstance", "(", "indexer", ",", "tuple", ")", ":", "indexer", "=", "tuple", "(", "[", "indexer", "]", ")", "return", "any", "(", "isinstance", "(", "idx", ",", "np", ".", "ndarray", ")", "and", "len", "(", "idx", ")", "==", "0", "for", "idx", "in", "indexer", ")", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexers.py#L54-L73
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/nntplib.py
python
_NNTPBase.xpath
(self, id)
Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article
Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article
[ "Process", "an", "XPATH", "command", "(", "optional", "server", "extension", ")", "Arguments", ":", "-", "id", ":", "Message", "id", "of", "article", "Returns", ":", "resp", ":", "server", "response", "if", "successful", "path", ":", "directory", "path", "to", "article" ]
def xpath(self, id): """Process an XPATH command (optional server extension) Arguments: - id: Message id of article Returns: resp: server response if successful path: directory path to article """ warnings.warn("The XPATH extension is not actively used", DeprecationWarning, 2) resp = self._shortcmd('XPATH {0}'.format(id)) if not resp.startswith('223'): raise NNTPReplyError(resp) try: [resp_num, path] = resp.split() except ValueError: raise NNTPReplyError(resp) from None else: return resp, path
[ "def", "xpath", "(", "self", ",", "id", ")", ":", "warnings", ".", "warn", "(", "\"The XPATH extension is not actively used\"", ",", "DeprecationWarning", ",", "2", ")", "resp", "=", "self", ".", "_shortcmd", "(", "'XPATH {0}'", ".", "format", "(", "id", ")", ")", "if", "not", "resp", ".", "startswith", "(", "'223'", ")", ":", "raise", "NNTPReplyError", "(", "resp", ")", "try", ":", "[", "resp_num", ",", "path", "]", "=", "resp", ".", "split", "(", ")", "except", "ValueError", ":", "raise", "NNTPReplyError", "(", "resp", ")", "from", "None", "else", ":", "return", "resp", ",", "path" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/nntplib.py#L853-L871
stitchEm/stitchEm
0f399501d41ab77933677f2907f41f80ceb704d7
lib/bindings/samples/server/utils/log.py
python
set_python_log
(loglevel, use_log_file=None, rotateAtRuntime=None)
Redirect the python log to stdio or to a file
Redirect the python log to stdio or to a file
[ "Redirect", "the", "python", "log", "to", "stdio", "or", "to", "a", "file" ]
def set_python_log(loglevel, use_log_file=None, rotateAtRuntime=None): """ Redirect the python log to stdio or to a file """ loglevels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.INFO, 4: logging.DEBUG } if use_log_file: if rotateAtRuntime: # Checks if a log has already happened before configuration assert (len(logging.getLogger().handlers) == 0) fh = logging.handlers.RotatingFileHandler(PYTHON_LOG_FILE, maxBytes=10*1024*1024, backupCount=4) fh.setLevel(loglevels[loglevel]) logging.getLogger().addHandler(fh) else: logrotate(PYTHON_LOG_FILE) logging.basicConfig(filename=PYTHON_LOG_FILE, level=loglevels[loglevel]) else: logging.basicConfig(level=loglevels[loglevel]) formatter = logging.Formatter("%(asctime)s %(levelname)s [%(name)s][%(threadName)s] %(message)s") logging.getLogger().handlers[0].setFormatter(formatter)
[ "def", "set_python_log", "(", "loglevel", ",", "use_log_file", "=", "None", ",", "rotateAtRuntime", "=", "None", ")", ":", "loglevels", "=", "{", "0", ":", "logging", ".", "ERROR", ",", "1", ":", "logging", ".", "WARNING", ",", "2", ":", "logging", ".", "INFO", ",", "3", ":", "logging", ".", "INFO", ",", "4", ":", "logging", ".", "DEBUG", "}", "if", "use_log_file", ":", "if", "rotateAtRuntime", ":", "# Checks if a log has already happened before configuration", "assert", "(", "len", "(", "logging", ".", "getLogger", "(", ")", ".", "handlers", ")", "==", "0", ")", "fh", "=", "logging", ".", "handlers", ".", "RotatingFileHandler", "(", "PYTHON_LOG_FILE", ",", "maxBytes", "=", "10", "*", "1024", "*", "1024", ",", "backupCount", "=", "4", ")", "fh", ".", "setLevel", "(", "loglevels", "[", "loglevel", "]", ")", "logging", ".", "getLogger", "(", ")", ".", "addHandler", "(", "fh", ")", "else", ":", "logrotate", "(", "PYTHON_LOG_FILE", ")", "logging", ".", "basicConfig", "(", "filename", "=", "PYTHON_LOG_FILE", ",", "level", "=", "loglevels", "[", "loglevel", "]", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "loglevels", "[", "loglevel", "]", ")", "formatter", "=", "logging", ".", "Formatter", "(", "\"%(asctime)s %(levelname)s [%(name)s][%(threadName)s] %(message)s\"", ")", "logging", ".", "getLogger", "(", ")", ".", "handlers", "[", "0", "]", ".", "setFormatter", "(", "formatter", ")" ]
https://github.com/stitchEm/stitchEm/blob/0f399501d41ab77933677f2907f41f80ceb704d7/lib/bindings/samples/server/utils/log.py#L69-L93
netease-youdao/hex
d7b8773dae8dde63f3807cef1d48c017077db727
tools/make_hexium.py
python
create_archive
(input_dir, zip_file)
Creates a zip archive of the specified input directory.
Creates a zip archive of the specified input directory.
[ "Creates", "a", "zip", "archive", "of", "the", "specified", "input", "directory", "." ]
def create_archive(input_dir, zip_file): """ Creates a zip archive of the specified input directory. """ zf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) def addDir(dir): for f in os.listdir(dir): full_path = os.path.join(dir, f) if os.path.isdir(full_path): addDir(full_path) else: zf.write(full_path, os.path.relpath(full_path, \ os.path.join(input_dir, os.pardir))) addDir(input_dir) zf.close()
[ "def", "create_archive", "(", "input_dir", ",", "zip_file", ")", ":", "zf", "=", "zipfile", ".", "ZipFile", "(", "zip_file", ",", "'w'", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "def", "addDir", "(", "dir", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "dir", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "f", ")", "if", "os", ".", "path", ".", "isdir", "(", "full_path", ")", ":", "addDir", "(", "full_path", ")", "else", ":", "zf", ".", "write", "(", "full_path", ",", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "os", ".", "path", ".", "join", "(", "input_dir", ",", "os", ".", "pardir", ")", ")", ")", "addDir", "(", "input_dir", ")", "zf", ".", "close", "(", ")" ]
https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/make_hexium.py#L17-L29
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
LayerNormLSTMCell.call
(self, inputs, state)
return m, new_state
Run one step of LSTM. Args: inputs: input Tensor, 2D, batch x num_units. state: this must be a tuple of state Tensors, both `2-D`, with column sizes `c_state` and `m_state`. Returns: A tuple containing: - A `2-D, [batch x output_dim]`, Tensor representing the output of the LSTM after reading `inputs` when previous state was `state`. Here output_dim is: num_proj if num_proj was set, num_units otherwise. - Tensor(s) representing the new state of LSTM after reading `inputs` when the previous state was `state`. Same type and shape(s) as `state`. Raises: ValueError: If input size cannot be inferred from inputs via static shape inference.
Run one step of LSTM.
[ "Run", "one", "step", "of", "LSTM", "." ]
def call(self, inputs, state): """Run one step of LSTM. Args: inputs: input Tensor, 2D, batch x num_units. state: this must be a tuple of state Tensors, both `2-D`, with column sizes `c_state` and `m_state`. Returns: A tuple containing: - A `2-D, [batch x output_dim]`, Tensor representing the output of the LSTM after reading `inputs` when previous state was `state`. Here output_dim is: num_proj if num_proj was set, num_units otherwise. - Tensor(s) representing the new state of LSTM after reading `inputs` when the previous state was `state`. Same type and shape(s) as `state`. Raises: ValueError: If input size cannot be inferred from inputs via static shape inference. """ sigmoid = math_ops.sigmoid (c_prev, m_prev) = state dtype = inputs.dtype input_size = inputs.get_shape().with_rank(2).dims[1] if input_size.value is None: raise ValueError("Could not infer input size from inputs.get_shape()[-1]") scope = vs.get_variable_scope() with vs.variable_scope(scope, initializer=self._initializer) as unit_scope: # i = input_gate, j = new_input, f = forget_gate, o = output_gate lstm_matrix = self._linear( [inputs, m_prev], 4 * self._num_units, bias=True, bias_initializer=None, layer_norm=self._layer_norm) i, j, f, o = array_ops.split( value=lstm_matrix, num_or_size_splits=4, axis=1) if self._layer_norm: i = _norm(self._norm_gain, self._norm_shift, i, "input") j = _norm(self._norm_gain, self._norm_shift, j, "transform") f = _norm(self._norm_gain, self._norm_shift, f, "forget") o = _norm(self._norm_gain, self._norm_shift, o, "output") # Diagonal connections if self._use_peepholes: with vs.variable_scope(unit_scope): w_f_diag = vs.get_variable( "w_f_diag", shape=[self._num_units], dtype=dtype) w_i_diag = vs.get_variable( "w_i_diag", shape=[self._num_units], dtype=dtype) w_o_diag = vs.get_variable( "w_o_diag", shape=[self._num_units], dtype=dtype) if self._use_peepholes: c = ( sigmoid(f + self._forget_bias + w_f_diag * c_prev) * c_prev + sigmoid(i + w_i_diag * c_prev) * self._activation(j)) else: c = ( sigmoid(f + self._forget_bias) * c_prev + sigmoid(i) * self._activation(j)) if self._layer_norm: c = _norm(self._norm_gain, self._norm_shift, c, "state") if self._cell_clip is not None: # pylint: disable=invalid-unary-operand-type c = clip_ops.clip_by_value(c, -self._cell_clip, self._cell_clip) # pylint: enable=invalid-unary-operand-type if self._use_peepholes: m = sigmoid(o + w_o_diag * c) * self._activation(c) else: m = sigmoid(o) * self._activation(c) if self._num_proj is not None: with vs.variable_scope("projection"): m = self._linear(m, self._num_proj, bias=False) if self._proj_clip is not None: # pylint: disable=invalid-unary-operand-type m = clip_ops.clip_by_value(m, -self._proj_clip, self._proj_clip) # pylint: enable=invalid-unary-operand-type new_state = (rnn_cell_impl.LSTMStateTuple(c, m)) return m, new_state
[ "def", "call", "(", "self", ",", "inputs", ",", "state", ")", ":", "sigmoid", "=", "math_ops", ".", "sigmoid", "(", "c_prev", ",", "m_prev", ")", "=", "state", "dtype", "=", "inputs", ".", "dtype", "input_size", "=", "inputs", ".", "get_shape", "(", ")", ".", "with_rank", "(", "2", ")", ".", "dims", "[", "1", "]", "if", "input_size", ".", "value", "is", "None", ":", "raise", "ValueError", "(", "\"Could not infer input size from inputs.get_shape()[-1]\"", ")", "scope", "=", "vs", ".", "get_variable_scope", "(", ")", "with", "vs", ".", "variable_scope", "(", "scope", ",", "initializer", "=", "self", ".", "_initializer", ")", "as", "unit_scope", ":", "# i = input_gate, j = new_input, f = forget_gate, o = output_gate", "lstm_matrix", "=", "self", ".", "_linear", "(", "[", "inputs", ",", "m_prev", "]", ",", "4", "*", "self", ".", "_num_units", ",", "bias", "=", "True", ",", "bias_initializer", "=", "None", ",", "layer_norm", "=", "self", ".", "_layer_norm", ")", "i", ",", "j", ",", "f", ",", "o", "=", "array_ops", ".", "split", "(", "value", "=", "lstm_matrix", ",", "num_or_size_splits", "=", "4", ",", "axis", "=", "1", ")", "if", "self", ".", "_layer_norm", ":", "i", "=", "_norm", "(", "self", ".", "_norm_gain", ",", "self", ".", "_norm_shift", ",", "i", ",", "\"input\"", ")", "j", "=", "_norm", "(", "self", ".", "_norm_gain", ",", "self", ".", "_norm_shift", ",", "j", ",", "\"transform\"", ")", "f", "=", "_norm", "(", "self", ".", "_norm_gain", ",", "self", ".", "_norm_shift", ",", "f", ",", "\"forget\"", ")", "o", "=", "_norm", "(", "self", ".", "_norm_gain", ",", "self", ".", "_norm_shift", ",", "o", ",", "\"output\"", ")", "# Diagonal connections", "if", "self", ".", "_use_peepholes", ":", "with", "vs", ".", "variable_scope", "(", "unit_scope", ")", ":", "w_f_diag", "=", "vs", ".", "get_variable", "(", "\"w_f_diag\"", ",", "shape", "=", "[", "self", ".", "_num_units", "]", ",", "dtype", "=", "dtype", ")", "w_i_diag", "=", "vs", ".", "get_variable", "(", "\"w_i_diag\"", ",", "shape", "=", "[", "self", ".", "_num_units", "]", ",", "dtype", "=", "dtype", ")", "w_o_diag", "=", "vs", ".", "get_variable", "(", "\"w_o_diag\"", ",", "shape", "=", "[", "self", ".", "_num_units", "]", ",", "dtype", "=", "dtype", ")", "if", "self", ".", "_use_peepholes", ":", "c", "=", "(", "sigmoid", "(", "f", "+", "self", ".", "_forget_bias", "+", "w_f_diag", "*", "c_prev", ")", "*", "c_prev", "+", "sigmoid", "(", "i", "+", "w_i_diag", "*", "c_prev", ")", "*", "self", ".", "_activation", "(", "j", ")", ")", "else", ":", "c", "=", "(", "sigmoid", "(", "f", "+", "self", ".", "_forget_bias", ")", "*", "c_prev", "+", "sigmoid", "(", "i", ")", "*", "self", ".", "_activation", "(", "j", ")", ")", "if", "self", ".", "_layer_norm", ":", "c", "=", "_norm", "(", "self", ".", "_norm_gain", ",", "self", ".", "_norm_shift", ",", "c", ",", "\"state\"", ")", "if", "self", ".", "_cell_clip", "is", "not", "None", ":", "# pylint: disable=invalid-unary-operand-type", "c", "=", "clip_ops", ".", "clip_by_value", "(", "c", ",", "-", "self", ".", "_cell_clip", ",", "self", ".", "_cell_clip", ")", "# pylint: enable=invalid-unary-operand-type", "if", "self", ".", "_use_peepholes", ":", "m", "=", "sigmoid", "(", "o", "+", "w_o_diag", "*", "c", ")", "*", "self", ".", "_activation", "(", "c", ")", "else", ":", "m", "=", "sigmoid", "(", "o", ")", "*", "self", ".", "_activation", "(", "c", ")", "if", "self", ".", "_num_proj", "is", "not", "None", ":", "with", "vs", ".", "variable_scope", "(", "\"projection\"", ")", ":", "m", "=", "self", ".", "_linear", "(", "m", ",", "self", ".", "_num_proj", ",", "bias", "=", "False", ")", "if", "self", ".", "_proj_clip", "is", "not", "None", ":", "# pylint: disable=invalid-unary-operand-type", "m", "=", "clip_ops", ".", "clip_by_value", "(", "m", ",", "-", "self", ".", "_proj_clip", ",", "self", ".", "_proj_clip", ")", "# pylint: enable=invalid-unary-operand-type", "new_state", "=", "(", "rnn_cell_impl", ".", "LSTMStateTuple", "(", "c", ",", "m", ")", ")", "return", "m", ",", "new_state" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L2643-L2735
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/dfxml.py
python
fileobjects_dom
(xmlfile=None,imagefile=None,flags=0)
return (doc,ret)
Returns a tuple consisting of (XML,LIST) where XML is the document of the imagefile's fiwalk and LIST is a list of file objects extracted from that document.
Returns a tuple consisting of (XML,LIST) where XML is the document of the imagefile's fiwalk and LIST is a list of file objects extracted from that document.
[ "Returns", "a", "tuple", "consisting", "of", "(", "XML", "LIST", ")", "where", "XML", "is", "the", "document", "of", "the", "imagefile", "s", "fiwalk", "and", "LIST", "is", "a", "list", "of", "file", "objects", "extracted", "from", "that", "document", "." ]
def fileobjects_dom(xmlfile=None,imagefile=None,flags=0): """Returns a tuple consisting of (XML,LIST) where XML is the document of the imagefile's fiwalk and LIST is a list of file objects extracted from that document.""" import xml.dom.minidom doc = xml.dom.minidom.parseString(xmlfile.read()) ret = [] for xmlfi in doc.getElementsByTagName("fileobject"): fi = fileobject_dom(xmlfi,imagefile=imagefile) ret.append(fi) return (doc,ret)
[ "def", "fileobjects_dom", "(", "xmlfile", "=", "None", ",", "imagefile", "=", "None", ",", "flags", "=", "0", ")", ":", "import", "xml", ".", "dom", ".", "minidom", "doc", "=", "xml", ".", "dom", ".", "minidom", ".", "parseString", "(", "xmlfile", ".", "read", "(", ")", ")", "ret", "=", "[", "]", "for", "xmlfi", "in", "doc", ".", "getElementsByTagName", "(", "\"fileobject\"", ")", ":", "fi", "=", "fileobject_dom", "(", "xmlfi", ",", "imagefile", "=", "imagefile", ")", "ret", ".", "append", "(", "fi", ")", "return", "(", "doc", ",", "ret", ")" ]
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/dfxml.py#L1605-L1616
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
SimBody.setCollisionPadding
(self, padding)
return _robotsim.SimBody_setCollisionPadding(self, padding)
setCollisionPadding(SimBody self, double padding) Sets the collision padding used for contact generation. At 0 padding the simulation will be unstable for triangle mesh and point cloud geometries. A larger value is useful to maintain simulation stability for thin or soft objects. Default is 0.0025.
setCollisionPadding(SimBody self, double padding)
[ "setCollisionPadding", "(", "SimBody", "self", "double", "padding", ")" ]
def setCollisionPadding(self, padding): """ setCollisionPadding(SimBody self, double padding) Sets the collision padding used for contact generation. At 0 padding the simulation will be unstable for triangle mesh and point cloud geometries. A larger value is useful to maintain simulation stability for thin or soft objects. Default is 0.0025. """ return _robotsim.SimBody_setCollisionPadding(self, padding)
[ "def", "setCollisionPadding", "(", "self", ",", "padding", ")", ":", "return", "_robotsim", ".", "SimBody_setCollisionPadding", "(", "self", ",", "padding", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L8020-L8032
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Build.py
python
InstallContext.run_task_now
(self, tsk, postpone)
This method is called by :py:meth:`waflib.Build.InstallContext.install_files`, :py:meth:`waflib.Build.InstallContext.install_as` and :py:meth:`waflib.Build.InstallContext.symlink_as` immediately after the installation task is created. Its role is to force the immediate execution if necessary, that is when ``postpone=False`` was given.
This method is called by :py:meth:`waflib.Build.InstallContext.install_files`, :py:meth:`waflib.Build.InstallContext.install_as` and :py:meth:`waflib.Build.InstallContext.symlink_as` immediately after the installation task is created. Its role is to force the immediate execution if necessary, that is when ``postpone=False`` was given.
[ "This", "method", "is", "called", "by", ":", "py", ":", "meth", ":", "waflib", ".", "Build", ".", "InstallContext", ".", "install_files", ":", "py", ":", "meth", ":", "waflib", ".", "Build", ".", "InstallContext", ".", "install_as", "and", ":", "py", ":", "meth", ":", "waflib", ".", "Build", ".", "InstallContext", ".", "symlink_as", "immediately", "after", "the", "installation", "task", "is", "created", ".", "Its", "role", "is", "to", "force", "the", "immediate", "execution", "if", "necessary", "that", "is", "when", "postpone", "=", "False", "was", "given", "." ]
def run_task_now(self, tsk, postpone): """ This method is called by :py:meth:`waflib.Build.InstallContext.install_files`, :py:meth:`waflib.Build.InstallContext.install_as` and :py:meth:`waflib.Build.InstallContext.symlink_as` immediately after the installation task is created. Its role is to force the immediate execution if necessary, that is when ``postpone=False`` was given. """ tsk.post() if not postpone: if tsk.runnable_status() == Task.ASK_LATER: raise self.WafError('cannot post the task %r' % tsk) tsk.run()
[ "def", "run_task_now", "(", "self", ",", "tsk", ",", "postpone", ")", ":", "tsk", ".", "post", "(", ")", "if", "not", "postpone", ":", "if", "tsk", ".", "runnable_status", "(", ")", "==", "Task", ".", "ASK_LATER", ":", "raise", "self", ".", "WafError", "(", "'cannot post the task %r'", "%", "tsk", ")", "tsk", ".", "run", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Build.py#L1042-L1053
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozbuild/html_build_viewer.py
python
BuildViewerServer.add_resource_json_file
(self, key, path)
Register a resource JSON file with the server. The file will be made available under the name/key specified.
Register a resource JSON file with the server.
[ "Register", "a", "resource", "JSON", "file", "with", "the", "server", "." ]
def add_resource_json_file(self, key, path): """Register a resource JSON file with the server. The file will be made available under the name/key specified.""" self.json_files[key] = path
[ "def", "add_resource_json_file", "(", "self", ",", "key", ",", "path", ")", ":", "self", ".", "json_files", "[", "key", "]", "=", "path" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozbuild/html_build_viewer.py#L104-L108
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
python
AppleScript_Suite_Events.error
(self, _object=None, _attributes={}, **_arguments)
error: Raise an error Required argument: anything Keyword argument number: an error number Keyword argument partial_result: any partial result occurring before the error Keyword argument from_: the object that caused the error Keyword argument to: the desired class for a failed coercion Keyword argument _attributes: AppleEvent attribute dictionary
error: Raise an error Required argument: anything Keyword argument number: an error number Keyword argument partial_result: any partial result occurring before the error Keyword argument from_: the object that caused the error Keyword argument to: the desired class for a failed coercion Keyword argument _attributes: AppleEvent attribute dictionary
[ "error", ":", "Raise", "an", "error", "Required", "argument", ":", "anything", "Keyword", "argument", "number", ":", "an", "error", "number", "Keyword", "argument", "partial_result", ":", "any", "partial", "result", "occurring", "before", "the", "error", "Keyword", "argument", "from_", ":", "the", "object", "that", "caused", "the", "error", "Keyword", "argument", "to", ":", "the", "desired", "class", "for", "a", "failed", "coercion", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def error(self, _object=None, _attributes={}, **_arguments): """error: Raise an error Required argument: anything Keyword argument number: an error number Keyword argument partial_result: any partial result occurring before the error Keyword argument from_: the object that caused the error Keyword argument to: the desired class for a failed coercion Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'ascr' _subcode = 'err ' aetools.keysubst(_arguments, self._argmap_error) _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "error", "(", "self", ",", "_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'ascr'", "_subcode", "=", "'err '", "aetools", ".", "keysubst", "(", "_arguments", ",", "self", ".", "_argmap_error", ")", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py#L413-L435
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/sdist.py
python
sdist.read_manifest
(self)
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
[ "Read", "the", "manifest", "file", "(", "named", "by", "self", ".", "manifest", ")", "and", "use", "it", "to", "fill", "in", "self", ".", "filelist", "the", "list", "of", "files", "to", "include", "in", "the", "source", "distribution", "." ]
def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest, 'rb') for line in manifest: # The manifest must contain UTF-8. See #303. if not six.PY2: try: line = line.decode('UTF-8') except UnicodeDecodeError: log.warn("%r not UTF-8 decodable -- skipping" % line) continue # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: continue self.filelist.append(line) manifest.close()
[ "def", "read_manifest", "(", "self", ")", ":", "log", ".", "info", "(", "\"reading manifest file '%s'\"", ",", "self", ".", "manifest", ")", "manifest", "=", "open", "(", "self", ".", "manifest", ",", "'rb'", ")", "for", "line", "in", "manifest", ":", "# The manifest must contain UTF-8. See #303.", "if", "not", "six", ".", "PY2", ":", "try", ":", "line", "=", "line", ".", "decode", "(", "'UTF-8'", ")", "except", "UnicodeDecodeError", ":", "log", ".", "warn", "(", "\"%r not UTF-8 decodable -- skipping\"", "%", "line", ")", "continue", "# ignore comments and blank lines", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "'#'", ")", "or", "not", "line", ":", "continue", "self", ".", "filelist", ".", "append", "(", "line", ")", "manifest", ".", "close", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/sdist.py#L201-L221
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/distributed/ConnectionRepository.py
python
ConnectionRepository.disconnect
(self)
Closes the previously-established connection.
Closes the previously-established connection.
[ "Closes", "the", "previously", "-", "established", "connection", "." ]
def disconnect(self): """ Closes the previously-established connection. """ self.notify.info("Closing connection to server.") self._serverAddress = '' CConnectionRepository.disconnect(self) self.stopReaderPollTask()
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "notify", ".", "info", "(", "\"Closing connection to server.\"", ")", "self", ".", "_serverAddress", "=", "''", "CConnectionRepository", ".", "disconnect", "(", "self", ")", "self", ".", "stopReaderPollTask", "(", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/distributed/ConnectionRepository.py#L522-L529
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.srp_client_get_key_lease_interval
(self)
return self.__parse_int(self.execute_command('srp client keyleaseinterval'))
Get SRP client key lease interval (in seconds).
Get SRP client key lease interval (in seconds).
[ "Get", "SRP", "client", "key", "lease", "interval", "(", "in", "seconds", ")", "." ]
def srp_client_get_key_lease_interval(self) -> int: """Get SRP client key lease interval (in seconds).""" return self.__parse_int(self.execute_command('srp client keyleaseinterval'))
[ "def", "srp_client_get_key_lease_interval", "(", "self", ")", "->", "int", ":", "return", "self", ".", "__parse_int", "(", "self", ".", "execute_command", "(", "'srp client keyleaseinterval'", ")", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L1143-L1145
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.__reversed__
(self)
od.__reversed__() <==> reversed(od)
od.__reversed__() <==> reversed(od)
[ "od", ".", "__reversed__", "()", "<", "==", ">", "reversed", "(", "od", ")" ]
def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0]
[ "def", "__reversed__", "(", "self", ")", ":", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "0", "]", "while", "curr", "is", "not", "root", ":", "yield", "curr", "[", "2", "]", "curr", "=", "curr", "[", "0", "]" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/ordered_dict.py#L98-L104
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStrV.__add__
(self, *args)
return _snap.TStrV___add__(self, *args)
__add__(TStrV self, TStr Val) -> TStrV Parameters: Val: TStr const &
__add__(TStrV self, TStr Val) -> TStrV
[ "__add__", "(", "TStrV", "self", "TStr", "Val", ")", "-", ">", "TStrV" ]
def __add__(self, *args): """ __add__(TStrV self, TStr Val) -> TStrV Parameters: Val: TStr const & """ return _snap.TStrV___add__(self, *args)
[ "def", "__add__", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TStrV___add__", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19176-L19184
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/depends.py
python
get_module_constant
(module, symbol, default=-1, paths=None)
return extract_constant(code, symbol, default)
Find 'module' by searching 'paths', and extract 'symbol' Return 'None' if 'module' does not exist on 'paths', or it does not define 'symbol'. If the module defines 'symbol' as a constant, return the constant. Otherwise, return 'default'.
Find 'module' by searching 'paths', and extract 'symbol'
[ "Find", "module", "by", "searching", "paths", "and", "extract", "symbol" ]
def get_module_constant(module, symbol, default=-1, paths=None): """Find 'module' by searching 'paths', and extract 'symbol' Return 'None' if 'module' does not exist on 'paths', or it does not define 'symbol'. If the module defines 'symbol' as a constant, return the constant. Otherwise, return 'default'.""" try: f, path, (suffix, mode, kind) = find_module(module, paths) except ImportError: # Module doesn't exist return None try: if kind == PY_COMPILED: f.read(8) # skip magic & date code = marshal.load(f) elif kind == PY_FROZEN: code = imp.get_frozen_object(module) elif kind == PY_SOURCE: code = compile(f.read(), path, 'exec') else: # Not something we can parse; we'll have to import it. :( if module not in sys.modules: imp.load_module(module, f, path, (suffix, mode, kind)) return getattr(sys.modules[module], symbol, None) finally: if f: f.close() return extract_constant(code, symbol, default)
[ "def", "get_module_constant", "(", "module", ",", "symbol", ",", "default", "=", "-", "1", ",", "paths", "=", "None", ")", ":", "try", ":", "f", ",", "path", ",", "(", "suffix", ",", "mode", ",", "kind", ")", "=", "find_module", "(", "module", ",", "paths", ")", "except", "ImportError", ":", "# Module doesn't exist", "return", "None", "try", ":", "if", "kind", "==", "PY_COMPILED", ":", "f", ".", "read", "(", "8", ")", "# skip magic & date", "code", "=", "marshal", ".", "load", "(", "f", ")", "elif", "kind", "==", "PY_FROZEN", ":", "code", "=", "imp", ".", "get_frozen_object", "(", "module", ")", "elif", "kind", "==", "PY_SOURCE", ":", "code", "=", "compile", "(", "f", ".", "read", "(", ")", ",", "path", ",", "'exec'", ")", "else", ":", "# Not something we can parse; we'll have to import it. :(", "if", "module", "not", "in", "sys", ".", "modules", ":", "imp", ".", "load_module", "(", "module", ",", "f", ",", "path", ",", "(", "suffix", ",", "mode", ",", "kind", ")", ")", "return", "getattr", "(", "sys", ".", "modules", "[", "module", "]", ",", "symbol", ",", "None", ")", "finally", ":", "if", "f", ":", "f", ".", "close", "(", ")", "return", "extract_constant", "(", "code", ",", "symbol", ",", "default", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/depends.py#L101-L132
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/util/struct.py
python
NamedStruct.as_dict
(self)
return {attr: getattr(self, attr) for attr in self._attributes}
Returns a key-value dict for all attributes.
Returns a key-value dict for all attributes.
[ "Returns", "a", "key", "-", "value", "dict", "for", "all", "attributes", "." ]
def as_dict(self): """ Returns a key-value dict for all attributes. """ # pylint: disable=not-an-iterable return {attr: getattr(self, attr) for attr in self._attributes}
[ "def", "as_dict", "(", "self", ")", ":", "# pylint: disable=not-an-iterable", "return", "{", "attr", ":", "getattr", "(", "self", ",", "attr", ")", "for", "attr", "in", "self", ".", "_attributes", "}" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/struct.py#L185-L190
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/procrouting/proc.py
python
run_psimrcc_scf
(name, **kwargs)
return psimrcc_wfn
Function encoding sequence of PSI module calls for a PSIMRCC computation using a reference from the SCF module
Function encoding sequence of PSI module calls for a PSIMRCC computation using a reference from the SCF module
[ "Function", "encoding", "sequence", "of", "PSI", "module", "calls", "for", "a", "PSIMRCC", "computation", "using", "a", "reference", "from", "the", "SCF", "module" ]
def run_psimrcc_scf(name, **kwargs): """Function encoding sequence of PSI module calls for a PSIMRCC computation using a reference from the SCF module """ # Bypass the scf call if a reference wavefunction is given ref_wfn = kwargs.get('ref_wfn', None) if ref_wfn is None: ref_wfn = scf_helper(name, **kwargs) psimrcc_wfn = core.psimrcc(ref_wfn) # Shove variables into global space for k, v in psimrcc_wfn.variables().items(): core.set_variable(k, v) return psimrcc_wfn
[ "def", "run_psimrcc_scf", "(", "name", ",", "*", "*", "kwargs", ")", ":", "# Bypass the scf call if a reference wavefunction is given", "ref_wfn", "=", "kwargs", ".", "get", "(", "'ref_wfn'", ",", "None", ")", "if", "ref_wfn", "is", "None", ":", "ref_wfn", "=", "scf_helper", "(", "name", ",", "*", "*", "kwargs", ")", "psimrcc_wfn", "=", "core", ".", "psimrcc", "(", "ref_wfn", ")", "# Shove variables into global space", "for", "k", ",", "v", "in", "psimrcc_wfn", ".", "variables", "(", ")", ".", "items", "(", ")", ":", "core", ".", "set_variable", "(", "k", ",", "v", ")", "return", "psimrcc_wfn" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/procrouting/proc.py#L4216-L4232
facebook/fboss
60063db1df37c2ec0e7dcd0955c54885ea9bf7f0
build/fbcode_builder/CMake/make_fbpy_archive.py
python
build_zipapp
(args, path_map)
Create a self executing python binary using Python 3's built-in zipapp module. This type of Python binary is relatively simple, as zipapp is part of the standard library, but it does not support native language extensions (.so/.dll files).
Create a self executing python binary using Python 3's built-in zipapp module.
[ "Create", "a", "self", "executing", "python", "binary", "using", "Python", "3", "s", "built", "-", "in", "zipapp", "module", "." ]
def build_zipapp(args, path_map): """Create a self executing python binary using Python 3's built-in zipapp module. This type of Python binary is relatively simple, as zipapp is part of the standard library, but it does not support native language extensions (.so/.dll files). """ dest_dir = os.path.dirname(args.output) with tempfile.TemporaryDirectory(prefix="make_fbpy.", dir=dest_dir) as tmpdir: inst_dir = os.path.join(tmpdir, "tree") populate_install_tree(inst_dir, path_map) tmp_output = os.path.join(tmpdir, "output.exe") zipapp.create_archive( inst_dir, target=tmp_output, interpreter=args.python, main=args.main ) os.replace(tmp_output, args.output)
[ "def", "build_zipapp", "(", "args", ",", "path_map", ")", ":", "dest_dir", "=", "os", ".", "path", ".", "dirname", "(", "args", ".", "output", ")", "with", "tempfile", ".", "TemporaryDirectory", "(", "prefix", "=", "\"make_fbpy.\"", ",", "dir", "=", "dest_dir", ")", "as", "tmpdir", ":", "inst_dir", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"tree\"", ")", "populate_install_tree", "(", "inst_dir", ",", "path_map", ")", "tmp_output", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"output.exe\"", ")", "zipapp", ".", "create_archive", "(", "inst_dir", ",", "target", "=", "tmp_output", ",", "interpreter", "=", "args", ".", "python", ",", "main", "=", "args", ".", "main", ")", "os", ".", "replace", "(", "tmp_output", ",", "args", ".", "output", ")" ]
https://github.com/facebook/fboss/blob/60063db1df37c2ec0e7dcd0955c54885ea9bf7f0/build/fbcode_builder/CMake/make_fbpy_archive.py#L126-L143
libornovax/master_thesis_code
6eca474ed3cae673afde010caef338cf7349f839
caffe/python/caffe/coord_map.py
python
coord_map_from_to
(top_from, top_to)
Determine the coordinate mapping betweeen a top (from) and a top (to). Walk the graph to find a common ancestor while composing the coord maps for from and to until they meet. As a last step the from map is inverted.
Determine the coordinate mapping betweeen a top (from) and a top (to). Walk the graph to find a common ancestor while composing the coord maps for from and to until they meet. As a last step the from map is inverted.
[ "Determine", "the", "coordinate", "mapping", "betweeen", "a", "top", "(", "from", ")", "and", "a", "top", "(", "to", ")", ".", "Walk", "the", "graph", "to", "find", "a", "common", "ancestor", "while", "composing", "the", "coord", "maps", "for", "from", "and", "to", "until", "they", "meet", ".", "As", "a", "last", "step", "the", "from", "map", "is", "inverted", "." ]
def coord_map_from_to(top_from, top_to): """ Determine the coordinate mapping betweeen a top (from) and a top (to). Walk the graph to find a common ancestor while composing the coord maps for from and to until they meet. As a last step the from map is inverted. """ # We need to find a common ancestor of top_from and top_to. # We'll assume that all ancestors are equivalent here (otherwise the graph # is an inconsistent state (which we could improve this to check for)). # For now use a brute-force algorithm. def collect_bottoms(top): """ Collect the bottoms to walk for the coordinate mapping. The general rule is that all the bottoms of a layer can be mapped, as most layers have the same coordinate mapping for each bottom. Crop layer is a notable exception. Only the first/cropped bottom is mappable; the second/dimensions bottom is excluded from the walk. """ bottoms = top.fn.inputs if top.fn.type_name == 'Crop': bottoms = bottoms[:1] return bottoms # walk back from top_from, keeping the coord map as we go from_maps = {top_from: (None, 1, 0)} frontier = {top_from} while frontier: top = frontier.pop() try: bottoms = collect_bottoms(top) for bottom in bottoms: from_maps[bottom] = compose(from_maps[top], coord_map(top.fn)) frontier.add(bottom) except UndefinedMapException: pass # now walk back from top_to until we hit a common blob to_maps = {top_to: (None, 1, 0)} frontier = {top_to} while frontier: top = frontier.pop() if top in from_maps: return compose(to_maps[top], inverse(from_maps[top])) try: bottoms = collect_bottoms(top) for bottom in bottoms: to_maps[bottom] = compose(to_maps[top], coord_map(top.fn)) frontier.add(bottom) except UndefinedMapException: continue # if we got here, we did not find a blob in common raise RuntimeError('Could not compute map between tops; are they ' 'connected by spatial layers?')
[ "def", "coord_map_from_to", "(", "top_from", ",", "top_to", ")", ":", "# We need to find a common ancestor of top_from and top_to.", "# We'll assume that all ancestors are equivalent here (otherwise the graph", "# is an inconsistent state (which we could improve this to check for)).", "# For now use a brute-force algorithm.", "def", "collect_bottoms", "(", "top", ")", ":", "\"\"\"\n Collect the bottoms to walk for the coordinate mapping.\n The general rule is that all the bottoms of a layer can be mapped, as\n most layers have the same coordinate mapping for each bottom.\n Crop layer is a notable exception. Only the first/cropped bottom is\n mappable; the second/dimensions bottom is excluded from the walk.\n \"\"\"", "bottoms", "=", "top", ".", "fn", ".", "inputs", "if", "top", ".", "fn", ".", "type_name", "==", "'Crop'", ":", "bottoms", "=", "bottoms", "[", ":", "1", "]", "return", "bottoms", "# walk back from top_from, keeping the coord map as we go", "from_maps", "=", "{", "top_from", ":", "(", "None", ",", "1", ",", "0", ")", "}", "frontier", "=", "{", "top_from", "}", "while", "frontier", ":", "top", "=", "frontier", ".", "pop", "(", ")", "try", ":", "bottoms", "=", "collect_bottoms", "(", "top", ")", "for", "bottom", "in", "bottoms", ":", "from_maps", "[", "bottom", "]", "=", "compose", "(", "from_maps", "[", "top", "]", ",", "coord_map", "(", "top", ".", "fn", ")", ")", "frontier", ".", "add", "(", "bottom", ")", "except", "UndefinedMapException", ":", "pass", "# now walk back from top_to until we hit a common blob", "to_maps", "=", "{", "top_to", ":", "(", "None", ",", "1", ",", "0", ")", "}", "frontier", "=", "{", "top_to", "}", "while", "frontier", ":", "top", "=", "frontier", ".", "pop", "(", ")", "if", "top", "in", "from_maps", ":", "return", "compose", "(", "to_maps", "[", "top", "]", ",", "inverse", "(", "from_maps", "[", "top", "]", ")", ")", "try", ":", "bottoms", "=", "collect_bottoms", "(", "top", ")", "for", "bottom", "in", "bottoms", ":", "to_maps", "[", "bottom", "]", "=", "compose", "(", "to_maps", "[", "top", "]", ",", "coord_map", "(", "top", ".", "fn", ")", ")", "frontier", ".", "add", "(", "bottom", ")", "except", "UndefinedMapException", ":", "continue", "# if we got here, we did not find a blob in common", "raise", "RuntimeError", "(", "'Could not compute map between tops; are they '", "'connected by spatial layers?'", ")" ]
https://github.com/libornovax/master_thesis_code/blob/6eca474ed3cae673afde010caef338cf7349f839/caffe/python/caffe/coord_map.py#L115-L169
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/refactor.py
python
RefactoringTool.refactor_file
(self, filename, write=False, doctests_only=False)
Refactors a file.
Refactors a file.
[ "Refactors", "a", "file", "." ]
def refactor_file(self, filename, write=False, doctests_only=False): """Refactors a file.""" input, encoding = self._read_python_source(filename) if input is None: # Reading the file failed. return input += "\n" # Silence certain parse errors if doctests_only: self.log_debug("Refactoring doctests in %s", filename) output = self.refactor_docstring(input, filename) if self.write_unchanged_files or output != input: self.processed_file(output, filename, input, write, encoding) else: self.log_debug("No doctest changes in %s", filename) else: tree = self.refactor_string(input, filename) if self.write_unchanged_files or (tree and tree.was_changed): # The [:-1] is to take off the \n we added earlier self.processed_file(str(tree)[:-1], filename, write=write, encoding=encoding) else: self.log_debug("No changes in %s", filename)
[ "def", "refactor_file", "(", "self", ",", "filename", ",", "write", "=", "False", ",", "doctests_only", "=", "False", ")", ":", "input", ",", "encoding", "=", "self", ".", "_read_python_source", "(", "filename", ")", "if", "input", "is", "None", ":", "# Reading the file failed.", "return", "input", "+=", "\"\\n\"", "# Silence certain parse errors", "if", "doctests_only", ":", "self", ".", "log_debug", "(", "\"Refactoring doctests in %s\"", ",", "filename", ")", "output", "=", "self", ".", "refactor_docstring", "(", "input", ",", "filename", ")", "if", "self", ".", "write_unchanged_files", "or", "output", "!=", "input", ":", "self", ".", "processed_file", "(", "output", ",", "filename", ",", "input", ",", "write", ",", "encoding", ")", "else", ":", "self", ".", "log_debug", "(", "\"No doctest changes in %s\"", ",", "filename", ")", "else", ":", "tree", "=", "self", ".", "refactor_string", "(", "input", ",", "filename", ")", "if", "self", ".", "write_unchanged_files", "or", "(", "tree", "and", "tree", ".", "was_changed", ")", ":", "# The [:-1] is to take off the \\n we added earlier", "self", ".", "processed_file", "(", "str", "(", "tree", ")", "[", ":", "-", "1", "]", ",", "filename", ",", "write", "=", "write", ",", "encoding", "=", "encoding", ")", "else", ":", "self", ".", "log_debug", "(", "\"No changes in %s\"", ",", "filename", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/refactor.py#L320-L341
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py
python
ExpandWildcardDependencies
(targets, data)
Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called.
Expands dependencies specified as build_file:*.
[ "Expands", "dependencies", "specified", "as", "build_file", ":", "*", "." ]
def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.items(): target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in range" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): ( dependency_build_file, dependency_target, dependency_toolset, ) = gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != "*" and dependency_toolset != "*": # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise GypError( "Found wildcard in " + dependency_key + " of " + target + " referring to same build file" ) # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]["targets"] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get("suppress_wildcard", False)): continue dependency_target_name = dependency_target_dict["target_name"] if ( dependency_target != "*" and dependency_target != dependency_target_name ): continue dependency_target_toolset = dependency_target_dict["toolset"] if ( dependency_toolset != "*" and dependency_toolset != dependency_target_toolset ): continue dependency = gyp.common.QualifiedTarget( dependency_build_file, dependency_target_name, dependency_target_toolset, ) index = index + 1 dependencies.insert(index, dependency) index = index + 1
[ "def", "ExpandWildcardDependencies", "(", "targets", ",", "data", ")", ":", "for", "target", ",", "target_dict", "in", "targets", ".", "items", "(", ")", ":", "target_build_file", "=", "gyp", ".", "common", ".", "BuildFile", "(", "target", ")", "for", "dependency_key", "in", "dependency_sections", ":", "dependencies", "=", "target_dict", ".", "get", "(", "dependency_key", ",", "[", "]", ")", "# Loop this way instead of \"for dependency in\" or \"for index in range\"", "# because the dependencies list will be modified within the loop body.", "index", "=", "0", "while", "index", "<", "len", "(", "dependencies", ")", ":", "(", "dependency_build_file", ",", "dependency_target", ",", "dependency_toolset", ",", ")", "=", "gyp", ".", "common", ".", "ParseQualifiedTarget", "(", "dependencies", "[", "index", "]", ")", "if", "dependency_target", "!=", "\"*\"", "and", "dependency_toolset", "!=", "\"*\"", ":", "# Not a wildcard. Keep it moving.", "index", "=", "index", "+", "1", "continue", "if", "dependency_build_file", "==", "target_build_file", ":", "# It's an error for a target to depend on all other targets in", "# the same file, because a target cannot depend on itself.", "raise", "GypError", "(", "\"Found wildcard in \"", "+", "dependency_key", "+", "\" of \"", "+", "target", "+", "\" referring to same build file\"", ")", "# Take the wildcard out and adjust the index so that the next", "# dependency in the list will be processed the next time through the", "# loop.", "del", "dependencies", "[", "index", "]", "index", "=", "index", "-", "1", "# Loop through the targets in the other build file, adding them to", "# this target's list of dependencies in place of the removed", "# wildcard.", "dependency_target_dicts", "=", "data", "[", "dependency_build_file", "]", "[", "\"targets\"", "]", "for", "dependency_target_dict", "in", "dependency_target_dicts", ":", "if", "int", "(", "dependency_target_dict", ".", "get", "(", "\"suppress_wildcard\"", ",", "False", ")", ")", ":", "continue", "dependency_target_name", "=", "dependency_target_dict", "[", "\"target_name\"", "]", "if", "(", "dependency_target", "!=", "\"*\"", "and", "dependency_target", "!=", "dependency_target_name", ")", ":", "continue", "dependency_target_toolset", "=", "dependency_target_dict", "[", "\"toolset\"", "]", "if", "(", "dependency_toolset", "!=", "\"*\"", "and", "dependency_toolset", "!=", "dependency_target_toolset", ")", ":", "continue", "dependency", "=", "gyp", ".", "common", ".", "QualifiedTarget", "(", "dependency_build_file", ",", "dependency_target_name", ",", "dependency_target_toolset", ",", ")", "index", "=", "index", "+", "1", "dependencies", ".", "insert", "(", "index", ",", "dependency", ")", "index", "=", "index", "+", "1" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py#L1528-L1607
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/roundinghelper.py
python
declare_rounding_property
(o)
Declares the properties needed for rounding.
Declares the properties needed for rounding.
[ "Declares", "the", "properties", "needed", "for", "rounding", "." ]
def declare_rounding_property(o): ''' Declares the properties needed for rounding. ''' rounding = StringListValidator() rounding.addAllowedValue(ROUNDING_NONE) rounding.addAllowedValue(ROUNDING_TEN_TO_INT) o.declareProperty(name=PROP_NAME_ROUNDING_MODE, defaultValue=ROUNDING_NONE, validator=rounding, direction=Direction.Input, doc='Bin width rounding')
[ "def", "declare_rounding_property", "(", "o", ")", ":", "rounding", "=", "StringListValidator", "(", ")", "rounding", ".", "addAllowedValue", "(", "ROUNDING_NONE", ")", "rounding", ".", "addAllowedValue", "(", "ROUNDING_TEN_TO_INT", ")", "o", ".", "declareProperty", "(", "name", "=", "PROP_NAME_ROUNDING_MODE", ",", "defaultValue", "=", "ROUNDING_NONE", ",", "validator", "=", "rounding", ",", "direction", "=", "Direction", ".", "Input", ",", "doc", "=", "'Bin width rounding'", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/roundinghelper.py#L24-L33
freelan-developers/freelan
779a1421adbbfa35568cea9b212d1ba0635570e1
packaging/osx/pkgbuild.py
python
pkgbuild_generator
(target, source, env, for_signature)
return '{executable} {options_str} --root $SOURCE $TARGET'.format( executable=env['PKGBUILD'], options_str=options_str, )
The generator
The generator
[ "The", "generator" ]
def pkgbuild_generator(target, source, env, for_signature): """The generator""" options = env['PKGBUILD_OPTIONS'].value options_str = ' '.join( '--%s %s' % (key, value) for key, value in options.items() ) if env['PKGBUILD_SCRIPTS']: options_str = options_str + ' --scripts $PKGBUILD_SCRIPTS' return '{executable} {options_str} --root $SOURCE $TARGET'.format( executable=env['PKGBUILD'], options_str=options_str, )
[ "def", "pkgbuild_generator", "(", "target", ",", "source", ",", "env", ",", "for_signature", ")", ":", "options", "=", "env", "[", "'PKGBUILD_OPTIONS'", "]", ".", "value", "options_str", "=", "' '", ".", "join", "(", "'--%s %s'", "%", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "options", ".", "items", "(", ")", ")", "if", "env", "[", "'PKGBUILD_SCRIPTS'", "]", ":", "options_str", "=", "options_str", "+", "' --scripts $PKGBUILD_SCRIPTS'", "return", "'{executable} {options_str} --root $SOURCE $TARGET'", ".", "format", "(", "executable", "=", "env", "[", "'PKGBUILD'", "]", ",", "options_str", "=", "options_str", ",", ")" ]
https://github.com/freelan-developers/freelan/blob/779a1421adbbfa35568cea9b212d1ba0635570e1/packaging/osx/pkgbuild.py#L16-L31
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/misc/shapeformat.py
python
guess_utm_from_coord
(coord)
return "+proj=utm +zone=%d +ellps=WGS84 +datum=WGS84 +units=m +no_defs" % zone
Returns UTM projection parameters from an example point with coord = (lat,lon)
Returns UTM projection parameters from an example point with coord = (lat,lon)
[ "Returns", "UTM", "projection", "parameters", "from", "an", "example", "point", "with", "coord", "=", "(", "lat", "lon", ")" ]
def guess_utm_from_coord(coord): """ Returns UTM projection parameters from an example point with coord = (lat,lon) """ zone = get_zone(coord) return "+proj=utm +zone=%d +ellps=WGS84 +datum=WGS84 +units=m +no_defs" % zone
[ "def", "guess_utm_from_coord", "(", "coord", ")", ":", "zone", "=", "get_zone", "(", "coord", ")", "return", "\"+proj=utm +zone=%d +ellps=WGS84 +datum=WGS84 +units=m +no_defs\"", "%", "zone" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/misc/shapeformat.py#L120-L126
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
URI.fragment
(self)
return ret
Get the fragment part from an URI
Get the fragment part from an URI
[ "Get", "the", "fragment", "part", "from", "an", "URI" ]
def fragment(self): """Get the fragment part from an URI """ ret = libxml2mod.xmlURIGetFragment(self._o) return ret
[ "def", "fragment", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlURIGetFragment", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L6974-L6977
limbo018/DREAMPlace
146c3b9fd003d1acd52c96d9fd02e3f0a05154e4
dreamplace/BasicPlace.py
python
BasicPlace.load
(self, params, placedb, filename)
@brief dump intermediate solution as compressed pickle file (.pklz) @param params parameters @param placedb placement database @param iteration optimization step @param pos locations of cells @param filename output file name
[]
def load(self, params, placedb, filename): """ @brief dump intermediate solution as compressed pickle file (.pklz) @param params parameters @param placedb placement database @param iteration optimization step @param pos locations of cells @param filename output file name """ with gzip.open(filename, "rb") as f: data = pickle.load(f) self.data_collections.node_size_x.data = data[0].data.to( self.device) self.data_collections.node_size_y.data = data[1].data.to( self.device) self.data_collections.flat_net2pin_map.data = data[2].data.to( self.device) self.data_collections.flat_net2pin_start_map.data = data[ 3].data.to(self.device) self.data_collections.pin2net_map.data = data[4].data.to( self.device) self.data_collections.flat_node2pin_map.data = data[5].data.to( self.device) self.data_collections.flat_node2pin_start_map.data = data[ 6].data.to(self.device) self.data_collections.pin2node_map.data = data[7].data.to( self.device) self.data_collections.pin_offset_x.data = data[8].data.to( self.device) self.data_collections.pin_offset_y.data = data[9].data.to( self.device) self.data_collections.net_mask_ignore_large_degrees.data = data[ 10].data.to(self.device) placedb.xl = data[11] placedb.yl = data[12] placedb.xh = data[13] placedb.yh = data[14] placedb.site_width = data[15] placedb.row_height = data[16] placedb.num_bins_x = data[17] placedb.num_bins_y = data[18] num_movable_nodes = data[19] num_nodes = data[0].numel() placedb.num_terminal_NIs = data[20] placedb.num_filler_nodes = data[21] placedb.num_physical_nodes = num_nodes - placedb.num_filler_nodes placedb.num_terminals = placedb.num_physical_nodes - placedb.num_terminal_NIs - num_movable_nodes self.data_collections.pos[0].data = data[22].data.to(self.device)
[ "def", "load", "(", "self", ",", "params", ",", "placedb", ",", "filename", ")", ":", "with", "gzip", ".", "open", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "data", "=", "pickle", ".", "load", "(", "f", ")", "self", ".", "data_collections", ".", "node_size_x", ".", "data", "=", "data", "[", "0", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "node_size_y", ".", "data", "=", "data", "[", "1", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "flat_net2pin_map", ".", "data", "=", "data", "[", "2", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "flat_net2pin_start_map", ".", "data", "=", "data", "[", "3", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "pin2net_map", ".", "data", "=", "data", "[", "4", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "flat_node2pin_map", ".", "data", "=", "data", "[", "5", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "flat_node2pin_start_map", ".", "data", "=", "data", "[", "6", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "pin2node_map", ".", "data", "=", "data", "[", "7", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "pin_offset_x", ".", "data", "=", "data", "[", "8", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "pin_offset_y", ".", "data", "=", "data", "[", "9", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "self", ".", "data_collections", ".", "net_mask_ignore_large_degrees", ".", "data", "=", "data", "[", "10", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")", "placedb", ".", "xl", "=", "data", "[", "11", "]", "placedb", ".", "yl", "=", "data", "[", "12", "]", "placedb", ".", "xh", "=", "data", "[", "13", "]", "placedb", ".", "yh", "=", "data", "[", "14", "]", "placedb", ".", "site_width", "=", "data", "[", "15", "]", "placedb", ".", "row_height", "=", "data", "[", "16", "]", "placedb", ".", "num_bins_x", "=", "data", "[", "17", "]", "placedb", ".", "num_bins_y", "=", "data", "[", "18", "]", "num_movable_nodes", "=", "data", "[", "19", "]", "num_nodes", "=", "data", "[", "0", "]", ".", "numel", "(", ")", "placedb", ".", "num_terminal_NIs", "=", "data", "[", "20", "]", "placedb", ".", "num_filler_nodes", "=", "data", "[", "21", "]", "placedb", ".", "num_physical_nodes", "=", "num_nodes", "-", "placedb", ".", "num_filler_nodes", "placedb", ".", "num_terminals", "=", "placedb", ".", "num_physical_nodes", "-", "placedb", ".", "num_terminal_NIs", "-", "num_movable_nodes", "self", ".", "data_collections", ".", "pos", "[", "0", "]", ".", "data", "=", "data", "[", "22", "]", ".", "data", ".", "to", "(", "self", ".", "device", ")" ]
https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/BasicPlace.py#L1064-L1111
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Menu.add_cascade
(self, cnf={}, **kw)
Add hierarchical menu item.
Add hierarchical menu item.
[ "Add", "hierarchical", "menu", "item", "." ]
def add_cascade(self, cnf={}, **kw): """Add hierarchical menu item.""" self.add('cascade', cnf or kw)
[ "def", "add_cascade", "(", "self", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "self", ".", "add", "(", "'cascade'", ",", "cnf", "or", "kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L2879-L2881
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/aio/_server.py
python
Server.add_secure_port
(self, address: str, server_credentials: grpc.ServerCredentials)
return _common.validate_port_binding_result( address, self._server.add_secure_port(_common.encode(address), server_credentials))
Opens a secure port for accepting RPCs. This method may only be called before starting the server. Args: address: The address for which to open a port. if the port is 0, or not specified in the address, then the gRPC runtime will choose a port. server_credentials: A ServerCredentials object. Returns: An integer port on which the server will accept RPC requests.
Opens a secure port for accepting RPCs.
[ "Opens", "a", "secure", "port", "for", "accepting", "RPCs", "." ]
def add_secure_port(self, address: str, server_credentials: grpc.ServerCredentials) -> int: """Opens a secure port for accepting RPCs. This method may only be called before starting the server. Args: address: The address for which to open a port. if the port is 0, or not specified in the address, then the gRPC runtime will choose a port. server_credentials: A ServerCredentials object. Returns: An integer port on which the server will accept RPC requests. """ return _common.validate_port_binding_result( address, self._server.add_secure_port(_common.encode(address), server_credentials))
[ "def", "add_secure_port", "(", "self", ",", "address", ":", "str", ",", "server_credentials", ":", "grpc", ".", "ServerCredentials", ")", "->", "int", ":", "return", "_common", ".", "validate_port_binding_result", "(", "address", ",", "self", ".", "_server", ".", "add_secure_port", "(", "_common", ".", "encode", "(", "address", ")", ",", "server_credentials", ")", ")" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_server.py#L87-L105
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/protocol.py
python
TelnetProtocolParser._parse_coroutine
(self)
Parser state machine. Every 'yield' expression returns the next byte.
Parser state machine. Every 'yield' expression returns the next byte.
[ "Parser", "state", "machine", ".", "Every", "yield", "expression", "returns", "the", "next", "byte", "." ]
def _parse_coroutine(self) -> Generator[None, bytes, None]: """ Parser state machine. Every 'yield' expression returns the next byte. """ while True: d = yield if d == int2byte(0): pass # NOP # Go to state escaped. elif d == IAC: d2 = yield if d2 == IAC: self.received_data(d2) # Handle simple commands. elif d2 in (NOP, DM, BRK, IP, AO, AYT, EC, EL, GA): self.command_received(d2, b"") # Handle IAC-[DO/DONT/WILL/WONT] commands. elif d2 in (DO, DONT, WILL, WONT): d3 = yield self.command_received(d2, d3) # Subnegotiation elif d2 == SB: # Consume everything until next IAC-SE data = [] while True: d3 = yield if d3 == IAC: d4 = yield if d4 == SE: break else: data.append(d4) else: data.append(d3) self.negotiate(b"".join(data)) else: self.received_data(d)
[ "def", "_parse_coroutine", "(", "self", ")", "->", "Generator", "[", "None", ",", "bytes", ",", "None", "]", ":", "while", "True", ":", "d", "=", "yield", "if", "d", "==", "int2byte", "(", "0", ")", ":", "pass", "# NOP", "# Go to state escaped.", "elif", "d", "==", "IAC", ":", "d2", "=", "yield", "if", "d2", "==", "IAC", ":", "self", ".", "received_data", "(", "d2", ")", "# Handle simple commands.", "elif", "d2", "in", "(", "NOP", ",", "DM", ",", "BRK", ",", "IP", ",", "AO", ",", "AYT", ",", "EC", ",", "EL", ",", "GA", ")", ":", "self", ".", "command_received", "(", "d2", ",", "b\"\"", ")", "# Handle IAC-[DO/DONT/WILL/WONT] commands.", "elif", "d2", "in", "(", "DO", ",", "DONT", ",", "WILL", ",", "WONT", ")", ":", "d3", "=", "yield", "self", ".", "command_received", "(", "d2", ",", "d3", ")", "# Subnegotiation", "elif", "d2", "==", "SB", ":", "# Consume everything until next IAC-SE", "data", "=", "[", "]", "while", "True", ":", "d3", "=", "yield", "if", "d3", "==", "IAC", ":", "d4", "=", "yield", "if", "d4", "==", "SE", ":", "break", "else", ":", "data", ".", "append", "(", "d4", ")", "else", ":", "data", ".", "append", "(", "d3", ")", "self", ".", "negotiate", "(", "b\"\"", ".", "join", "(", "data", ")", ")", "else", ":", "self", ".", "received_data", "(", "d", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/telnet/protocol.py#L154-L200
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/distributed/elastic/multiprocessing/redirects.py
python
redirect
(std: str, to_file: str)
Redirects ``std`` (one of ``"stdout"`` or ``"stderr"``) to a file in the path specified by ``to_file``. This method redirects the underlying std file descriptor (not just pyton's ``sys.stdout|stderr``). See usage for details. Directory of ``dst_filename`` is assumed to exist and the destination file is overwritten if it already exists. .. note:: Due to buffering cross source writes are not guaranteed to appear in wall-clock order. For instance in the example below it is possible for the C-outputs to appear before the python outputs in the log file. Usage: :: # syntactic-sugar for redirect("stdout", "tmp/stdout.log") with redirect_stdout("/tmp/stdout.log"): print("python stdouts are redirected") libc = ctypes.CDLL("libc.so.6") libc.printf(b"c stdouts are also redirected" os.system("echo system stdouts are also redirected") print("stdout restored")
Redirects ``std`` (one of ``"stdout"`` or ``"stderr"``) to a file in the path specified by ``to_file``. This method redirects the underlying std file descriptor (not just pyton's ``sys.stdout|stderr``). See usage for details.
[ "Redirects", "std", "(", "one", "of", "stdout", "or", "stderr", ")", "to", "a", "file", "in", "the", "path", "specified", "by", "to_file", ".", "This", "method", "redirects", "the", "underlying", "std", "file", "descriptor", "(", "not", "just", "pyton", "s", "sys", ".", "stdout|stderr", ")", ".", "See", "usage", "for", "details", "." ]
def redirect(std: str, to_file: str): """ Redirects ``std`` (one of ``"stdout"`` or ``"stderr"``) to a file in the path specified by ``to_file``. This method redirects the underlying std file descriptor (not just pyton's ``sys.stdout|stderr``). See usage for details. Directory of ``dst_filename`` is assumed to exist and the destination file is overwritten if it already exists. .. note:: Due to buffering cross source writes are not guaranteed to appear in wall-clock order. For instance in the example below it is possible for the C-outputs to appear before the python outputs in the log file. Usage: :: # syntactic-sugar for redirect("stdout", "tmp/stdout.log") with redirect_stdout("/tmp/stdout.log"): print("python stdouts are redirected") libc = ctypes.CDLL("libc.so.6") libc.printf(b"c stdouts are also redirected" os.system("echo system stdouts are also redirected") print("stdout restored") """ if std not in _VALID_STD: raise ValueError( f"unknown standard stream <{std}>, must be one of {_VALID_STD}" ) c_std = _c_std(std) python_std = _python_std(std) std_fd = python_std.fileno() def _redirect(dst): libc.fflush(c_std) python_std.flush() os.dup2(dst.fileno(), std_fd) with os.fdopen(os.dup(std_fd)) as orig_std, open(to_file, mode="w+b") as dst: _redirect(dst) yield _redirect(orig_std)
[ "def", "redirect", "(", "std", ":", "str", ",", "to_file", ":", "str", ")", ":", "if", "std", "not", "in", "_VALID_STD", ":", "raise", "ValueError", "(", "f\"unknown standard stream <{std}>, must be one of {_VALID_STD}\"", ")", "c_std", "=", "_c_std", "(", "std", ")", "python_std", "=", "_python_std", "(", "std", ")", "std_fd", "=", "python_std", ".", "fileno", "(", ")", "def", "_redirect", "(", "dst", ")", ":", "libc", ".", "fflush", "(", "c_std", ")", "python_std", ".", "flush", "(", ")", "os", ".", "dup2", "(", "dst", ".", "fileno", "(", ")", ",", "std_fd", ")", "with", "os", ".", "fdopen", "(", "os", ".", "dup", "(", "std_fd", ")", ")", "as", "orig_std", ",", "open", "(", "to_file", ",", "mode", "=", "\"w+b\"", ")", "as", "dst", ":", "_redirect", "(", "dst", ")", "yield", "_redirect", "(", "orig_std", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/distributed/elastic/multiprocessing/redirects.py#L50-L97
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/controlflow.py
python
ControlFlowAnalysis.iterliveblocks
(self)
Return all live blocks in sequence of occurrence
Return all live blocks in sequence of occurrence
[ "Return", "all", "live", "blocks", "in", "sequence", "of", "occurrence" ]
def iterliveblocks(self): """ Return all live blocks in sequence of occurrence """ for i in self.blockseq: if i in self.liveblocks: yield self.blocks[i]
[ "def", "iterliveblocks", "(", "self", ")", ":", "for", "i", "in", "self", ".", "blockseq", ":", "if", "i", "in", "self", ".", "liveblocks", ":", "yield", "self", ".", "blocks", "[", "i", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/controlflow.py#L660-L666
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/rook/rook_cluster.py
python
KubernetesResource._fetch
(self)
return metadata.resource_version
Execute the requested api method as a one-off fetch
Execute the requested api method as a one-off fetch
[ "Execute", "the", "requested", "api", "method", "as", "a", "one", "-", "off", "fetch" ]
def _fetch(self) -> str: """ Execute the requested api method as a one-off fetch""" response = self.api_func(**self.kwargs) metadata = response.metadata self._items = {item.metadata.name: item for item in response.items} log.info('Full fetch of {}. result: {}'.format(self.api_func, len(self._items))) return metadata.resource_version
[ "def", "_fetch", "(", "self", ")", "->", "str", ":", "response", "=", "self", ".", "api_func", "(", "*", "*", "self", ".", "kwargs", ")", "metadata", "=", "response", ".", "metadata", "self", ".", "_items", "=", "{", "item", ".", "metadata", ".", "name", ":", "item", "for", "item", "in", "response", ".", "items", "}", "log", ".", "info", "(", "'Full fetch of {}. result: {}'", ".", "format", "(", "self", ".", "api_func", ",", "len", "(", "self", ".", "_items", ")", ")", ")", "return", "metadata", ".", "resource_version" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/rook/rook_cluster.py#L240-L246
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic.py
python
Expression.isConstant
(self)
Returns true if this expression is identically a constant. If so, then the expression can be safely replaced with its evalf() value without any possible change in meaning.
Returns true if this expression is identically a constant. If so, then the expression can be safely replaced with its evalf() value without any possible change in meaning.
[ "Returns", "true", "if", "this", "expression", "is", "identically", "a", "constant", ".", "If", "so", "then", "the", "expression", "can", "be", "safely", "replaced", "with", "its", "evalf", "()", "value", "without", "any", "possible", "change", "in", "meaning", "." ]
def isConstant(self): """Returns true if this expression is identically a constant. If so, then the expression can be safely replaced with its evalf() value without any possible change in meaning. """ raise NotImplementedError()
[ "def", "isConstant", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic.py#L2537-L2542
AojunZhou/Incremental-Network-Quantization
c7f6a609d5817d8424ce224209cf4c50f1e4de50
scripts/cpp_lint.py
python
_VerboseLevel
()
return _cpplint_state.verbose_level
Returns the module's verbosity setting.
Returns the module's verbosity setting.
[ "Returns", "the", "module", "s", "verbosity", "setting", "." ]
def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level
[ "def", "_VerboseLevel", "(", ")", ":", "return", "_cpplint_state", ".", "verbose_level" ]
https://github.com/AojunZhou/Incremental-Network-Quantization/blob/c7f6a609d5817d8424ce224209cf4c50f1e4de50/scripts/cpp_lint.py#L777-L779