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
commaai/openpilot
4416c21b1e738ab7d04147c5ae52b5135e0cdb40
pyextra/acados_template/acados_ocp.py
python
AcadosOcpCost.Zu_e
(self)
return self.__Zu_e
:math:`Z_u^e` - diagonal of Hessian wrt upper slack at terminal shooting node (N). Default: :code:`np.array([])`.
:math:`Z_u^e` - diagonal of Hessian wrt upper slack at terminal shooting node (N). Default: :code:`np.array([])`.
[ ":", "math", ":", "Z_u^e", "-", "diagonal", "of", "Hessian", "wrt", "upper", "slack", "at", "terminal", "shooting", "node", "(", "N", ")", ".", "Default", ":", ":", "code", ":", "np", ".", "array", "(", "[]", ")", "." ]
def Zu_e(self): """:math:`Z_u^e` - diagonal of Hessian wrt upper slack at terminal shooting node (N). Default: :code:`np.array([])`. """ return self.__Zu_e
[ "def", "Zu_e", "(", "self", ")", ":", "return", "self", ".", "__Zu_e" ]
https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L862-L866
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
FileType.SetDefaultIcon
(*args, **kwargs)
return _misc_.FileType_SetDefaultIcon(*args, **kwargs)
SetDefaultIcon(self, String cmd=EmptyString, int index=0) -> bool
SetDefaultIcon(self, String cmd=EmptyString, int index=0) -> bool
[ "SetDefaultIcon", "(", "self", "String", "cmd", "=", "EmptyString", "int", "index", "=", "0", ")", "-", ">", "bool" ]
def SetDefaultIcon(*args, **kwargs): """SetDefaultIcon(self, String cmd=EmptyString, int index=0) -> bool""" return _misc_.FileType_SetDefaultIcon(*args, **kwargs)
[ "def", "SetDefaultIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "FileType_SetDefaultIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2621-L2623
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py
python
WorldWideWeb_suite_Events.list_windows
(self, _no_object=None, _attributes={}, **_arguments)
list windows: Lists the IDs of all the hypertext windows Keyword argument _attributes: AppleEvent attribute dictionary Returns: List of unique IDs of all the hypertext windows
list windows: Lists the IDs of all the hypertext windows Keyword argument _attributes: AppleEvent attribute dictionary Returns: List of unique IDs of all the hypertext windows
[ "list", "windows", ":", "Lists", "the", "IDs", "of", "all", "the", "hypertext", "windows", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary", "Returns", ":", "List", "of", "unique", "IDs", "of", "all", "the", "hypertext", "windows" ]
def list_windows(self, _no_object=None, _attributes={}, **_arguments): """list windows: Lists the IDs of all the hypertext windows Keyword argument _attributes: AppleEvent attribute dictionary Returns: List of unique IDs of all the hypertext windows """ _code = 'WWW!' _subcode = 'LSTW' if _arguments: raise TypeError, 'No optional args expected' if _no_object is not None: raise TypeError, 'No direct arg expected' _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", "list_windows", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'WWW!'", "_subcode", "=", "'LSTW'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "if", "_no_object", "is", "not", "None", ":", "raise", "TypeError", ",", "'No direct arg expected'", "_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/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py#L148-L166
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBModule.FindTypes
(self, *args)
return _lldb.SBModule_FindTypes(self, *args)
FindTypes(self, str type) -> SBTypeList
FindTypes(self, str type) -> SBTypeList
[ "FindTypes", "(", "self", "str", "type", ")", "-", ">", "SBTypeList" ]
def FindTypes(self, *args): """FindTypes(self, str type) -> SBTypeList""" return _lldb.SBModule_FindTypes(self, *args)
[ "def", "FindTypes", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBModule_FindTypes", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L6170-L6172
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
DateTime.Now
(*args, **kwargs)
return _misc_.DateTime_Now(*args, **kwargs)
Now() -> DateTime
Now() -> DateTime
[ "Now", "()", "-", ">", "DateTime" ]
def Now(*args, **kwargs): """Now() -> DateTime""" return _misc_.DateTime_Now(*args, **kwargs)
[ "def", "Now", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_Now", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3766-L3768
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/compileall.py
python
main
()
return success
Script main program.
Script main program.
[ "Script", "main", "program", "." ]
def main(): """Script main program.""" import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:i:') except getopt.error, msg: print msg print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \ "[-x regexp] [-i list] [directory|file ...]" print print "arguments: zero or more file and directory names to compile; " \ "if no arguments given, " print " defaults to the equivalent of -l sys.path" print print "options:" print "-l: don't recurse into subdirectories" print "-f: force rebuild even if timestamps are up-to-date" print "-q: output only error messages" print "-d destdir: directory to prepend to file paths for use in " \ "compile-time tracebacks and in" print " runtime tracebacks in cases where the source " \ "file is unavailable" print "-x regexp: skip files matching the regular expression regexp; " \ "the regexp is searched for" print " in the full path of each file considered for " \ "compilation" print "-i file: add all the files and directories listed in file to " \ "the list considered for" print ' compilation; if "-", names are read from stdin' sys.exit(2) maxlevels = 10 ddir = None force = 0 quiet = 0 rx = None flist = None for o, a in opts: if o == '-l': maxlevels = 0 if o == '-d': ddir = a if o == '-f': force = 1 if o == '-q': quiet = 1 if o == '-x': import re rx = re.compile(a) if o == '-i': flist = a if ddir: if len(args) != 1 and not os.path.isdir(args[0]): print "-d destdir require exactly one directory argument" sys.exit(2) success = 1 try: if args or flist: try: if flist: args = expand_args(args, flist) except IOError: success = 0 if success: for arg in args: if os.path.isdir(arg): if not compile_dir(arg, maxlevels, ddir, force, rx, quiet): success = 0 else: if not compile_file(arg, ddir, force, rx, quiet): success = 0 else: success = compile_path() except KeyboardInterrupt: print "\n[interrupted]" success = 0 return success
[ "def", "main", "(", ")", ":", "import", "getopt", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'lfqd:x:i:'", ")", "except", "getopt", ".", "error", ",", "msg", ":", "print", "msg", "print", "\"usage: python compileall.py [-l] [-f] [-q] [-d destdir] \"", "\"[-x regexp] [-i list] [directory|file ...]\"", "print", "print", "\"arguments: zero or more file and directory names to compile; \"", "\"if no arguments given, \"", "print", "\" defaults to the equivalent of -l sys.path\"", "print", "print", "\"options:\"", "print", "\"-l: don't recurse into subdirectories\"", "print", "\"-f: force rebuild even if timestamps are up-to-date\"", "print", "\"-q: output only error messages\"", "print", "\"-d destdir: directory to prepend to file paths for use in \"", "\"compile-time tracebacks and in\"", "print", "\" runtime tracebacks in cases where the source \"", "\"file is unavailable\"", "print", "\"-x regexp: skip files matching the regular expression regexp; \"", "\"the regexp is searched for\"", "print", "\" in the full path of each file considered for \"", "\"compilation\"", "print", "\"-i file: add all the files and directories listed in file to \"", "\"the list considered for\"", "print", "' compilation; if \"-\", names are read from stdin'", "sys", ".", "exit", "(", "2", ")", "maxlevels", "=", "10", "ddir", "=", "None", "force", "=", "0", "quiet", "=", "0", "rx", "=", "None", "flist", "=", "None", "for", "o", ",", "a", "in", "opts", ":", "if", "o", "==", "'-l'", ":", "maxlevels", "=", "0", "if", "o", "==", "'-d'", ":", "ddir", "=", "a", "if", "o", "==", "'-f'", ":", "force", "=", "1", "if", "o", "==", "'-q'", ":", "quiet", "=", "1", "if", "o", "==", "'-x'", ":", "import", "re", "rx", "=", "re", ".", "compile", "(", "a", ")", "if", "o", "==", "'-i'", ":", "flist", "=", "a", "if", "ddir", ":", "if", "len", "(", "args", ")", "!=", "1", "and", "not", "os", ".", "path", ".", "isdir", "(", "args", "[", "0", "]", ")", ":", "print", "\"-d destdir require exactly one directory argument\"", "sys", ".", "exit", "(", "2", ")", "success", "=", "1", "try", ":", "if", "args", "or", "flist", ":", "try", ":", "if", "flist", ":", "args", "=", "expand_args", "(", "args", ",", "flist", ")", "except", "IOError", ":", "success", "=", "0", "if", "success", ":", "for", "arg", "in", "args", ":", "if", "os", ".", "path", ".", "isdir", "(", "arg", ")", ":", "if", "not", "compile_dir", "(", "arg", ",", "maxlevels", ",", "ddir", ",", "force", ",", "rx", ",", "quiet", ")", ":", "success", "=", "0", "else", ":", "if", "not", "compile_file", "(", "arg", ",", "ddir", ",", "force", ",", "rx", ",", "quiet", ")", ":", "success", "=", "0", "else", ":", "success", "=", "compile_path", "(", ")", "except", "KeyboardInterrupt", ":", "print", "\"\\n[interrupted]\"", "success", "=", "0", "return", "success" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/compileall.py#L153-L225
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/distributed/helper.py
python
synchronized
(func: Callable)
return wrapper
r"""Decorator. Decorated function will synchronize when finished. Specifically, we use this to prevent data race during hub.load
r"""Decorator. Decorated function will synchronize when finished. Specifically, we use this to prevent data race during hub.load
[ "r", "Decorator", ".", "Decorated", "function", "will", "synchronize", "when", "finished", ".", "Specifically", "we", "use", "this", "to", "prevent", "data", "race", "during", "hub", ".", "load" ]
def synchronized(func: Callable): r"""Decorator. Decorated function will synchronize when finished. Specifically, we use this to prevent data race during hub.load """ @functools.wraps(func) def wrapper(*args, **kwargs): if not is_distributed(): return func(*args, **kwargs) ret = func(*args, **kwargs) group_barrier() return ret return wrapper
[ "def", "synchronized", "(", "func", ":", "Callable", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_distributed", "(", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "ret", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "group_barrier", "(", ")", "return", "ret", "return", "wrapper" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/distributed/helper.py#L166-L180
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/max-stack.py
python
MaxStack.popMax
(self)
return val
:rtype: int
:rtype: int
[ ":", "rtype", ":", "int" ]
def popMax(self): """ :rtype: int """ val = self.__max self.__remove(val) return val
[ "def", "popMax", "(", "self", ")", ":", "val", "=", "self", ".", "__max", "self", ".", "__remove", "(", "val", ")", "return", "val" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/max-stack.py#L58-L64
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
RasterAttributeTable.DumpReadable
(self, *args)
return _gdal.RasterAttributeTable_DumpReadable(self, *args)
r"""DumpReadable(RasterAttributeTable self)
r"""DumpReadable(RasterAttributeTable self)
[ "r", "DumpReadable", "(", "RasterAttributeTable", "self", ")" ]
def DumpReadable(self, *args): r"""DumpReadable(RasterAttributeTable self)""" return _gdal.RasterAttributeTable_DumpReadable(self, *args)
[ "def", "DumpReadable", "(", "self", ",", "*", "args", ")", ":", "return", "_gdal", ".", "RasterAttributeTable_DumpReadable", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3886-L3888
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mimetypes.py
python
add_type
(type, ext, strict=True)
return _db.add_type(type, ext, strict)
Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types.
Add a mapping between a type and an extension.
[ "Add", "a", "mapping", "between", "a", "type", "and", "an", "extension", "." ]
def add_type(type, ext, strict=True): """Add a mapping between a type and an extension. When the extension is already known, the new type will replace the old one. When the type is already known the extension will be added to the list of known extensions. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ if _db is None: init() return _db.add_type(type, ext, strict)
[ "def", "add_type", "(", "type", ",", "ext", ",", "strict", "=", "True", ")", ":", "if", "_db", "is", "None", ":", "init", "(", ")", "return", "_db", ".", "add_type", "(", "type", ",", "ext", ",", "strict", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mimetypes.py#L330-L344
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/req/req_file.py
python
preprocess
(content, options)
return lines_enum
Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file :param options: cli options
Split, filter, and join lines, and return a line iterator
[ "Split", "filter", "and", "join", "lines", "and", "return", "a", "line", "iterator" ]
def preprocess(content, options): # type: (Text, Optional[optparse.Values]) -> ReqFileLines """Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file :param options: cli options """ lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines lines_enum = join_lines(lines_enum) lines_enum = ignore_comments(lines_enum) lines_enum = skip_regex(lines_enum, options) lines_enum = expand_env_variables(lines_enum) return lines_enum
[ "def", "preprocess", "(", "content", ",", "options", ")", ":", "# type: (Text, Optional[optparse.Values]) -> ReqFileLines", "lines_enum", "=", "enumerate", "(", "content", ".", "splitlines", "(", ")", ",", "start", "=", "1", ")", "# type: ReqFileLines", "lines_enum", "=", "join_lines", "(", "lines_enum", ")", "lines_enum", "=", "ignore_comments", "(", "lines_enum", ")", "lines_enum", "=", "skip_regex", "(", "lines_enum", ",", "options", ")", "lines_enum", "=", "expand_env_variables", "(", "lines_enum", ")", "return", "lines_enum" ]
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/_internal/req/req_file.py#L116-L128
quantOS-org/DataCore
e2ef9bd2c22ee9e2845675b6435a14fa607f3551
dataserver/api/py/data_api.py
python
DataApi.query
(self, view, filter="", fields="", data_format="", **kwargs)
return self._call_rpc("jset.query", self._get_format(data_format, "pandas"), "JSetData", view=view, fields=fields, filter=filter, **kwargs)
Get various reference data. Parameters ---------- view : str data source. fields : str Separated by ',' filter : str filter expressions. kwargs Returns ------- df : pd.DataFrame msg : str error code and error message, joined by ',' Examples -------- res3, msg3 = ds.query("lb.secDailyIndicator", fields="price_level,high_52w_adj,low_52w_adj",\ filter="start_date=20170907&end_date=20170907",\ data_format='pandas') view does not change. fileds can be any field predefined in reference data api.
Get various reference data. Parameters ---------- view : str data source. fields : str Separated by ',' filter : str filter expressions. kwargs
[ "Get", "various", "reference", "data", ".", "Parameters", "----------", "view", ":", "str", "data", "source", ".", "fields", ":", "str", "Separated", "by", "filter", ":", "str", "filter", "expressions", ".", "kwargs" ]
def query(self, view, filter="", fields="", data_format="", **kwargs): """ Get various reference data. Parameters ---------- view : str data source. fields : str Separated by ',' filter : str filter expressions. kwargs Returns ------- df : pd.DataFrame msg : str error code and error message, joined by ',' Examples -------- res3, msg3 = ds.query("lb.secDailyIndicator", fields="price_level,high_52w_adj,low_52w_adj",\ filter="start_date=20170907&end_date=20170907",\ data_format='pandas') view does not change. fileds can be any field predefined in reference data api. """ return self._call_rpc("jset.query", self._get_format(data_format, "pandas"), "JSetData", view=view, fields=fields, filter=filter, **kwargs)
[ "def", "query", "(", "self", ",", "view", ",", "filter", "=", "\"\"", ",", "fields", "=", "\"\"", ",", "data_format", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_call_rpc", "(", "\"jset.query\"", ",", "self", ".", "_get_format", "(", "data_format", ",", "\"pandas\"", ")", ",", "\"JSetData\"", ",", "view", "=", "view", ",", "fields", "=", "fields", ",", "filter", "=", "filter", ",", "*", "*", "kwargs", ")" ]
https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/dataserver/api/py/data_api.py#L353-L387
LiXizhi/NPLRuntime
a42720e5fe9a6960e0a9ce40bbbcd809192906be
Client/trunk/externals/assimp-4.0.0/port/PyAssimp/scripts/transformations.py
python
inverse_matrix
(matrix)
return numpy.linalg.inv(matrix)
Return inverse of square transformation matrix. >>> M0 = random_rotation_matrix() >>> M1 = inverse_matrix(M0.T) >>> numpy.allclose(M1, numpy.linalg.inv(M0.T)) True >>> for size in range(1, 7): ... M0 = numpy.random.rand(size, size) ... M1 = inverse_matrix(M0) ... if not numpy.allclose(M1, numpy.linalg.inv(M0)): print size
Return inverse of square transformation matrix.
[ "Return", "inverse", "of", "square", "transformation", "matrix", "." ]
def inverse_matrix(matrix): """Return inverse of square transformation matrix. >>> M0 = random_rotation_matrix() >>> M1 = inverse_matrix(M0.T) >>> numpy.allclose(M1, numpy.linalg.inv(M0.T)) True >>> for size in range(1, 7): ... M0 = numpy.random.rand(size, size) ... M1 = inverse_matrix(M0) ... if not numpy.allclose(M1, numpy.linalg.inv(M0)): print size """ return numpy.linalg.inv(matrix)
[ "def", "inverse_matrix", "(", "matrix", ")", ":", "return", "numpy", ".", "linalg", ".", "inv", "(", "matrix", ")" ]
https://github.com/LiXizhi/NPLRuntime/blob/a42720e5fe9a6960e0a9ce40bbbcd809192906be/Client/trunk/externals/assimp-4.0.0/port/PyAssimp/scripts/transformations.py#L1633-L1646
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exodus3.in.py
python
exodus.put_set_params
(self, object_type, object_id, numSetEntity, numSetDistFacts=None)
initialize a new set of the specified type >>> exo.put_set_params('EX_NODE_SET', node_set_id, ... num_ns_nodes, num_ns_dist_facts) Parameters ---------- set_id : int set *ID* (not *INDEX*) num_set_entity : int number of nodes/edges/faces/elements to be added to set num_dist_facts : int, optional number of distribution factors (e.g. nodal 'weights') -- must be equal to zero or num_set_entity
initialize a new set of the specified type
[ "initialize", "a", "new", "set", "of", "the", "specified", "type" ]
def put_set_params(self, object_type, object_id, numSetEntity, numSetDistFacts=None): """ initialize a new set of the specified type >>> exo.put_set_params('EX_NODE_SET', node_set_id, ... num_ns_nodes, num_ns_dist_facts) Parameters ---------- set_id : int set *ID* (not *INDEX*) num_set_entity : int number of nodes/edges/faces/elements to be added to set num_dist_facts : int, optional number of distribution factors (e.g. nodal 'weights') -- must be equal to zero or num_set_entity """ if numSetDistFacts is None: numSetDistFacts = numSetEntity assert numSetDistFacts in (0, numSetEntity) self.__ex_put_set_param(object_type, object_id, numSetEntity, numSetDistFacts)
[ "def", "put_set_params", "(", "self", ",", "object_type", ",", "object_id", ",", "numSetEntity", ",", "numSetDistFacts", "=", "None", ")", ":", "if", "numSetDistFacts", "is", "None", ":", "numSetDistFacts", "=", "numSetEntity", "assert", "numSetDistFacts", "in", "(", "0", ",", "numSetEntity", ")", "self", ".", "__ex_put_set_param", "(", "object_type", ",", "object_id", ",", "numSetEntity", ",", "numSetDistFacts", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L3602-L3622
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
tools/extra/plot_loss_trends.py
python
TrainLog.lrs
(self)
return self._multi_lrs
get lrs data showed within log file
get lrs data showed within log file
[ "get", "lrs", "data", "showed", "within", "log", "file" ]
def lrs(self): '''get lrs data showed within log file''' return self._multi_lrs
[ "def", "lrs", "(", "self", ")", ":", "return", "self", ".", "_multi_lrs" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/tools/extra/plot_loss_trends.py#L112-L114
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/distributed/DistributedObjectOV.py
python
DistributedObjectOV.generateInit
(self)
This method is called when the DistributedObjectOV is first introduced to the world... Not when it is pulled from the cache.
This method is called when the DistributedObjectOV is first introduced to the world... Not when it is pulled from the cache.
[ "This", "method", "is", "called", "when", "the", "DistributedObjectOV", "is", "first", "introduced", "to", "the", "world", "...", "Not", "when", "it", "is", "pulled", "from", "the", "cache", "." ]
def generateInit(self): """ This method is called when the DistributedObjectOV is first introduced to the world... Not when it is pulled from the cache. """ self.activeState = ESGenerating
[ "def", "generateInit", "(", "self", ")", ":", "self", ".", "activeState", "=", "ESGenerating" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/distributed/DistributedObjectOV.py#L134-L139
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py
python
FakeOsModule._fdopen
(self, *args, **kwargs)
return FakeFileOpen(self.filesystem)(*args, **kwargs)
Redirector to open() builtin function. Args: *args: pass through args **kwargs: pass through kwargs Returns: File object corresponding to file_des. Raises: TypeError: if file descriptor is not an integer.
Redirector to open() builtin function.
[ "Redirector", "to", "open", "()", "builtin", "function", "." ]
def _fdopen(self, *args, **kwargs): """Redirector to open() builtin function. Args: *args: pass through args **kwargs: pass through kwargs Returns: File object corresponding to file_des. Raises: TypeError: if file descriptor is not an integer. """ if not isinstance(args[0], int): raise TypeError('an integer is required') return FakeFileOpen(self.filesystem)(*args, **kwargs)
[ "def", "_fdopen", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "args", "[", "0", "]", ",", "int", ")", ":", "raise", "TypeError", "(", "'an integer is required'", ")", "return", "FakeFileOpen", "(", "self", ".", "filesystem", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L1173-L1188
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py
python
BaseMonitor.post_step
(self, step, session)
Callback after the step is finished. Called after step_end and receives session to perform extra session.run calls. If failure occurred in the process, will be called as well. Args: step: `int`, global step of the model. session: `Session` object.
Callback after the step is finished.
[ "Callback", "after", "the", "step", "is", "finished", "." ]
def post_step(self, step, session): # pylint: disable=unused-argument """Callback after the step is finished. Called after step_end and receives session to perform extra session.run calls. If failure occurred in the process, will be called as well. Args: step: `int`, global step of the model. session: `Session` object. """ _ = step, session
[ "def", "post_step", "(", "self", ",", "step", ",", "session", ")", ":", "# pylint: disable=unused-argument", "_", "=", "step", ",", "session" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L250-L260
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/configprovider.py
python
ChainProvider.provide
(self)
return None
Provide the value from the first provider to return non-None. Each provider in the chain has its provide method called. The first one in the chain to return a non-None value is the returned from the ChainProvider. When no non-None value is found, None is returned.
Provide the value from the first provider to return non-None.
[ "Provide", "the", "value", "from", "the", "first", "provider", "to", "return", "non", "-", "None", "." ]
def provide(self): """Provide the value from the first provider to return non-None. Each provider in the chain has its provide method called. The first one in the chain to return a non-None value is the returned from the ChainProvider. When no non-None value is found, None is returned. """ for provider in self._providers: value = provider.provide() if value is not None: return self._convert_type(value) return None
[ "def", "provide", "(", "self", ")", ":", "for", "provider", "in", "self", ".", "_providers", ":", "value", "=", "provider", ".", "provide", "(", ")", "if", "value", "is", "not", "None", ":", "return", "self", ".", "_convert_type", "(", "value", ")", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/configprovider.py#L382-L393
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
python
SequenceQueueingStateSaver.prefetch_op
(self)
return self._prefetch_op
The op used to prefetch new data into the state saver. Running it once enqueues one new input example into the state saver. The first time this gets called, it additionally creates the prefetch_op. Subsequent calls simply return the previously created `prefetch_op`. It should be run in a separate thread via e.g. a `QueueRunner`. Returns: An `Operation` that performs prefetching.
The op used to prefetch new data into the state saver.
[ "The", "op", "used", "to", "prefetch", "new", "data", "into", "the", "state", "saver", "." ]
def prefetch_op(self): """The op used to prefetch new data into the state saver. Running it once enqueues one new input example into the state saver. The first time this gets called, it additionally creates the prefetch_op. Subsequent calls simply return the previously created `prefetch_op`. It should be run in a separate thread via e.g. a `QueueRunner`. Returns: An `Operation` that performs prefetching. """ if not self._prefetch_op: with ops.name_scope(None), ops.name_scope( self._scope, values=[self._barrier.barrier_ref]): self._create_prefetch_op() return self._prefetch_op
[ "def", "prefetch_op", "(", "self", ")", ":", "if", "not", "self", ".", "_prefetch_op", ":", "with", "ops", ".", "name_scope", "(", "None", ")", ",", "ops", ".", "name_scope", "(", "self", ".", "_scope", ",", "values", "=", "[", "self", ".", "_barrier", ".", "barrier_ref", "]", ")", ":", "self", ".", "_create_prefetch_op", "(", ")", "return", "self", ".", "_prefetch_op" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L904-L920
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
tools/check_op_benchmark_result.py
python
check_accuracy_result
(case_name, pr_result)
return not pr_result.get("consistent")
Check accuracy result.
Check accuracy result.
[ "Check", "accuracy", "result", "." ]
def check_accuracy_result(case_name, pr_result): """Check accuracy result. """ logging.info("------ OP: %s ------" % case_name) logging.info("Accuracy diff: %s" % pr_result.get("diff")) logging.info("backward: %s" % pr_result.get("backward")) logging.info("parameters:") for line in pr_result.get("parameters").strip().split("\n"): logging.info("\t%s" % line) return not pr_result.get("consistent")
[ "def", "check_accuracy_result", "(", "case_name", ",", "pr_result", ")", ":", "logging", ".", "info", "(", "\"------ OP: %s ------\"", "%", "case_name", ")", "logging", ".", "info", "(", "\"Accuracy diff: %s\"", "%", "pr_result", ".", "get", "(", "\"diff\"", ")", ")", "logging", ".", "info", "(", "\"backward: %s\"", "%", "pr_result", ".", "get", "(", "\"backward\"", ")", ")", "logging", ".", "info", "(", "\"parameters:\"", ")", "for", "line", "in", "pr_result", ".", "get", "(", "\"parameters\"", ")", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", ":", "logging", ".", "info", "(", "\"\\t%s\"", "%", "line", ")", "return", "not", "pr_result", ".", "get", "(", "\"consistent\"", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/tools/check_op_benchmark_result.py#L93-L103
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/bulk_extractor_reader.py
python
BulkReport.margin_size
(self)
return int((self.xmldoc.getElementsByTagName("configuration")[0] .getElementsByTagName("marginsize")[0].firstChild.wholeText))
Returns the size of the overlapping margins around each page.
Returns the size of the overlapping margins around each page.
[ "Returns", "the", "size", "of", "the", "overlapping", "margins", "around", "each", "page", "." ]
def margin_size(self): """Returns the size of the overlapping margins around each page.""" return int((self.xmldoc.getElementsByTagName("configuration")[0] .getElementsByTagName("marginsize")[0].firstChild.wholeText))
[ "def", "margin_size", "(", "self", ")", ":", "return", "int", "(", "(", "self", ".", "xmldoc", ".", "getElementsByTagName", "(", "\"configuration\"", ")", "[", "0", "]", ".", "getElementsByTagName", "(", "\"marginsize\"", ")", "[", "0", "]", ".", "firstChild", ".", "wholeText", ")", ")" ]
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/bulk_extractor_reader.py#L241-L244
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Menu.FindItemByPosition
(*args, **kwargs)
return _core_.Menu_FindItemByPosition(*args, **kwargs)
FindItemByPosition(self, size_t position) -> MenuItem
FindItemByPosition(self, size_t position) -> MenuItem
[ "FindItemByPosition", "(", "self", "size_t", "position", ")", "-", ">", "MenuItem" ]
def FindItemByPosition(*args, **kwargs): """FindItemByPosition(self, size_t position) -> MenuItem""" return _core_.Menu_FindItemByPosition(*args, **kwargs)
[ "def", "FindItemByPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_FindItemByPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12146-L12148
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosbag/src/rosbag/rosbag_main.py
python
ProgressMeter.terminal_width
()
return width
Estimate the width of the terminal
Estimate the width of the terminal
[ "Estimate", "the", "width", "of", "the", "terminal" ]
def terminal_width(): """Estimate the width of the terminal""" width = 0 try: import struct, fcntl, termios s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(1, termios.TIOCGWINSZ, s) width = struct.unpack('HHHH', x)[1] except (IOError, ImportError): pass if width <= 0: try: width = int(os.environ['COLUMNS']) except: pass if width <= 0: width = 80 return width
[ "def", "terminal_width", "(", ")", ":", "width", "=", "0", "try", ":", "import", "struct", ",", "fcntl", ",", "termios", "s", "=", "struct", ".", "pack", "(", "'HHHH'", ",", "0", ",", "0", ",", "0", ",", "0", ")", "x", "=", "fcntl", ".", "ioctl", "(", "1", ",", "termios", ".", "TIOCGWINSZ", ",", "s", ")", "width", "=", "struct", ".", "unpack", "(", "'HHHH'", ",", "x", ")", "[", "1", "]", "except", "(", "IOError", ",", "ImportError", ")", ":", "pass", "if", "width", "<=", "0", ":", "try", ":", "width", "=", "int", "(", "os", ".", "environ", "[", "'COLUMNS'", "]", ")", "except", ":", "pass", "if", "width", "<=", "0", ":", "width", "=", "80", "return", "width" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosbag/src/rosbag/rosbag_main.py#L837-L855
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/control/cartesian_drive.py
python
normalize_rotation
(R)
return so3.from_quaternion(q)
Given a matrix close to a proper (orthogonal) rotation matrix, returns a true orthogonal matrix.
Given a matrix close to a proper (orthogonal) rotation matrix, returns a true orthogonal matrix.
[ "Given", "a", "matrix", "close", "to", "a", "proper", "(", "orthogonal", ")", "rotation", "matrix", "returns", "a", "true", "orthogonal", "matrix", "." ]
def normalize_rotation(R): """Given a matrix close to a proper (orthogonal) rotation matrix, returns a true orthogonal matrix.""" q = so3.quaternion(R) #normalizes return so3.from_quaternion(q)
[ "def", "normalize_rotation", "(", "R", ")", ":", "q", "=", "so3", ".", "quaternion", "(", "R", ")", "#normalizes", "return", "so3", ".", "from_quaternion", "(", "q", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/cartesian_drive.py#L424-L428
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/recommender/util.py
python
compare_models
( dataset, models, model_names=None, user_sample=1.0, metric="auto", target=None, exclude_known_for_precision_recall=True, make_plot=False, verbose=True, **kwargs )
return results
Compare the prediction or recommendation performance of recommender models on a common test dataset. Models that are trained to predict ratings are compared separately from models that are trained without target ratings. The ratings prediction models are compared on root-mean-squared error, and the rest are compared on precision-recall. Parameters ---------- dataset : SFrame The dataset to use for model evaluation. models : list[recommender models] List of trained recommender models. model_names : list[str], optional List of model name strings for display. user_sample : float, optional Sampling proportion of unique users to use in estimating model performance. Defaults to 1.0, i.e. use all users in the dataset. metric : str, {'auto', 'rmse', 'precision_recall'}, optional Metric for the evaluation. The default automatically splits models into two groups with their default evaluation metric respectively: 'rmse' for models trained with a target, and 'precision_recall' otherwise. target : str, optional The name of the target column for evaluating rmse. If the model is trained with a target column, the default is to using the same column. If the model is trained without a target column and `metric='rmse'`, then this option must be provided by user. exclude_known_for_precision_recall : bool, optional A useful option when `metric='precision_recall'`. Recommender models automatically exclude items seen in the training data from the final recommendation list. If the input evaluation `dataset` is the same as the data used for training the models, set this option to False. verbose : bool, optional If true, print the progress. Returns ------- out : list[SFrame] A list of results where each one is an sframe of evaluation results of the respective model on the given dataset Examples -------- If you have created two ItemSimilarityRecommenders ``m1`` and ``m2`` and have an :class:`~turicreate.SFrame` ``test_data``, then you may compare the performance of the two models on test data using: >>> import turicreate >>> train_data = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"], ... 'item_id': ["a", "c", "e", "b", "f", "b", "c", "d"]}) >>> test_data = turicreate.SFrame({'user_id': ["0", "0", "1", "1", "1", "2", "2"], ... 'item_id': ["b", "d", "a", "c", "e", "a", "e"]}) >>> m1 = turicreate.item_similarity_recommender.create(train_data) >>> m2 = turicreate.item_similarity_recommender.create(train_data, only_top_k=1) >>> turicreate.recommender.util.compare_models(test_data, [m1, m2], model_names=["m1", "m2"]) The evaluation metric is automatically set to 'precision_recall', and the evaluation will be based on recommendations that exclude items seen in the training data. If you want to evaluate on the original training set: >>> turicreate.recommender.util.compare_models(train_data, [m1, m2], ... exclude_known_for_precision_recall=False) Suppose you have four models, two trained with a target rating column, and the other two trained without a target. By default, the models are put into two different groups with "rmse", and "precision-recall" as the evaluation metric respectively. >>> train_data2 = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"], ... 'item_id': ["a", "c", "e", "b", "f", "b", "c", "d"], ... 'rating': [1, 3, 4, 5, 3, 4, 2, 5]}) >>> test_data2 = turicreate.SFrame({'user_id': ["0", "0", "1", "1", "1", "2", "2"], ... 'item_id': ["b", "d", "a", "c", "e", "a", "e"], ... 'rating': [3, 5, 4, 4, 3, 5, 2]}) >>> m3 = turicreate.factorization_recommender.create(train_data2, target='rating') >>> m4 = turicreate.factorization_recommender.create(train_data2, target='rating') >>> turicreate.recommender.util.compare_models(test_data2, [m3, m4]) To compare all four models using the same 'precision_recall' metric, you can do: >>> turicreate.recommender.util.compare_models(test_data2, [m1, m2, m3, m4], ... metric='precision_recall')
Compare the prediction or recommendation performance of recommender models on a common test dataset.
[ "Compare", "the", "prediction", "or", "recommendation", "performance", "of", "recommender", "models", "on", "a", "common", "test", "dataset", "." ]
def compare_models( dataset, models, model_names=None, user_sample=1.0, metric="auto", target=None, exclude_known_for_precision_recall=True, make_plot=False, verbose=True, **kwargs ): """ Compare the prediction or recommendation performance of recommender models on a common test dataset. Models that are trained to predict ratings are compared separately from models that are trained without target ratings. The ratings prediction models are compared on root-mean-squared error, and the rest are compared on precision-recall. Parameters ---------- dataset : SFrame The dataset to use for model evaluation. models : list[recommender models] List of trained recommender models. model_names : list[str], optional List of model name strings for display. user_sample : float, optional Sampling proportion of unique users to use in estimating model performance. Defaults to 1.0, i.e. use all users in the dataset. metric : str, {'auto', 'rmse', 'precision_recall'}, optional Metric for the evaluation. The default automatically splits models into two groups with their default evaluation metric respectively: 'rmse' for models trained with a target, and 'precision_recall' otherwise. target : str, optional The name of the target column for evaluating rmse. If the model is trained with a target column, the default is to using the same column. If the model is trained without a target column and `metric='rmse'`, then this option must be provided by user. exclude_known_for_precision_recall : bool, optional A useful option when `metric='precision_recall'`. Recommender models automatically exclude items seen in the training data from the final recommendation list. If the input evaluation `dataset` is the same as the data used for training the models, set this option to False. verbose : bool, optional If true, print the progress. Returns ------- out : list[SFrame] A list of results where each one is an sframe of evaluation results of the respective model on the given dataset Examples -------- If you have created two ItemSimilarityRecommenders ``m1`` and ``m2`` and have an :class:`~turicreate.SFrame` ``test_data``, then you may compare the performance of the two models on test data using: >>> import turicreate >>> train_data = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"], ... 'item_id': ["a", "c", "e", "b", "f", "b", "c", "d"]}) >>> test_data = turicreate.SFrame({'user_id': ["0", "0", "1", "1", "1", "2", "2"], ... 'item_id': ["b", "d", "a", "c", "e", "a", "e"]}) >>> m1 = turicreate.item_similarity_recommender.create(train_data) >>> m2 = turicreate.item_similarity_recommender.create(train_data, only_top_k=1) >>> turicreate.recommender.util.compare_models(test_data, [m1, m2], model_names=["m1", "m2"]) The evaluation metric is automatically set to 'precision_recall', and the evaluation will be based on recommendations that exclude items seen in the training data. If you want to evaluate on the original training set: >>> turicreate.recommender.util.compare_models(train_data, [m1, m2], ... exclude_known_for_precision_recall=False) Suppose you have four models, two trained with a target rating column, and the other two trained without a target. By default, the models are put into two different groups with "rmse", and "precision-recall" as the evaluation metric respectively. >>> train_data2 = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"], ... 'item_id': ["a", "c", "e", "b", "f", "b", "c", "d"], ... 'rating': [1, 3, 4, 5, 3, 4, 2, 5]}) >>> test_data2 = turicreate.SFrame({'user_id': ["0", "0", "1", "1", "1", "2", "2"], ... 'item_id': ["b", "d", "a", "c", "e", "a", "e"], ... 'rating': [3, 5, 4, 4, 3, 5, 2]}) >>> m3 = turicreate.factorization_recommender.create(train_data2, target='rating') >>> m4 = turicreate.factorization_recommender.create(train_data2, target='rating') >>> turicreate.recommender.util.compare_models(test_data2, [m3, m4]) To compare all four models using the same 'precision_recall' metric, you can do: >>> turicreate.recommender.util.compare_models(test_data2, [m1, m2, m3, m4], ... metric='precision_recall') """ from turicreate.toolkits.recommender.util import _Recommender as BaseRecommender if not isinstance(dataset, _SFrame): raise TypeError('"dataset" must be of type SFrame.') if len(dataset) == 0: raise _ToolkitError("Unable to test on an empty dataset.") if any(map(lambda m: not issubclass(type(m), BaseRecommender), models)): raise _ToolkitError("All models must be recommender models.") num_models = len(models) if model_names is None: model_names = ["M" + str(i) for i in range(len(models))] if num_models < 1: raise ValueError( "Must pass in at least one recommender model to \ evaluate" ) if model_names is not None and len(model_names) != num_models: raise ValueError( "Must pass in the same number of model names as \ models" ) # if we are asked to sample the users, come up with a list of unique users if user_sample < 1.0: user_id_name = models[0].user_id if user_id_name is None: raise ValueError("user_id not set in model(s)") user_sa = dataset[user_id_name] unique_users = list(user_sa.unique()) nusers = len(unique_users) ntake = int(round(user_sample * nusers)) _random.shuffle(unique_users) users = unique_users[:ntake] print("compare_models: using", ntake, "users to estimate model performance") users = frozenset(users) ix = [u in users for u in dataset[user_id_name]] dataset_subset = dataset[_SArray(ix) == True] else: dataset_subset = dataset results = [] for (m, mname) in zip(models, model_names): if verbose: print("PROGRESS: Evaluate model %s" % mname) r = m.evaluate( dataset_subset, metric, exclude_known_for_precision_recall, target, verbose=verbose, cutoffs=list(range(1, 11, 1)) + list(range(11, 50, 5)), **kwargs ) results.append(r) return results
[ "def", "compare_models", "(", "dataset", ",", "models", ",", "model_names", "=", "None", ",", "user_sample", "=", "1.0", ",", "metric", "=", "\"auto\"", ",", "target", "=", "None", ",", "exclude_known_for_precision_recall", "=", "True", ",", "make_plot", "=", "False", ",", "verbose", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", "turicreate", ".", "toolkits", ".", "recommender", ".", "util", "import", "_Recommender", "as", "BaseRecommender", "if", "not", "isinstance", "(", "dataset", ",", "_SFrame", ")", ":", "raise", "TypeError", "(", "'\"dataset\" must be of type SFrame.'", ")", "if", "len", "(", "dataset", ")", "==", "0", ":", "raise", "_ToolkitError", "(", "\"Unable to test on an empty dataset.\"", ")", "if", "any", "(", "map", "(", "lambda", "m", ":", "not", "issubclass", "(", "type", "(", "m", ")", ",", "BaseRecommender", ")", ",", "models", ")", ")", ":", "raise", "_ToolkitError", "(", "\"All models must be recommender models.\"", ")", "num_models", "=", "len", "(", "models", ")", "if", "model_names", "is", "None", ":", "model_names", "=", "[", "\"M\"", "+", "str", "(", "i", ")", "for", "i", "in", "range", "(", "len", "(", "models", ")", ")", "]", "if", "num_models", "<", "1", ":", "raise", "ValueError", "(", "\"Must pass in at least one recommender model to \\\n evaluate\"", ")", "if", "model_names", "is", "not", "None", "and", "len", "(", "model_names", ")", "!=", "num_models", ":", "raise", "ValueError", "(", "\"Must pass in the same number of model names as \\\n models\"", ")", "# if we are asked to sample the users, come up with a list of unique users", "if", "user_sample", "<", "1.0", ":", "user_id_name", "=", "models", "[", "0", "]", ".", "user_id", "if", "user_id_name", "is", "None", ":", "raise", "ValueError", "(", "\"user_id not set in model(s)\"", ")", "user_sa", "=", "dataset", "[", "user_id_name", "]", "unique_users", "=", "list", "(", "user_sa", ".", "unique", "(", ")", ")", "nusers", "=", "len", "(", "unique_users", ")", "ntake", "=", "int", "(", "round", "(", "user_sample", "*", "nusers", ")", ")", "_random", ".", "shuffle", "(", "unique_users", ")", "users", "=", "unique_users", "[", ":", "ntake", "]", "print", "(", "\"compare_models: using\"", ",", "ntake", ",", "\"users to estimate model performance\"", ")", "users", "=", "frozenset", "(", "users", ")", "ix", "=", "[", "u", "in", "users", "for", "u", "in", "dataset", "[", "user_id_name", "]", "]", "dataset_subset", "=", "dataset", "[", "_SArray", "(", "ix", ")", "==", "True", "]", "else", ":", "dataset_subset", "=", "dataset", "results", "=", "[", "]", "for", "(", "m", ",", "mname", ")", "in", "zip", "(", "models", ",", "model_names", ")", ":", "if", "verbose", ":", "print", "(", "\"PROGRESS: Evaluate model %s\"", "%", "mname", ")", "r", "=", "m", ".", "evaluate", "(", "dataset_subset", ",", "metric", ",", "exclude_known_for_precision_recall", ",", "target", ",", "verbose", "=", "verbose", ",", "cutoffs", "=", "list", "(", "range", "(", "1", ",", "11", ",", "1", ")", ")", "+", "list", "(", "range", "(", "11", ",", "50", ",", "5", ")", ")", ",", "*", "*", "kwargs", ")", "results", ".", "append", "(", "r", ")", "return", "results" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/recommender/util.py#L185-L354
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Fem/femtools/femutils.py
python
get_refshape_type
(fem_doc_object)
Return shape type the constraints references. Determine single shape type of references of *fem_doc_object* which must be a constraint (=have a *References* property). All references must be of the same type which is than returned as a string. A type can be "Vertex", "Edge", "Face" or "Solid". :param fem_doc_object: A constraint object with a *References* property. :returns: A string representing the shape type ("Vertex", "Edge", "Face" or "Solid"). If *fem_doc_object* isn't a constraint ``""`` is returned. :note: Undefined behaviour if the type of the references of one object are not all the same. :note: Undefined behaviour if constraint contains no references (empty list).
Return shape type the constraints references.
[ "Return", "shape", "type", "the", "constraints", "references", "." ]
def get_refshape_type(fem_doc_object): """ Return shape type the constraints references. Determine single shape type of references of *fem_doc_object* which must be a constraint (=have a *References* property). All references must be of the same type which is than returned as a string. A type can be "Vertex", "Edge", "Face" or "Solid". :param fem_doc_object: A constraint object with a *References* property. :returns: A string representing the shape type ("Vertex", "Edge", "Face" or "Solid"). If *fem_doc_object* isn't a constraint ``""`` is returned. :note: Undefined behaviour if the type of the references of one object are not all the same. :note: Undefined behaviour if constraint contains no references (empty list). """ from femtools.geomtools import get_element if hasattr(fem_doc_object, "References") and fem_doc_object.References: first_ref_obj = fem_doc_object.References[0] first_ref_shape = get_element(first_ref_obj[0], first_ref_obj[1][0]) st = first_ref_shape.ShapeType FreeCAD.Console.PrintLog( "References: {} in {}, {}\n" . format(st, fem_doc_object.Name, fem_doc_object.Label) ) return st else: FreeCAD.Console.PrintLog( "References: empty in {}, {}\n" . format(fem_doc_object.Name, fem_doc_object.Label) ) return ""
[ "def", "get_refshape_type", "(", "fem_doc_object", ")", ":", "from", "femtools", ".", "geomtools", "import", "get_element", "if", "hasattr", "(", "fem_doc_object", ",", "\"References\"", ")", "and", "fem_doc_object", ".", "References", ":", "first_ref_obj", "=", "fem_doc_object", ".", "References", "[", "0", "]", "first_ref_shape", "=", "get_element", "(", "first_ref_obj", "[", "0", "]", ",", "first_ref_obj", "[", "1", "]", "[", "0", "]", ")", "st", "=", "first_ref_shape", ".", "ShapeType", "FreeCAD", ".", "Console", ".", "PrintLog", "(", "\"References: {} in {}, {}\\n\"", ".", "format", "(", "st", ",", "fem_doc_object", ".", "Name", ",", "fem_doc_object", ".", "Label", ")", ")", "return", "st", "else", ":", "FreeCAD", ".", "Console", ".", "PrintLog", "(", "\"References: empty in {}, {}\\n\"", ".", "format", "(", "fem_doc_object", ".", "Name", ",", "fem_doc_object", ".", "Label", ")", ")", "return", "\"\"" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Fem/femtools/femutils.py#L339-L376
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/npydecl.py
python
MatMulTyperMixin.matmul_typer
(self, a, b, out=None)
Typer function for Numpy matrix multiplication.
Typer function for Numpy matrix multiplication.
[ "Typer", "function", "for", "Numpy", "matrix", "multiplication", "." ]
def matmul_typer(self, a, b, out=None): """ Typer function for Numpy matrix multiplication. """ if not isinstance(a, types.Array) or not isinstance(b, types.Array): return if not all(x.ndim in (1, 2) for x in (a, b)): raise TypingError("%s only supported on 1-D and 2-D arrays" % (self.func_name, )) # Output dimensionality ndims = set([a.ndim, b.ndim]) if ndims == set([2]): # M * M out_ndim = 2 elif ndims == set([1, 2]): # M* V and V * M out_ndim = 1 elif ndims == set([1]): # V * V out_ndim = 0 if out is not None: if out_ndim == 0: raise TypeError("explicit output unsupported for vector * vector") elif out.ndim != out_ndim: raise TypeError("explicit output has incorrect dimensionality") if not isinstance(out, types.Array) or out.layout != 'C': raise TypeError("output must be a C-contiguous array") all_args = (a, b, out) else: all_args = (a, b) if not (config.DISABLE_PERFORMANCE_WARNINGS or all(x.layout in 'CF' for x in (a, b))): msg = ("%s is faster on contiguous arrays, called on %s" % (self.func_name, (a, b))) warnings.warn(NumbaPerformanceWarning(msg)) if not all(x.dtype == a.dtype for x in all_args): raise TypingError("%s arguments must all have " "the same dtype" % (self.func_name,)) if not isinstance(a.dtype, (types.Float, types.Complex)): raise TypingError("%s only supported on " "float and complex arrays" % (self.func_name,)) if out: return out elif out_ndim > 0: return types.Array(a.dtype, out_ndim, 'C') else: return a.dtype
[ "def", "matmul_typer", "(", "self", ",", "a", ",", "b", ",", "out", "=", "None", ")", ":", "if", "not", "isinstance", "(", "a", ",", "types", ".", "Array", ")", "or", "not", "isinstance", "(", "b", ",", "types", ".", "Array", ")", ":", "return", "if", "not", "all", "(", "x", ".", "ndim", "in", "(", "1", ",", "2", ")", "for", "x", "in", "(", "a", ",", "b", ")", ")", ":", "raise", "TypingError", "(", "\"%s only supported on 1-D and 2-D arrays\"", "%", "(", "self", ".", "func_name", ",", ")", ")", "# Output dimensionality", "ndims", "=", "set", "(", "[", "a", ".", "ndim", ",", "b", ".", "ndim", "]", ")", "if", "ndims", "==", "set", "(", "[", "2", "]", ")", ":", "# M * M", "out_ndim", "=", "2", "elif", "ndims", "==", "set", "(", "[", "1", ",", "2", "]", ")", ":", "# M* V and V * M", "out_ndim", "=", "1", "elif", "ndims", "==", "set", "(", "[", "1", "]", ")", ":", "# V * V", "out_ndim", "=", "0", "if", "out", "is", "not", "None", ":", "if", "out_ndim", "==", "0", ":", "raise", "TypeError", "(", "\"explicit output unsupported for vector * vector\"", ")", "elif", "out", ".", "ndim", "!=", "out_ndim", ":", "raise", "TypeError", "(", "\"explicit output has incorrect dimensionality\"", ")", "if", "not", "isinstance", "(", "out", ",", "types", ".", "Array", ")", "or", "out", ".", "layout", "!=", "'C'", ":", "raise", "TypeError", "(", "\"output must be a C-contiguous array\"", ")", "all_args", "=", "(", "a", ",", "b", ",", "out", ")", "else", ":", "all_args", "=", "(", "a", ",", "b", ")", "if", "not", "(", "config", ".", "DISABLE_PERFORMANCE_WARNINGS", "or", "all", "(", "x", ".", "layout", "in", "'CF'", "for", "x", "in", "(", "a", ",", "b", ")", ")", ")", ":", "msg", "=", "(", "\"%s is faster on contiguous arrays, called on %s\"", "%", "(", "self", ".", "func_name", ",", "(", "a", ",", "b", ")", ")", ")", "warnings", ".", "warn", "(", "NumbaPerformanceWarning", "(", "msg", ")", ")", "if", "not", "all", "(", "x", ".", "dtype", "==", "a", ".", "dtype", "for", "x", "in", "all_args", ")", ":", "raise", "TypingError", "(", "\"%s arguments must all have \"", "\"the same dtype\"", "%", "(", "self", ".", "func_name", ",", ")", ")", "if", "not", "isinstance", "(", "a", ".", "dtype", ",", "(", "types", ".", "Float", ",", "types", ".", "Complex", ")", ")", ":", "raise", "TypingError", "(", "\"%s only supported on \"", "\"float and complex arrays\"", "%", "(", "self", ".", "func_name", ",", ")", ")", "if", "out", ":", "return", "out", "elif", "out_ndim", ">", "0", ":", "return", "types", ".", "Array", "(", "a", ".", "dtype", ",", "out_ndim", ",", "'C'", ")", "else", ":", "return", "a", ".", "dtype" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/npydecl.py#L922-L971
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/_multivariate.py
python
multivariate_normal_frozen.entropy
(self)
return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet)
Computes the differential entropy of the multivariate normal. Returns ------- h : scalar Entropy of the multivariate normal distribution
Computes the differential entropy of the multivariate normal.
[ "Computes", "the", "differential", "entropy", "of", "the", "multivariate", "normal", "." ]
def entropy(self): """ Computes the differential entropy of the multivariate normal. Returns ------- h : scalar Entropy of the multivariate normal distribution """ log_pdet = self.cov_info.log_pdet rank = self.cov_info.rank return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet)
[ "def", "entropy", "(", "self", ")", ":", "log_pdet", "=", "self", ".", "cov_info", ".", "log_pdet", "rank", "=", "self", ".", "cov_info", ".", "rank", "return", "0.5", "*", "(", "rank", "*", "(", "_LOG_2PI", "+", "1", ")", "+", "log_pdet", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_multivariate.py#L764-L776
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/variables.py
python
Variable._OverloadAllOperators
()
Register overloads for all operators.
Register overloads for all operators.
[ "Register", "overloads", "for", "all", "operators", "." ]
def _OverloadAllOperators(): """Register overloads for all operators.""" for operator in ops.Tensor.OVERLOADABLE_OPERATORS: Variable._OverloadOperator(operator)
[ "def", "_OverloadAllOperators", "(", ")", ":", "for", "operator", "in", "ops", ".", "Tensor", ".", "OVERLOADABLE_OPERATORS", ":", "Variable", ".", "_OverloadOperator", "(", "operator", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/variables.py#L600-L603
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/stateful_random_ops.py
python
create_rng_state
(seed, alg)
return _make_state_from_seed(seed, alg)
Creates a RNG state from an integer or a vector. Example: >>> tf.random.create_rng_state( ... 1234, "philox") <tf.Tensor: shape=(3,), dtype=int64, numpy=array([1234, 0, 0])> >>> tf.random.create_rng_state( ... [12, 34], "threefry") <tf.Tensor: shape=(2,), dtype=int64, numpy=array([12, 34])> Args: seed: an integer or 1-D numpy array. alg: the RNG algorithm. Can be a string, an `Algorithm` or an integer. Returns: a 1-D numpy array whose size depends on the algorithm.
Creates a RNG state from an integer or a vector.
[ "Creates", "a", "RNG", "state", "from", "an", "integer", "or", "a", "vector", "." ]
def create_rng_state(seed, alg): """Creates a RNG state from an integer or a vector. Example: >>> tf.random.create_rng_state( ... 1234, "philox") <tf.Tensor: shape=(3,), dtype=int64, numpy=array([1234, 0, 0])> >>> tf.random.create_rng_state( ... [12, 34], "threefry") <tf.Tensor: shape=(2,), dtype=int64, numpy=array([12, 34])> Args: seed: an integer or 1-D numpy array. alg: the RNG algorithm. Can be a string, an `Algorithm` or an integer. Returns: a 1-D numpy array whose size depends on the algorithm. """ alg = stateless_random_ops.convert_alg_to_int(alg) return _make_state_from_seed(seed, alg)
[ "def", "create_rng_state", "(", "seed", ",", "alg", ")", ":", "alg", "=", "stateless_random_ops", ".", "convert_alg_to_int", "(", "alg", ")", "return", "_make_state_from_seed", "(", "seed", ",", "alg", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/stateful_random_ops.py#L163-L183
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/stc.py
python
StyledTextCtrl.SetRectangularSelectionAnchor
(*args, **kwargs)
return _stc.StyledTextCtrl_SetRectangularSelectionAnchor(*args, **kwargs)
SetRectangularSelectionAnchor(self, int posAnchor)
SetRectangularSelectionAnchor(self, int posAnchor)
[ "SetRectangularSelectionAnchor", "(", "self", "int", "posAnchor", ")" ]
def SetRectangularSelectionAnchor(*args, **kwargs): """SetRectangularSelectionAnchor(self, int posAnchor)""" return _stc.StyledTextCtrl_SetRectangularSelectionAnchor(*args, **kwargs)
[ "def", "SetRectangularSelectionAnchor", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_SetRectangularSelectionAnchor", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/stc.py#L6216-L6218
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py
python
IdleConf.SaveUserCfgFiles
(self)
write all loaded user configuration files back to disk
write all loaded user configuration files back to disk
[ "write", "all", "loaded", "user", "configuration", "files", "back", "to", "disk" ]
def SaveUserCfgFiles(self): """ write all loaded user configuration files back to disk """ for key in self.userCfg.keys(): self.userCfg[key].Save()
[ "def", "SaveUserCfgFiles", "(", "self", ")", ":", "for", "key", "in", "self", ".", "userCfg", ".", "keys", "(", ")", ":", "self", ".", "userCfg", "[", "key", "]", ".", "Save", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/configHandler.py#L693-L698
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/position.py
python
Position.pos_loss
(self, pos_loss)
Sets the pos_loss of this Position. :param pos_loss: The pos_loss of this Position. # noqa: E501 :type: float
Sets the pos_loss of this Position.
[ "Sets", "the", "pos_loss", "of", "this", "Position", "." ]
def pos_loss(self, pos_loss): """Sets the pos_loss of this Position. :param pos_loss: The pos_loss of this Position. # noqa: E501 :type: float """ self._pos_loss = pos_loss
[ "def", "pos_loss", "(", "self", ",", "pos_loss", ")", ":", "self", ".", "_pos_loss", "=", "pos_loss" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/position.py#L1648-L1656
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py
python
_DetectVisualStudioVersions
(versions_to_check, force_express)
return versions
Collect the list of installed visual studio versions. Returns: A list of visual studio versions installed in descending order of usage preference. Base this on the registry and a quick check if devenv.exe exists. Possibilities are: 2005(e) - Visual Studio 2005 (8) 2008(e) - Visual Studio 2008 (9) 2010(e) - Visual Studio 2010 (10) 2012(e) - Visual Studio 2012 (11) 2013(e) - Visual Studio 2013 (12) 2015 - Visual Studio 2015 (14) 2017 - Visual Studio 2017 (15) 2019 - Visual Studio 2019 (16) 2022 - Visual Studio 2022 (17) Where (e) is e for express editions of MSVS and blank otherwise.
Collect the list of installed visual studio versions.
[ "Collect", "the", "list", "of", "installed", "visual", "studio", "versions", "." ]
def _DetectVisualStudioVersions(versions_to_check, force_express): """Collect the list of installed visual studio versions. Returns: A list of visual studio versions installed in descending order of usage preference. Base this on the registry and a quick check if devenv.exe exists. Possibilities are: 2005(e) - Visual Studio 2005 (8) 2008(e) - Visual Studio 2008 (9) 2010(e) - Visual Studio 2010 (10) 2012(e) - Visual Studio 2012 (11) 2013(e) - Visual Studio 2013 (12) 2015 - Visual Studio 2015 (14) 2017 - Visual Studio 2017 (15) 2019 - Visual Studio 2019 (16) 2022 - Visual Studio 2022 (17) Where (e) is e for express editions of MSVS and blank otherwise. """ version_to_year = { "8.0": "2005", "9.0": "2008", "10.0": "2010", "11.0": "2012", "12.0": "2013", "14.0": "2015", "15.0": "2017", "16.0": "2019", "17.0": "2022", } versions = [] for version in versions_to_check: # Old method of searching for which VS version is installed # We don't use the 2010-encouraged-way because we also want to get the # path to the binaries, which it doesn't offer. keys = [ r"HKLM\Software\Microsoft\VisualStudio\%s" % version, r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s" % version, r"HKLM\Software\Microsoft\VCExpress\%s" % version, r"HKLM\Software\Wow6432Node\Microsoft\VCExpress\%s" % version, ] for index in range(len(keys)): path = _RegistryGetValue(keys[index], "InstallDir") if not path: continue path = _ConvertToCygpath(path) # Check for full. full_path = os.path.join(path, "devenv.exe") express_path = os.path.join(path, "*express.exe") if not force_express and os.path.exists(full_path): # Add this one. versions.append( _CreateVersion( version_to_year[version], os.path.join(path, "..", "..") ) ) # Check for express. elif glob.glob(express_path): # Add this one. versions.append( _CreateVersion( version_to_year[version] + "e", os.path.join(path, "..", "..") ) ) # The old method above does not work when only SDK is installed. keys = [ r"HKLM\Software\Microsoft\VisualStudio\SxS\VC7", r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VC7", r"HKLM\Software\Microsoft\VisualStudio\SxS\VS7", r"HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VS7", ] for index in range(len(keys)): path = _RegistryGetValue(keys[index], version) if not path: continue path = _ConvertToCygpath(path) if version == "15.0": if os.path.exists(path): versions.append(_CreateVersion("2017", path)) elif version != "14.0": # There is no Express edition for 2015. versions.append( _CreateVersion( version_to_year[version] + "e", os.path.join(path, ".."), sdk_based=True, ) ) return versions
[ "def", "_DetectVisualStudioVersions", "(", "versions_to_check", ",", "force_express", ")", ":", "version_to_year", "=", "{", "\"8.0\"", ":", "\"2005\"", ",", "\"9.0\"", ":", "\"2008\"", ",", "\"10.0\"", ":", "\"2010\"", ",", "\"11.0\"", ":", "\"2012\"", ",", "\"12.0\"", ":", "\"2013\"", ",", "\"14.0\"", ":", "\"2015\"", ",", "\"15.0\"", ":", "\"2017\"", ",", "\"16.0\"", ":", "\"2019\"", ",", "\"17.0\"", ":", "\"2022\"", ",", "}", "versions", "=", "[", "]", "for", "version", "in", "versions_to_check", ":", "# Old method of searching for which VS version is installed", "# We don't use the 2010-encouraged-way because we also want to get the", "# path to the binaries, which it doesn't offer.", "keys", "=", "[", "r\"HKLM\\Software\\Microsoft\\VisualStudio\\%s\"", "%", "version", ",", "r\"HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\%s\"", "%", "version", ",", "r\"HKLM\\Software\\Microsoft\\VCExpress\\%s\"", "%", "version", ",", "r\"HKLM\\Software\\Wow6432Node\\Microsoft\\VCExpress\\%s\"", "%", "version", ",", "]", "for", "index", "in", "range", "(", "len", "(", "keys", ")", ")", ":", "path", "=", "_RegistryGetValue", "(", "keys", "[", "index", "]", ",", "\"InstallDir\"", ")", "if", "not", "path", ":", "continue", "path", "=", "_ConvertToCygpath", "(", "path", ")", "# Check for full.", "full_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"devenv.exe\"", ")", "express_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"*express.exe\"", ")", "if", "not", "force_express", "and", "os", ".", "path", ".", "exists", "(", "full_path", ")", ":", "# Add this one.", "versions", ".", "append", "(", "_CreateVersion", "(", "version_to_year", "[", "version", "]", ",", "os", ".", "path", ".", "join", "(", "path", ",", "\"..\"", ",", "\"..\"", ")", ")", ")", "# Check for express.", "elif", "glob", ".", "glob", "(", "express_path", ")", ":", "# Add this one.", "versions", ".", "append", "(", "_CreateVersion", "(", "version_to_year", "[", "version", "]", "+", "\"e\"", ",", "os", ".", "path", ".", "join", "(", "path", ",", "\"..\"", ",", "\"..\"", ")", ")", ")", "# The old method above does not work when only SDK is installed.", "keys", "=", "[", "r\"HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7\"", ",", "r\"HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7\"", ",", "r\"HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VS7\"", ",", "r\"HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7\"", ",", "]", "for", "index", "in", "range", "(", "len", "(", "keys", ")", ")", ":", "path", "=", "_RegistryGetValue", "(", "keys", "[", "index", "]", ",", "version", ")", "if", "not", "path", ":", "continue", "path", "=", "_ConvertToCygpath", "(", "path", ")", "if", "version", "==", "\"15.0\"", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "versions", ".", "append", "(", "_CreateVersion", "(", "\"2017\"", ",", "path", ")", ")", "elif", "version", "!=", "\"14.0\"", ":", "# There is no Express edition for 2015.", "versions", ".", "append", "(", "_CreateVersion", "(", "version_to_year", "[", "version", "]", "+", "\"e\"", ",", "os", ".", "path", ".", "join", "(", "path", ",", "\"..\"", ")", ",", "sdk_based", "=", "True", ",", ")", ")", "return", "versions" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py#L435-L524
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py
python
CCompiler.add_library_dir
(self, dir)
Add 'dir' to the list of directories that will be searched for libraries specified to 'add_library()' and 'set_libraries()'. The linker will be instructed to search for libraries in the order they are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
Add 'dir' to the list of directories that will be searched for libraries specified to 'add_library()' and 'set_libraries()'. The linker will be instructed to search for libraries in the order they are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
[ "Add", "dir", "to", "the", "list", "of", "directories", "that", "will", "be", "searched", "for", "libraries", "specified", "to", "add_library", "()", "and", "set_libraries", "()", ".", "The", "linker", "will", "be", "instructed", "to", "search", "for", "libraries", "in", "the", "order", "they", "are", "supplied", "to", "add_library_dir", "()", "and", "/", "or", "set_library_dirs", "()", "." ]
def add_library_dir(self, dir): """Add 'dir' to the list of directories that will be searched for libraries specified to 'add_library()' and 'set_libraries()'. The linker will be instructed to search for libraries in the order they are supplied to 'add_library_dir()' and/or 'set_library_dirs()'. """ self.library_dirs.append(dir)
[ "def", "add_library_dir", "(", "self", ",", "dir", ")", ":", "self", ".", "library_dirs", ".", "append", "(", "dir", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/ccompiler.py#L272-L278
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/mvn.py
python
MultivariateNormalOperatorPD.sample_n
(self, n, seed=None, name="sample_n")
Sample `n` observations from the Multivariate Normal Distributions. Args: n: `Scalar`, type int32, the number of observations to sample. seed: Python integer, the random seed. name: The name to give this op. Returns: samples: `[n, ...]`, a `Tensor` of `n` samples for each of the distributions determined by broadcasting the hyperparameters.
Sample `n` observations from the Multivariate Normal Distributions.
[ "Sample", "n", "observations", "from", "the", "Multivariate", "Normal", "Distributions", "." ]
def sample_n(self, n, seed=None, name="sample_n"): """Sample `n` observations from the Multivariate Normal Distributions. Args: n: `Scalar`, type int32, the number of observations to sample. seed: Python integer, the random seed. name: The name to give this op. Returns: samples: `[n, ...]`, a `Tensor` of `n` samples for each of the distributions determined by broadcasting the hyperparameters. """ with ops.name_scope(self.name): with ops.op_scope([self._mu, n] + self._cov.inputs, name): # Recall _check_mu ensures mu and self._cov have same batch shape. broadcast_shape = self.mu.get_shape() n = ops.convert_to_tensor(n) shape = array_ops.concat(0, [self._cov.vector_shape(), [n]]) white_samples = random_ops.random_normal(shape=shape, mean=0, stddev=1, dtype=self.dtype, seed=seed) correlated_samples = self._cov.sqrt_matmul(white_samples) # Move the last dimension to the front perm = array_ops.concat(0, ( array_ops.pack([array_ops.rank(correlated_samples) - 1]), math_ops.range(0, array_ops.rank(correlated_samples) - 1))) # TODO(ebrevdo): Once we get a proper tensor contraction op, # perform the inner product using that instead of batch_matmul # and this slow transpose can go away! correlated_samples = array_ops.transpose(correlated_samples, perm) samples = correlated_samples + self.mu # Provide some hints to shape inference n_val = tensor_util.constant_value(n) final_shape = tensor_shape.vector(n_val).concatenate(broadcast_shape) samples.set_shape(final_shape) return samples
[ "def", "sample_n", "(", "self", ",", "n", ",", "seed", "=", "None", ",", "name", "=", "\"sample_n\"", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "self", ".", "_mu", ",", "n", "]", "+", "self", ".", "_cov", ".", "inputs", ",", "name", ")", ":", "# Recall _check_mu ensures mu and self._cov have same batch shape.", "broadcast_shape", "=", "self", ".", "mu", ".", "get_shape", "(", ")", "n", "=", "ops", ".", "convert_to_tensor", "(", "n", ")", "shape", "=", "array_ops", ".", "concat", "(", "0", ",", "[", "self", ".", "_cov", ".", "vector_shape", "(", ")", ",", "[", "n", "]", "]", ")", "white_samples", "=", "random_ops", ".", "random_normal", "(", "shape", "=", "shape", ",", "mean", "=", "0", ",", "stddev", "=", "1", ",", "dtype", "=", "self", ".", "dtype", ",", "seed", "=", "seed", ")", "correlated_samples", "=", "self", ".", "_cov", ".", "sqrt_matmul", "(", "white_samples", ")", "# Move the last dimension to the front", "perm", "=", "array_ops", ".", "concat", "(", "0", ",", "(", "array_ops", ".", "pack", "(", "[", "array_ops", ".", "rank", "(", "correlated_samples", ")", "-", "1", "]", ")", ",", "math_ops", ".", "range", "(", "0", ",", "array_ops", ".", "rank", "(", "correlated_samples", ")", "-", "1", ")", ")", ")", "# TODO(ebrevdo): Once we get a proper tensor contraction op,", "# perform the inner product using that instead of batch_matmul", "# and this slow transpose can go away!", "correlated_samples", "=", "array_ops", ".", "transpose", "(", "correlated_samples", ",", "perm", ")", "samples", "=", "correlated_samples", "+", "self", ".", "mu", "# Provide some hints to shape inference", "n_val", "=", "tensor_util", ".", "constant_value", "(", "n", ")", "final_shape", "=", "tensor_shape", ".", "vector", "(", "n_val", ")", ".", "concatenate", "(", "broadcast_shape", ")", "samples", ".", "set_shape", "(", "final_shape", ")", "return", "samples" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/mvn.py#L347-L391
bumptop/BumpTop
466d23597a07ae738f4265262fa01087fc6e257c
trunk/win/Source/bin/jinja2/compiler.py
python
UndeclaredNameVisitor.visit_Block
(self, node)
Stop visiting a blocks.
Stop visiting a blocks.
[ "Stop", "visiting", "a", "blocks", "." ]
def visit_Block(self, node): """Stop visiting a blocks."""
[ "def", "visit_Block", "(", "self", ",", "node", ")", ":" ]
https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/compiler.py#L247-L248
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/input_lib.py
python
DistributedDataset.__init__
(self, input_workers, strategy, dataset=None, num_replicas_in_sync=None, input_context=None, components=None, element_spec=None, enable_get_next_as_optional=None, build=True, options=None)
Distribute the dataset on all workers. If `num_replicas_in_sync` is not None, we split each batch of the dataset into `num_replicas_in_sync` smaller batches, to be distributed among that worker's replicas, so that the batch size for a global step (across all workers and replicas) is as expected. Args: input_workers: an `InputWorkers` object. strategy: a `tf.distribute.Strategy` object, used to run all-reduce to handle last partial batch. dataset: `tf.data.Dataset` that will be used as the input source. Either dataset or components field should be passed when constructing DistributedDataset. Use this when contructing DistributedDataset from a new `tf.data.Dataset`. Use components when constructing using DistributedDatasetSpec. num_replicas_in_sync: Optional integer. If this is not None, the value is used to decide how to rebatch datasets into smaller batches so that the total batch size for each step (across all workers and replicas) adds up to `dataset`'s batch size. input_context: `InputContext` for sharding. Only pass this in for between graph multi-worker cases where there is only one `input_worker`. In these cases, we will shard based on the `input_pipeline_id` and `num_input_pipelines` in the `InputContext`. components: datasets when DistributedDataset is constructed from DistributedDatasetSpec. Either field dataset or components should be passed. element_spec: element spec for DistributedDataset when constructing from DistributedDatasetSpec. This will be used to set the element_spec for DistributedDataset and verified against element_spec from components. enable_get_next_as_optional: this is required when components is passed instead of dataset. build: whether to build underlying datasets when this object is created. This is only useful for `ParameterServerStrategy` now. options: `tf.distribute.InputOptions` used to control options on how this dataset is distributed.
Distribute the dataset on all workers.
[ "Distribute", "the", "dataset", "on", "all", "workers", "." ]
def __init__(self, input_workers, strategy, dataset=None, num_replicas_in_sync=None, input_context=None, components=None, element_spec=None, enable_get_next_as_optional=None, build=True, options=None): """Distribute the dataset on all workers. If `num_replicas_in_sync` is not None, we split each batch of the dataset into `num_replicas_in_sync` smaller batches, to be distributed among that worker's replicas, so that the batch size for a global step (across all workers and replicas) is as expected. Args: input_workers: an `InputWorkers` object. strategy: a `tf.distribute.Strategy` object, used to run all-reduce to handle last partial batch. dataset: `tf.data.Dataset` that will be used as the input source. Either dataset or components field should be passed when constructing DistributedDataset. Use this when contructing DistributedDataset from a new `tf.data.Dataset`. Use components when constructing using DistributedDatasetSpec. num_replicas_in_sync: Optional integer. If this is not None, the value is used to decide how to rebatch datasets into smaller batches so that the total batch size for each step (across all workers and replicas) adds up to `dataset`'s batch size. input_context: `InputContext` for sharding. Only pass this in for between graph multi-worker cases where there is only one `input_worker`. In these cases, we will shard based on the `input_pipeline_id` and `num_input_pipelines` in the `InputContext`. components: datasets when DistributedDataset is constructed from DistributedDatasetSpec. Either field dataset or components should be passed. element_spec: element spec for DistributedDataset when constructing from DistributedDatasetSpec. This will be used to set the element_spec for DistributedDataset and verified against element_spec from components. enable_get_next_as_optional: this is required when components is passed instead of dataset. build: whether to build underlying datasets when this object is created. This is only useful for `ParameterServerStrategy` now. options: `tf.distribute.InputOptions` used to control options on how this dataset is distributed. """ super(DistributedDataset, self).__init__(input_workers=input_workers) if input_workers is None or strategy is None: raise ValueError("input_workers and strategy are required arguments") if dataset is not None and components is not None: raise ValueError("Only one of dataset or components should be present") if dataset is None and components is None: raise ValueError("At least one of dataset or components should be passed") self._input_workers = input_workers self._strategy = strategy self._options = options self._input_context = input_context self._num_replicas_in_sync = num_replicas_in_sync if dataset is not None: self._original_dataset = dataset self._built = False if build: self.build() else: if not build: raise ValueError( "When constructing DistributedDataset with components, build " "should not be False. This is an internal error. Please file a " "bug.") if enable_get_next_as_optional is None: raise ValueError( "When constructing DistributedDataset with components, " + "enable_get_next_as_optional should also be passed") self._cloned_datasets = components self._cardinality = _cardinality(self._cloned_datasets[0]) self._enable_get_next_as_optional = enable_get_next_as_optional assert element_spec is not None if element_spec != _create_distributed_tensor_spec( self._strategy, self._cloned_datasets[0].element_spec): raise ValueError("Mismatched element_spec from the passed components") self._element_spec = element_spec self._built = True
[ "def", "__init__", "(", "self", ",", "input_workers", ",", "strategy", ",", "dataset", "=", "None", ",", "num_replicas_in_sync", "=", "None", ",", "input_context", "=", "None", ",", "components", "=", "None", ",", "element_spec", "=", "None", ",", "enable_get_next_as_optional", "=", "None", ",", "build", "=", "True", ",", "options", "=", "None", ")", ":", "super", "(", "DistributedDataset", ",", "self", ")", ".", "__init__", "(", "input_workers", "=", "input_workers", ")", "if", "input_workers", "is", "None", "or", "strategy", "is", "None", ":", "raise", "ValueError", "(", "\"input_workers and strategy are required arguments\"", ")", "if", "dataset", "is", "not", "None", "and", "components", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Only one of dataset or components should be present\"", ")", "if", "dataset", "is", "None", "and", "components", "is", "None", ":", "raise", "ValueError", "(", "\"At least one of dataset or components should be passed\"", ")", "self", ".", "_input_workers", "=", "input_workers", "self", ".", "_strategy", "=", "strategy", "self", ".", "_options", "=", "options", "self", ".", "_input_context", "=", "input_context", "self", ".", "_num_replicas_in_sync", "=", "num_replicas_in_sync", "if", "dataset", "is", "not", "None", ":", "self", ".", "_original_dataset", "=", "dataset", "self", ".", "_built", "=", "False", "if", "build", ":", "self", ".", "build", "(", ")", "else", ":", "if", "not", "build", ":", "raise", "ValueError", "(", "\"When constructing DistributedDataset with components, build \"", "\"should not be False. This is an internal error. Please file a \"", "\"bug.\"", ")", "if", "enable_get_next_as_optional", "is", "None", ":", "raise", "ValueError", "(", "\"When constructing DistributedDataset with components, \"", "+", "\"enable_get_next_as_optional should also be passed\"", ")", "self", ".", "_cloned_datasets", "=", "components", "self", ".", "_cardinality", "=", "_cardinality", "(", "self", ".", "_cloned_datasets", "[", "0", "]", ")", "self", ".", "_enable_get_next_as_optional", "=", "enable_get_next_as_optional", "assert", "element_spec", "is", "not", "None", "if", "element_spec", "!=", "_create_distributed_tensor_spec", "(", "self", ".", "_strategy", ",", "self", ".", "_cloned_datasets", "[", "0", "]", ".", "element_spec", ")", ":", "raise", "ValueError", "(", "\"Mismatched element_spec from the passed components\"", ")", "self", ".", "_element_spec", "=", "element_spec", "self", ".", "_built", "=", "True" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/input_lib.py#L960-L1047
strukturag/libheif
0082fea96ee70a20c8906a0373bedec0c01777bc
scripts/cpplint.py
python
_IncludeState.CheckNextIncludeOrder
(self, header_type)
return ''
Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong.
Returns a non-empty error message if the next header is out of order.
[ "Returns", "a", "non", "-", "empty", "error", "message", "if", "the", "next", "header", "is", "out", "of", "order", "." ]
def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong. """ error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if header_type == _C_SYS_HEADER: if self._section <= self._C_SECTION: self._section = self._C_SECTION else: self._last_header = '' return error_message elif header_type == _CPP_SYS_HEADER: if self._section <= self._CPP_SECTION: self._section = self._CPP_SECTION else: self._last_header = '' return error_message elif header_type == _LIKELY_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: self._section = self._OTHER_H_SECTION elif header_type == _POSSIBLE_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: # This will always be the fallback because we're not sure # enough that the header is associated with this file. self._section = self._OTHER_H_SECTION else: assert header_type == _OTHER_HEADER self._section = self._OTHER_H_SECTION if last_section != self._section: self._last_header = '' return ''
[ "def", "CheckNextIncludeOrder", "(", "self", ",", "header_type", ")", ":", "error_message", "=", "(", "'Found %s after %s'", "%", "(", "self", ".", "_TYPE_NAMES", "[", "header_type", "]", ",", "self", ".", "_SECTION_NAMES", "[", "self", ".", "_section", "]", ")", ")", "last_section", "=", "self", ".", "_section", "if", "header_type", "==", "_C_SYS_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_C_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_C_SECTION", "else", ":", "self", ".", "_last_header", "=", "''", "return", "error_message", "elif", "header_type", "==", "_CPP_SYS_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_CPP_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_CPP_SECTION", "else", ":", "self", ".", "_last_header", "=", "''", "return", "error_message", "elif", "header_type", "==", "_LIKELY_MY_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_MY_H_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_MY_H_SECTION", "else", ":", "self", ".", "_section", "=", "self", ".", "_OTHER_H_SECTION", "elif", "header_type", "==", "_POSSIBLE_MY_HEADER", ":", "if", "self", ".", "_section", "<=", "self", ".", "_MY_H_SECTION", ":", "self", ".", "_section", "=", "self", ".", "_MY_H_SECTION", "else", ":", "# This will always be the fallback because we're not sure", "# enough that the header is associated with this file.", "self", ".", "_section", "=", "self", ".", "_OTHER_H_SECTION", "else", ":", "assert", "header_type", "==", "_OTHER_HEADER", "self", ".", "_section", "=", "self", ".", "_OTHER_H_SECTION", "if", "last_section", "!=", "self", ".", "_section", ":", "self", ".", "_last_header", "=", "''", "return", "''" ]
https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L773-L824
emsesp/EMS-ESP
65c4a381bf8df61d1e18ba00223b1a55933fc547
scripts/esptool.py
python
ESP32FirmwareImage.default_output_name
(self, input_file)
return "%s.bin" % (os.path.splitext(input_file)[0])
Derive a default output name from the ELF name.
Derive a default output name from the ELF name.
[ "Derive", "a", "default", "output", "name", "from", "the", "ELF", "name", "." ]
def default_output_name(self, input_file): """ Derive a default output name from the ELF name. """ return "%s.bin" % (os.path.splitext(input_file)[0])
[ "def", "default_output_name", "(", "self", ",", "input_file", ")", ":", "return", "\"%s.bin\"", "%", "(", "os", ".", "path", ".", "splitext", "(", "input_file", ")", "[", "0", "]", ")" ]
https://github.com/emsesp/EMS-ESP/blob/65c4a381bf8df61d1e18ba00223b1a55933fc547/scripts/esptool.py#L1606-L1608
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/mox.py
python
Regex.equals
(self, rhs)
return self.regex.search(rhs) is not None
Check to see if rhs matches regular expression pattern. Returns: bool
Check to see if rhs matches regular expression pattern.
[ "Check", "to", "see", "if", "rhs", "matches", "regular", "expression", "pattern", "." ]
def equals(self, rhs): """Check to see if rhs matches regular expression pattern. Returns: bool """ return self.regex.search(rhs) is not None
[ "def", "equals", "(", "self", ",", "rhs", ")", ":", "return", "self", ".", "regex", ".", "search", "(", "rhs", ")", "is", "not", "None" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/mox.py#L922-L929
greatscottgadgets/gr-bluetooth
c2a7d7d810e047f8a18902a4e3d1a152420655bb
docs/doxygen/doxyxml/base.py
python
Base._get_dict_members
(self, cat=None)
return self._dict_members[cat]
For given category a dictionary is returned mapping member names to members of that category. For names that are duplicated the name is mapped to None.
For given category a dictionary is returned mapping member names to members of that category. For names that are duplicated the name is mapped to None.
[ "For", "given", "category", "a", "dictionary", "is", "returned", "mapping", "member", "names", "to", "members", "of", "that", "category", ".", "For", "names", "that", "are", "duplicated", "the", "name", "is", "mapped", "to", "None", "." ]
def _get_dict_members(self, cat=None): """ For given category a dictionary is returned mapping member names to members of that category. For names that are duplicated the name is mapped to None. """ self.confirm_no_error() if cat not in self._dict_members: new_dict = {} for mem in self.in_category(cat): if mem.name() not in new_dict: new_dict[mem.name()] = mem else: new_dict[mem.name()] = self.Duplicate self._dict_members[cat] = new_dict return self._dict_members[cat]
[ "def", "_get_dict_members", "(", "self", ",", "cat", "=", "None", ")", ":", "self", ".", "confirm_no_error", "(", ")", "if", "cat", "not", "in", "self", ".", "_dict_members", ":", "new_dict", "=", "{", "}", "for", "mem", "in", "self", ".", "in_category", "(", "cat", ")", ":", "if", "mem", ".", "name", "(", ")", "not", "in", "new_dict", ":", "new_dict", "[", "mem", ".", "name", "(", ")", "]", "=", "mem", "else", ":", "new_dict", "[", "mem", ".", "name", "(", ")", "]", "=", "self", ".", "Duplicate", "self", ".", "_dict_members", "[", "cat", "]", "=", "new_dict", "return", "self", ".", "_dict_members", "[", "cat", "]" ]
https://github.com/greatscottgadgets/gr-bluetooth/blob/c2a7d7d810e047f8a18902a4e3d1a152420655bb/docs/doxygen/doxyxml/base.py#L122-L137
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/extras/pgicc.py
python
get_pgi_version
(conf, cc)
return version[0]
Find the version of a pgi compiler.
Find the version of a pgi compiler.
[ "Find", "the", "version", "of", "a", "pgi", "compiler", "." ]
def get_pgi_version(conf, cc): """Find the version of a pgi compiler.""" version_re = re.compile(r"The Portland Group", re.I).search cmd = cc + ['-V', '-E'] # Issue 1078, prevent wrappers from linking try: out, err = conf.cmd_and_log(cmd, output=0) except Exception: conf.fatal('Could not find pgi compiler %r' % cmd) if out: match = version_re(out) else: match = version_re(err) if not match: conf.fatal('Could not verify PGI signature') cmd = cc + ['-help=variable'] try: out, err = conf.cmd_and_log(cmd, output=0) except Exception: conf.fatal('Could not find pgi compiler %r' % cmd) version = re.findall('^COMPVER\s*=(.*)', out, re.M) if len(version) != 1: conf.fatal('Could not determine the compiler version') return version[0]
[ "def", "get_pgi_version", "(", "conf", ",", "cc", ")", ":", "version_re", "=", "re", ".", "compile", "(", "r\"The Portland Group\"", ",", "re", ".", "I", ")", ".", "search", "cmd", "=", "cc", "+", "[", "'-V'", ",", "'-E'", "]", "# Issue 1078, prevent wrappers from linking", "try", ":", "out", ",", "err", "=", "conf", ".", "cmd_and_log", "(", "cmd", ",", "output", "=", "0", ")", "except", "Exception", ":", "conf", ".", "fatal", "(", "'Could not find pgi compiler %r'", "%", "cmd", ")", "if", "out", ":", "match", "=", "version_re", "(", "out", ")", "else", ":", "match", "=", "version_re", "(", "err", ")", "if", "not", "match", ":", "conf", ".", "fatal", "(", "'Could not verify PGI signature'", ")", "cmd", "=", "cc", "+", "[", "'-help=variable'", "]", "try", ":", "out", ",", "err", "=", "conf", ".", "cmd_and_log", "(", "cmd", ",", "output", "=", "0", ")", "except", "Exception", ":", "conf", ".", "fatal", "(", "'Could not find pgi compiler %r'", "%", "cmd", ")", "version", "=", "re", ".", "findall", "(", "'^COMPVER\\s*=(.*)'", ",", "out", ",", "re", ".", "M", ")", "if", "len", "(", "version", ")", "!=", "1", ":", "conf", ".", "fatal", "(", "'Could not determine the compiler version'", ")", "return", "version", "[", "0", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/pgicc.py#L35-L60
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/data_adapter.py
python
_type_name
(x)
return str(type(x))
Generates a description of the type of an object.
Generates a description of the type of an object.
[ "Generates", "a", "description", "of", "the", "type", "of", "an", "object", "." ]
def _type_name(x): """Generates a description of the type of an object.""" if isinstance(x, dict): key_types = set(_type_name(key) for key in x.keys()) val_types = set(_type_name(key) for key in x.values()) return "({} containing {} keys and {} values)".format( type(x), key_types, val_types) if isinstance(x, (list, tuple)): types = set(_type_name(val) for val in x) return "({} containing values of types {})".format( type(x), types) return str(type(x))
[ "def", "_type_name", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "dict", ")", ":", "key_types", "=", "set", "(", "_type_name", "(", "key", ")", "for", "key", "in", "x", ".", "keys", "(", ")", ")", "val_types", "=", "set", "(", "_type_name", "(", "key", ")", "for", "key", "in", "x", ".", "values", "(", ")", ")", "return", "\"({} containing {} keys and {} values)\"", ".", "format", "(", "type", "(", "x", ")", ",", "key_types", ",", "val_types", ")", "if", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "types", "=", "set", "(", "_type_name", "(", "val", ")", "for", "val", "in", "x", ")", "return", "\"({} containing values of types {})\"", ".", "format", "(", "type", "(", "x", ")", ",", "types", ")", "return", "str", "(", "type", "(", "x", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/data_adapter.py#L641-L652
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/tools/run_perf.py
python
ResultTracker.HasEnoughRuns
(self, graph_config, confidence_level)
return confidence_level * mean_stderr < mean / 1000.0
Checks if the mean of the results for a given trace config is within 0.1% of the true value with the specified confidence level. This assumes Gaussian distribution of the noise and based on https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule. Args: graph_config: An instance of GraphConfig. confidence_level: Number of standard deviations from the mean that all values must lie within. Typical values are 1, 2 and 3 and correspond to 68%, 95% and 99.7% probability that the measured value is within 0.1% of the true value. Returns: True if specified confidence level have been achieved.
Checks if the mean of the results for a given trace config is within 0.1% of the true value with the specified confidence level.
[ "Checks", "if", "the", "mean", "of", "the", "results", "for", "a", "given", "trace", "config", "is", "within", "0", ".", "1%", "of", "the", "true", "value", "with", "the", "specified", "confidence", "level", "." ]
def HasEnoughRuns(self, graph_config, confidence_level): """Checks if the mean of the results for a given trace config is within 0.1% of the true value with the specified confidence level. This assumes Gaussian distribution of the noise and based on https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule. Args: graph_config: An instance of GraphConfig. confidence_level: Number of standard deviations from the mean that all values must lie within. Typical values are 1, 2 and 3 and correspond to 68%, 95% and 99.7% probability that the measured value is within 0.1% of the true value. Returns: True if specified confidence level have been achieved. """ if not isinstance(graph_config, TraceConfig): return all(self.HasEnoughRuns(child, confidence_level) for child in graph_config.children) trace = self.traces.get(graph_config.name, {}) results = trace.get('results', []) logging.debug('HasEnoughRuns for %s', graph_config.name) if len(results) < MIN_RUNS_FOR_CONFIDENCE: logging.debug(' Ran %d times, need at least %d', len(results), MIN_RUNS_FOR_CONFIDENCE) return False logging.debug(' Results: %d entries', len(results)) mean = numpy.mean(results) mean_stderr = numpy.std(results) / numpy.sqrt(len(results)) logging.debug(' Mean: %.2f, mean_stderr: %.2f', mean, mean_stderr) logging.info('>>> Confidence level is %.2f', mean / (1000.0 * mean_stderr)) return confidence_level * mean_stderr < mean / 1000.0
[ "def", "HasEnoughRuns", "(", "self", ",", "graph_config", ",", "confidence_level", ")", ":", "if", "not", "isinstance", "(", "graph_config", ",", "TraceConfig", ")", ":", "return", "all", "(", "self", ".", "HasEnoughRuns", "(", "child", ",", "confidence_level", ")", "for", "child", "in", "graph_config", ".", "children", ")", "trace", "=", "self", ".", "traces", ".", "get", "(", "graph_config", ".", "name", ",", "{", "}", ")", "results", "=", "trace", ".", "get", "(", "'results'", ",", "[", "]", ")", "logging", ".", "debug", "(", "'HasEnoughRuns for %s'", ",", "graph_config", ".", "name", ")", "if", "len", "(", "results", ")", "<", "MIN_RUNS_FOR_CONFIDENCE", ":", "logging", ".", "debug", "(", "' Ran %d times, need at least %d'", ",", "len", "(", "results", ")", ",", "MIN_RUNS_FOR_CONFIDENCE", ")", "return", "False", "logging", ".", "debug", "(", "' Results: %d entries'", ",", "len", "(", "results", ")", ")", "mean", "=", "numpy", ".", "mean", "(", "results", ")", "mean_stderr", "=", "numpy", ".", "std", "(", "results", ")", "/", "numpy", ".", "sqrt", "(", "len", "(", "results", ")", ")", "logging", ".", "debug", "(", "' Mean: %.2f, mean_stderr: %.2f'", ",", "mean", ",", "mean_stderr", ")", "logging", ".", "info", "(", "'>>> Confidence level is %.2f'", ",", "mean", "/", "(", "1000.0", "*", "mean_stderr", ")", ")", "return", "confidence_level", "*", "mean_stderr", "<", "mean", "/", "1000.0" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/tools/run_perf.py#L235-L270
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageFilter.py
python
Color3DLUT.transform
(self, callback, with_normals=False, channels=None, target_mode=None)
return type(self)( self.size, table, channels=ch_out, target_mode=target_mode or self.mode, _copy_table=False, )
Transforms the table values using provided callback and returns a new LUT with altered values. :param callback: A function which takes old lookup table values and returns a new set of values. The number of arguments which function should take is ``self.channels`` or ``3 + self.channels`` if ``with_normals`` flag is set. Should return a tuple of ``self.channels`` or ``channels`` elements if it is set. :param with_normals: If true, ``callback`` will be called with coordinates in the color cube as the first three arguments. Otherwise, ``callback`` will be called only with actual color values. :param channels: The number of channels in the resulting lookup table. :param target_mode: Passed to the constructor of the resulting lookup table.
Transforms the table values using provided callback and returns a new LUT with altered values.
[ "Transforms", "the", "table", "values", "using", "provided", "callback", "and", "returns", "a", "new", "LUT", "with", "altered", "values", "." ]
def transform(self, callback, with_normals=False, channels=None, target_mode=None): """Transforms the table values using provided callback and returns a new LUT with altered values. :param callback: A function which takes old lookup table values and returns a new set of values. The number of arguments which function should take is ``self.channels`` or ``3 + self.channels`` if ``with_normals`` flag is set. Should return a tuple of ``self.channels`` or ``channels`` elements if it is set. :param with_normals: If true, ``callback`` will be called with coordinates in the color cube as the first three arguments. Otherwise, ``callback`` will be called only with actual color values. :param channels: The number of channels in the resulting lookup table. :param target_mode: Passed to the constructor of the resulting lookup table. """ if channels not in (None, 3, 4): raise ValueError("Only 3 or 4 output channels are supported") ch_in = self.channels ch_out = channels or ch_in size1D, size2D, size3D = self.size table = [0] * (size1D * size2D * size3D * ch_out) idx_in = 0 idx_out = 0 for b in range(size3D): for g in range(size2D): for r in range(size1D): values = self.table[idx_in : idx_in + ch_in] if with_normals: values = callback( r / (size1D - 1), g / (size2D - 1), b / (size3D - 1), *values, ) else: values = callback(*values) table[idx_out : idx_out + ch_out] = values idx_in += ch_in idx_out += ch_out return type(self)( self.size, table, channels=ch_out, target_mode=target_mode or self.mode, _copy_table=False, )
[ "def", "transform", "(", "self", ",", "callback", ",", "with_normals", "=", "False", ",", "channels", "=", "None", ",", "target_mode", "=", "None", ")", ":", "if", "channels", "not", "in", "(", "None", ",", "3", ",", "4", ")", ":", "raise", "ValueError", "(", "\"Only 3 or 4 output channels are supported\"", ")", "ch_in", "=", "self", ".", "channels", "ch_out", "=", "channels", "or", "ch_in", "size1D", ",", "size2D", ",", "size3D", "=", "self", ".", "size", "table", "=", "[", "0", "]", "*", "(", "size1D", "*", "size2D", "*", "size3D", "*", "ch_out", ")", "idx_in", "=", "0", "idx_out", "=", "0", "for", "b", "in", "range", "(", "size3D", ")", ":", "for", "g", "in", "range", "(", "size2D", ")", ":", "for", "r", "in", "range", "(", "size1D", ")", ":", "values", "=", "self", ".", "table", "[", "idx_in", ":", "idx_in", "+", "ch_in", "]", "if", "with_normals", ":", "values", "=", "callback", "(", "r", "/", "(", "size1D", "-", "1", ")", ",", "g", "/", "(", "size2D", "-", "1", ")", ",", "b", "/", "(", "size3D", "-", "1", ")", ",", "*", "values", ",", ")", "else", ":", "values", "=", "callback", "(", "*", "values", ")", "table", "[", "idx_out", ":", "idx_out", "+", "ch_out", "]", "=", "values", "idx_in", "+=", "ch_in", "idx_out", "+=", "ch_out", "return", "type", "(", "self", ")", "(", "self", ".", "size", ",", "table", ",", "channels", "=", "ch_out", ",", "target_mode", "=", "target_mode", "or", "self", ".", "mode", ",", "_copy_table", "=", "False", ",", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageFilter.py#L461-L512
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/assembly_graph.py
python
AssemblyGraph.find_all_simple_loops
(self)
return simple_loops
This function finds all cases of a simple loop in the graph: A->B->C->B->D. It returns them as a list of 4-tuples of segment numbers in this order: (start, end, middle, repeat).
This function finds all cases of a simple loop in the graph: A->B->C->B->D. It returns them as a list of 4-tuples of segment numbers in this order: (start, end, middle, repeat).
[ "This", "function", "finds", "all", "cases", "of", "a", "simple", "loop", "in", "the", "graph", ":", "A", "-", ">", "B", "-", ">", "C", "-", ">", "B", "-", ">", "D", ".", "It", "returns", "them", "as", "a", "list", "of", "4", "-", "tuples", "of", "segment", "numbers", "in", "this", "order", ":", "(", "start", "end", "middle", "repeat", ")", "." ]
def find_all_simple_loops(self): """ This function finds all cases of a simple loop in the graph: A->B->C->B->D. It returns them as a list of 4-tuples of segment numbers in this order: (start, end, middle, repeat). """ simple_loops = [] # We'll search specifically for the middle segments as they should be easy to spot. for middle in self.segments: if self.segments[middle].get_length() > settings.MAX_SIMPLE_LOOP_SIZE: continue # A middle segment will always have exactly one connection on each end which connect # to the same segment (the repeat segment). if middle not in self.forward_links or middle not in self.reverse_links: continue if len(self.forward_links[middle]) != 1 or len(self.reverse_links[middle]) != 1: continue if self.forward_links[middle][0] != self.reverse_links[middle][0]: continue repeat = self.forward_links[middle][0] # The repeat segment should have exactly two connections on each end. If less, then we # have a simple path which can be merged. If more, it's a more complex loop. if len(self.forward_links[repeat]) != 2 or len(self.reverse_links[repeat]) != 2: continue # Find the start and end segment numbers. It's okay if the start and the end are the # same, but we exclude any other screwy cases where the start or end is the middle or # repeat segment. start = self.reverse_links[repeat][0] if abs(start) == abs(middle): start = self.reverse_links[repeat][1] if abs(start) == abs(middle) or abs(start) == abs(repeat): continue end = self.forward_links[repeat][0] if abs(end) == abs(middle): end = self.forward_links[repeat][1] if abs(end) == abs(middle) or abs(end) == abs(repeat): continue simple_loops.append((start, end, middle, repeat)) # Simple loops may just have the repeat node loop back to itself (i.e. no separate middle # segment). Look for these structures. for repeat in self.segments: if repeat not in self.forward_links or repeat not in self.reverse_links or \ len(self.forward_links[repeat]) != 2 or len(self.reverse_links[repeat]) != 2: continue # Make sure that the repeat loops back to itself. if repeat not in self.forward_links[repeat] or repeat not in self.reverse_links[repeat]: continue start_segs = list(self.reverse_links[repeat]) start_segs.remove(repeat) end_segs = list(self.forward_links[repeat]) end_segs.remove(repeat) if len(start_segs) != 1 or len(end_segs) != 1: continue start = start_segs[0] end = end_segs[0] if abs(start) == abs(repeat) or abs(end) == abs(repeat): continue simple_loops.append((start, end, None, repeat)) return simple_loops
[ "def", "find_all_simple_loops", "(", "self", ")", ":", "simple_loops", "=", "[", "]", "# We'll search specifically for the middle segments as they should be easy to spot.", "for", "middle", "in", "self", ".", "segments", ":", "if", "self", ".", "segments", "[", "middle", "]", ".", "get_length", "(", ")", ">", "settings", ".", "MAX_SIMPLE_LOOP_SIZE", ":", "continue", "# A middle segment will always have exactly one connection on each end which connect", "# to the same segment (the repeat segment).", "if", "middle", "not", "in", "self", ".", "forward_links", "or", "middle", "not", "in", "self", ".", "reverse_links", ":", "continue", "if", "len", "(", "self", ".", "forward_links", "[", "middle", "]", ")", "!=", "1", "or", "len", "(", "self", ".", "reverse_links", "[", "middle", "]", ")", "!=", "1", ":", "continue", "if", "self", ".", "forward_links", "[", "middle", "]", "[", "0", "]", "!=", "self", ".", "reverse_links", "[", "middle", "]", "[", "0", "]", ":", "continue", "repeat", "=", "self", ".", "forward_links", "[", "middle", "]", "[", "0", "]", "# The repeat segment should have exactly two connections on each end. If less, then we", "# have a simple path which can be merged. If more, it's a more complex loop.", "if", "len", "(", "self", ".", "forward_links", "[", "repeat", "]", ")", "!=", "2", "or", "len", "(", "self", ".", "reverse_links", "[", "repeat", "]", ")", "!=", "2", ":", "continue", "# Find the start and end segment numbers. It's okay if the start and the end are the", "# same, but we exclude any other screwy cases where the start or end is the middle or", "# repeat segment.", "start", "=", "self", ".", "reverse_links", "[", "repeat", "]", "[", "0", "]", "if", "abs", "(", "start", ")", "==", "abs", "(", "middle", ")", ":", "start", "=", "self", ".", "reverse_links", "[", "repeat", "]", "[", "1", "]", "if", "abs", "(", "start", ")", "==", "abs", "(", "middle", ")", "or", "abs", "(", "start", ")", "==", "abs", "(", "repeat", ")", ":", "continue", "end", "=", "self", ".", "forward_links", "[", "repeat", "]", "[", "0", "]", "if", "abs", "(", "end", ")", "==", "abs", "(", "middle", ")", ":", "end", "=", "self", ".", "forward_links", "[", "repeat", "]", "[", "1", "]", "if", "abs", "(", "end", ")", "==", "abs", "(", "middle", ")", "or", "abs", "(", "end", ")", "==", "abs", "(", "repeat", ")", ":", "continue", "simple_loops", ".", "append", "(", "(", "start", ",", "end", ",", "middle", ",", "repeat", ")", ")", "# Simple loops may just have the repeat node loop back to itself (i.e. no separate middle", "# segment). Look for these structures.", "for", "repeat", "in", "self", ".", "segments", ":", "if", "repeat", "not", "in", "self", ".", "forward_links", "or", "repeat", "not", "in", "self", ".", "reverse_links", "or", "len", "(", "self", ".", "forward_links", "[", "repeat", "]", ")", "!=", "2", "or", "len", "(", "self", ".", "reverse_links", "[", "repeat", "]", ")", "!=", "2", ":", "continue", "# Make sure that the repeat loops back to itself.", "if", "repeat", "not", "in", "self", ".", "forward_links", "[", "repeat", "]", "or", "repeat", "not", "in", "self", ".", "reverse_links", "[", "repeat", "]", ":", "continue", "start_segs", "=", "list", "(", "self", ".", "reverse_links", "[", "repeat", "]", ")", "start_segs", ".", "remove", "(", "repeat", ")", "end_segs", "=", "list", "(", "self", ".", "forward_links", "[", "repeat", "]", ")", "end_segs", ".", "remove", "(", "repeat", ")", "if", "len", "(", "start_segs", ")", "!=", "1", "or", "len", "(", "end_segs", ")", "!=", "1", ":", "continue", "start", "=", "start_segs", "[", "0", "]", "end", "=", "end_segs", "[", "0", "]", "if", "abs", "(", "start", ")", "==", "abs", "(", "repeat", ")", "or", "abs", "(", "end", ")", "==", "abs", "(", "repeat", ")", ":", "continue", "simple_loops", ".", "append", "(", "(", "start", ",", "end", ",", "None", ",", "repeat", ")", ")", "return", "simple_loops" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/assembly_graph.py#L1535-L1604
opengauss-mirror/openGauss-server
e383f1b77720a00ddbe4c0655bc85914d9b02a2b
src/gausskernel/dbmind/tools/index_advisor/index_advisor_workload.py
python
read_input_from_pipe
()
return input_str
Read stdin input if there is "echo 'str1 str2' | python xx.py", return the input string
Read stdin input if there is "echo 'str1 str2' | python xx.py", return the input string
[ "Read", "stdin", "input", "if", "there", "is", "echo", "str1", "str2", "|", "python", "xx", ".", "py", "return", "the", "input", "string" ]
def read_input_from_pipe(): """ Read stdin input if there is "echo 'str1 str2' | python xx.py", return the input string """ input_str = "" r_handle, _, _ = select.select([sys.stdin], [], [], 0) if not r_handle: return "" for item in r_handle: if item == sys.stdin: input_str = sys.stdin.read().strip() return input_str
[ "def", "read_input_from_pipe", "(", ")", ":", "input_str", "=", "\"\"", "r_handle", ",", "_", ",", "_", "=", "select", ".", "select", "(", "[", "sys", ".", "stdin", "]", ",", "[", "]", ",", "[", "]", ",", "0", ")", "if", "not", "r_handle", ":", "return", "\"\"", "for", "item", "in", "r_handle", ":", "if", "item", "==", "sys", ".", "stdin", ":", "input_str", "=", "sys", ".", "stdin", ".", "read", "(", ")", ".", "strip", "(", ")", "return", "input_str" ]
https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/index_advisor/index_advisor_workload.py#L59-L72
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/data_generator/data_generator.py
python
DataGenerator.run_from_stdin
(self)
This function reads the data row from stdin, parses it with the process function, and further parses the return value of the process function with the _gen_str function. The parsed data will be wrote to stdout and the corresponding protofile will be generated. Example: .. code-block:: python import paddle.distributed.fleet.data_generator as dg class MyData(dg.DataGenerator): def generate_sample(self, line): def local_iter(): int_words = [int(x) for x in line.split()] yield ("words", [int_words]) return local_iter mydata = MyData() mydata.run_from_stdin()
This function reads the data row from stdin, parses it with the process function, and further parses the return value of the process function with the _gen_str function. The parsed data will be wrote to stdout and the corresponding protofile will be generated.
[ "This", "function", "reads", "the", "data", "row", "from", "stdin", "parses", "it", "with", "the", "process", "function", "and", "further", "parses", "the", "return", "value", "of", "the", "process", "function", "with", "the", "_gen_str", "function", ".", "The", "parsed", "data", "will", "be", "wrote", "to", "stdout", "and", "the", "corresponding", "protofile", "will", "be", "generated", "." ]
def run_from_stdin(self): ''' This function reads the data row from stdin, parses it with the process function, and further parses the return value of the process function with the _gen_str function. The parsed data will be wrote to stdout and the corresponding protofile will be generated. Example: .. code-block:: python import paddle.distributed.fleet.data_generator as dg class MyData(dg.DataGenerator): def generate_sample(self, line): def local_iter(): int_words = [int(x) for x in line.split()] yield ("words", [int_words]) return local_iter mydata = MyData() mydata.run_from_stdin() ''' batch_samples = [] for line in sys.stdin: line_iter = self.generate_sample(line) for user_parsed_line in line_iter(): if user_parsed_line == None: continue batch_samples.append(user_parsed_line) if len(batch_samples) == self.batch_size_: batch_iter = self.generate_batch(batch_samples) for sample in batch_iter(): sys.stdout.write(self._gen_str(sample)) batch_samples = [] if len(batch_samples) > 0: batch_iter = self.generate_batch(batch_samples) for sample in batch_iter(): sys.stdout.write(self._gen_str(sample))
[ "def", "run_from_stdin", "(", "self", ")", ":", "batch_samples", "=", "[", "]", "for", "line", "in", "sys", ".", "stdin", ":", "line_iter", "=", "self", ".", "generate_sample", "(", "line", ")", "for", "user_parsed_line", "in", "line_iter", "(", ")", ":", "if", "user_parsed_line", "==", "None", ":", "continue", "batch_samples", ".", "append", "(", "user_parsed_line", ")", "if", "len", "(", "batch_samples", ")", "==", "self", ".", "batch_size_", ":", "batch_iter", "=", "self", ".", "generate_batch", "(", "batch_samples", ")", "for", "sample", "in", "batch_iter", "(", ")", ":", "sys", ".", "stdout", ".", "write", "(", "self", ".", "_gen_str", "(", "sample", ")", ")", "batch_samples", "=", "[", "]", "if", "len", "(", "batch_samples", ")", ">", "0", ":", "batch_iter", "=", "self", ".", "generate_batch", "(", "batch_samples", ")", "for", "sample", "in", "batch_iter", "(", ")", ":", "sys", ".", "stdout", ".", "write", "(", "self", ".", "_gen_str", "(", "sample", ")", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/data_generator/data_generator.py#L96-L136
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/lib2def.py
python
parse_cmd
()
return libfile, deffile
Parses the command-line arguments. libfile, deffile = parse_cmd()
Parses the command-line arguments.
[ "Parses", "the", "command", "-", "line", "arguments", "." ]
def parse_cmd(): """Parses the command-line arguments. libfile, deffile = parse_cmd()""" if len(sys.argv) == 3: if sys.argv[1][-4:] == '.lib' and sys.argv[2][-4:] == '.def': libfile, deffile = sys.argv[1:] elif sys.argv[1][-4:] == '.def' and sys.argv[2][-4:] == '.lib': deffile, libfile = sys.argv[1:] else: print("I'm assuming that your first argument is the library") print("and the second is the DEF file.") elif len(sys.argv) == 2: if sys.argv[1][-4:] == '.def': deffile = sys.argv[1] libfile = 'python%s.lib' % py_ver elif sys.argv[1][-4:] == '.lib': deffile = None libfile = sys.argv[1] else: libfile = 'python%s.lib' % py_ver deffile = None return libfile, deffile
[ "def", "parse_cmd", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "==", "3", ":", "if", "sys", ".", "argv", "[", "1", "]", "[", "-", "4", ":", "]", "==", "'.lib'", "and", "sys", ".", "argv", "[", "2", "]", "[", "-", "4", ":", "]", "==", "'.def'", ":", "libfile", ",", "deffile", "=", "sys", ".", "argv", "[", "1", ":", "]", "elif", "sys", ".", "argv", "[", "1", "]", "[", "-", "4", ":", "]", "==", "'.def'", "and", "sys", ".", "argv", "[", "2", "]", "[", "-", "4", ":", "]", "==", "'.lib'", ":", "deffile", ",", "libfile", "=", "sys", ".", "argv", "[", "1", ":", "]", "else", ":", "print", "(", "\"I'm assuming that your first argument is the library\"", ")", "print", "(", "\"and the second is the DEF file.\"", ")", "elif", "len", "(", "sys", ".", "argv", ")", "==", "2", ":", "if", "sys", ".", "argv", "[", "1", "]", "[", "-", "4", ":", "]", "==", "'.def'", ":", "deffile", "=", "sys", ".", "argv", "[", "1", "]", "libfile", "=", "'python%s.lib'", "%", "py_ver", "elif", "sys", ".", "argv", "[", "1", "]", "[", "-", "4", ":", "]", "==", "'.lib'", ":", "deffile", "=", "None", "libfile", "=", "sys", ".", "argv", "[", "1", "]", "else", ":", "libfile", "=", "'python%s.lib'", "%", "py_ver", "deffile", "=", "None", "return", "libfile", ",", "deffile" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/distutils/lib2def.py#L40-L62
vtraag/louvain-igraph
124ea1be49ee74eec2eaca8006599d7fc5560db6
src/louvain/VertexPartition.py
python
MutableVertexPartition.total_weight_to_comm
(self, comm)
return _c_louvain._MutableVertexPartition_total_weight_to_comm(self._partition, comm)
The total weight (i.e. number of edges) to a community. Parameters ---------- comm Community Notes ----- This includes all edges, also the ones that are internal to a community. Sometimes this is also referred to as the community (in)degree. See Also -------- :func:`~VertexPartition.MutableVertexPartition.total_weight_from_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_in_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_in_all_comms`
The total weight (i.e. number of edges) to a community.
[ "The", "total", "weight", "(", "i", ".", "e", ".", "number", "of", "edges", ")", "to", "a", "community", "." ]
def total_weight_to_comm(self, comm): """ The total weight (i.e. number of edges) to a community. Parameters ---------- comm Community Notes ----- This includes all edges, also the ones that are internal to a community. Sometimes this is also referred to as the community (in)degree. See Also -------- :func:`~VertexPartition.MutableVertexPartition.total_weight_from_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_in_comm` :func:`~VertexPartition.MutableVertexPartition.total_weight_in_all_comms` """ return _c_louvain._MutableVertexPartition_total_weight_to_comm(self._partition, comm)
[ "def", "total_weight_to_comm", "(", "self", ",", "comm", ")", ":", "return", "_c_louvain", ".", "_MutableVertexPartition_total_weight_to_comm", "(", "self", ".", "_partition", ",", "comm", ")" ]
https://github.com/vtraag/louvain-igraph/blob/124ea1be49ee74eec2eaca8006599d7fc5560db6/src/louvain/VertexPartition.py#L311-L332
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/nn/modules/container.py
python
ParameterDict.items
(self)
return self._parameters.items()
r"""Return an iterable of the ParameterDict key/value pairs.
r"""Return an iterable of the ParameterDict key/value pairs.
[ "r", "Return", "an", "iterable", "of", "the", "ParameterDict", "key", "/", "value", "pairs", "." ]
def items(self) -> Iterable[Tuple[str, 'Parameter']]: r"""Return an iterable of the ParameterDict key/value pairs. """ return self._parameters.items()
[ "def", "items", "(", "self", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "'Parameter'", "]", "]", ":", "return", "self", ".", "_parameters", ".", "items", "(", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/modules/container.py#L691-L694
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/adb_install_apk.py
python
AddInstallAPKOption
(option_parser)
Adds apk option used to install the APK to the OptionParser.
Adds apk option used to install the APK to the OptionParser.
[ "Adds", "apk", "option", "used", "to", "install", "the", "APK", "to", "the", "OptionParser", "." ]
def AddInstallAPKOption(option_parser): """Adds apk option used to install the APK to the OptionParser.""" test_options_parser.AddBuildTypeOption(option_parser) option_parser.add_option('--apk', help=('The name of the apk containing the ' ' application (with the .apk extension).')) option_parser.add_option('--apk_package', help=('The package name used by the apk containing ' 'the application.')) option_parser.add_option('--keep_data', action='store_true', default=False, help=('Keep the package data when installing ' 'the application.'))
[ "def", "AddInstallAPKOption", "(", "option_parser", ")", ":", "test_options_parser", ".", "AddBuildTypeOption", "(", "option_parser", ")", "option_parser", ".", "add_option", "(", "'--apk'", ",", "help", "=", "(", "'The name of the apk containing the '", "' application (with the .apk extension).'", ")", ")", "option_parser", ".", "add_option", "(", "'--apk_package'", ",", "help", "=", "(", "'The package name used by the apk containing '", "'the application.'", ")", ")", "option_parser", ".", "add_option", "(", "'--keep_data'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "(", "'Keep the package data when installing '", "'the application.'", ")", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/adb_install_apk.py#L20-L33
3drobotics/ardupilot-solo
05a123b002c11dccc905d4d7703a38e5f36ee723
mk/PX4/Tools/genmsg/src/genmsg/msg_loader.py
python
load_msg_from_file
(msg_context, file_path, full_name)
Convert the .msg representation in the file to a :class:`MsgSpec` instance. NOTE: this will register the message in the *msg_context*. :param file_path: path of file to load from, ``str`` :returns: :class:`MsgSpec` instance :raises: :exc:`InvalidMsgSpec`: if syntax errors or other problems are detected in file
Convert the .msg representation in the file to a :class:`MsgSpec` instance.
[ "Convert", "the", ".", "msg", "representation", "in", "the", "file", "to", "a", ":", "class", ":", "MsgSpec", "instance", "." ]
def load_msg_from_file(msg_context, file_path, full_name): """ Convert the .msg representation in the file to a :class:`MsgSpec` instance. NOTE: this will register the message in the *msg_context*. :param file_path: path of file to load from, ``str`` :returns: :class:`MsgSpec` instance :raises: :exc:`InvalidMsgSpec`: if syntax errors or other problems are detected in file """ log("Load spec from", file_path) with open(file_path, 'r') as f: text = f.read() try: return load_msg_from_string(msg_context, text, full_name) except InvalidMsgSpec as e: raise InvalidMsgSpec('%s: %s'%(file_path, e))
[ "def", "load_msg_from_file", "(", "msg_context", ",", "file_path", ",", "full_name", ")", ":", "log", "(", "\"Load spec from\"", ",", "file_path", ")", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "try", ":", "return", "load_msg_from_string", "(", "msg_context", ",", "text", ",", "full_name", ")", "except", "InvalidMsgSpec", "as", "e", ":", "raise", "InvalidMsgSpec", "(", "'%s: %s'", "%", "(", "file_path", ",", "e", ")", ")" ]
https://github.com/3drobotics/ardupilot-solo/blob/05a123b002c11dccc905d4d7703a38e5f36ee723/mk/PX4/Tools/genmsg/src/genmsg/msg_loader.py#L268-L284
google/sling
f408a148a06bc2d62e853a292a8ba7266c642839
python/task/workflow.py
python
Scope.prefix
(self)
return '/'.join(reversed(parts))
Returns the name prefix defined in the scope by concatenating all nested name spaces.
Returns the name prefix defined in the scope by concatenating all nested name spaces.
[ "Returns", "the", "name", "prefix", "defined", "in", "the", "scope", "by", "concatenating", "all", "nested", "name", "spaces", "." ]
def prefix(self): """Returns the name prefix defined in the scope by concatenating all nested name spaces.""" parts = [] s = self while s != None: parts.append(s.name) s = s.prev return '/'.join(reversed(parts))
[ "def", "prefix", "(", "self", ")", ":", "parts", "=", "[", "]", "s", "=", "self", "while", "s", "!=", "None", ":", "parts", ".", "append", "(", "s", ".", "name", ")", "s", "=", "s", ".", "prev", "return", "'/'", ".", "join", "(", "reversed", "(", "parts", ")", ")" ]
https://github.com/google/sling/blob/f408a148a06bc2d62e853a292a8ba7266c642839/python/task/workflow.py#L266-L274
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TMemIn.New
(*args)
return _snap.TMemIn_New(*args)
New(TMem Mem) -> PSIn Parameters: Mem: TMem const & New(PMem const & Mem) -> PSIn Parameters: Mem: PMem const &
New(TMem Mem) -> PSIn
[ "New", "(", "TMem", "Mem", ")", "-", ">", "PSIn" ]
def New(*args): """ New(TMem Mem) -> PSIn Parameters: Mem: TMem const & New(PMem const & Mem) -> PSIn Parameters: Mem: PMem const & """ return _snap.TMemIn_New(*args)
[ "def", "New", "(", "*", "args", ")", ":", "return", "_snap", ".", "TMemIn_New", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L8361-L8374
KhronosGroup/SPIR
f33c27876d9f3d5810162b60fa89cc13d2b55725
bindings/python/clang/cindex.py
python
Config.set_library_file
(file)
Set the exact location of libclang from
Set the exact location of libclang from
[ "Set", "the", "exact", "location", "of", "libclang", "from" ]
def set_library_file(file): """Set the exact location of libclang from""" if Config.loaded: raise Exception("library file must be set before before using " \ "any other functionalities in libclang.") Config.library_file = path
[ "def", "set_library_file", "(", "file", ")", ":", "if", "Config", ".", "loaded", ":", "raise", "Exception", "(", "\"library file must be set before before using \"", "\"any other functionalities in libclang.\"", ")", "Config", ".", "library_file", "=", "path" ]
https://github.com/KhronosGroup/SPIR/blob/f33c27876d9f3d5810162b60fa89cc13d2b55725/bindings/python/clang/cindex.py#L3049-L3055
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
vtr_flow/scripts/python_libs/vtr/parse_vtr_task.py
python
calculate_individual_geo_mean
(lines, index, geo_mean, num)
return geo_mean, num, previous_value
Calculate an individual line of parse results goe_mean
Calculate an individual line of parse results goe_mean
[ "Calculate", "an", "individual", "line", "of", "parse", "results", "goe_mean" ]
def calculate_individual_geo_mean(lines, index, geo_mean, num): """Calculate an individual line of parse results goe_mean""" previous_value = None for line in lines: line = line.split("\t")[4:] current_value = line[index] try: if float(current_value) > 0: geo_mean *= float(current_value) num += 1 except ValueError: if not previous_value: previous_value = current_value elif current_value != previous_value: previous_value = "-1" return geo_mean, num, previous_value
[ "def", "calculate_individual_geo_mean", "(", "lines", ",", "index", ",", "geo_mean", ",", "num", ")", ":", "previous_value", "=", "None", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "split", "(", "\"\\t\"", ")", "[", "4", ":", "]", "current_value", "=", "line", "[", "index", "]", "try", ":", "if", "float", "(", "current_value", ")", ">", "0", ":", "geo_mean", "*=", "float", "(", "current_value", ")", "num", "+=", "1", "except", "ValueError", ":", "if", "not", "previous_value", ":", "previous_value", "=", "current_value", "elif", "current_value", "!=", "previous_value", ":", "previous_value", "=", "\"-1\"", "return", "geo_mean", ",", "num", ",", "previous_value" ]
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/parse_vtr_task.py#L535-L550
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Colour.Green
(*args, **kwargs)
return _gdi_.Colour_Green(*args, **kwargs)
Green(self) -> byte Returns the green intensity.
Green(self) -> byte
[ "Green", "(", "self", ")", "-", ">", "byte" ]
def Green(*args, **kwargs): """ Green(self) -> byte Returns the green intensity. """ return _gdi_.Colour_Green(*args, **kwargs)
[ "def", "Green", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Colour_Green", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L141-L147
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/util/statistics.py
python
StandardDeviation
(data)
return std_dev
Calculates the standard deviation. Args: data: A list of samples. Returns: The standard deviation of the samples provided.
Calculates the standard deviation.
[ "Calculates", "the", "standard", "deviation", "." ]
def StandardDeviation(data): """Calculates the standard deviation. Args: data: A list of samples. Returns: The standard deviation of the samples provided. """ if len(data) == 1: return 0.0 mean = ArithmeticMean(data) variances = [float(x) - mean for x in data] variances = [x * x for x in variances] std_dev = math.sqrt(ArithmeticMean(variances)) return std_dev
[ "def", "StandardDeviation", "(", "data", ")", ":", "if", "len", "(", "data", ")", "==", "1", ":", "return", "0.0", "mean", "=", "ArithmeticMean", "(", "data", ")", "variances", "=", "[", "float", "(", "x", ")", "-", "mean", "for", "x", "in", "data", "]", "variances", "=", "[", "x", "*", "x", "for", "x", "in", "variances", "]", "std_dev", "=", "math", ".", "sqrt", "(", "ArithmeticMean", "(", "variances", ")", ")", "return", "std_dev" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/util/statistics.py#L218-L235
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py
python
Kernel.n_dims
(self)
return self.theta.shape[0]
Returns the number of non-fixed hyperparameters of the kernel.
Returns the number of non-fixed hyperparameters of the kernel.
[ "Returns", "the", "number", "of", "non", "-", "fixed", "hyperparameters", "of", "the", "kernel", "." ]
def n_dims(self): """Returns the number of non-fixed hyperparameters of the kernel.""" return self.theta.shape[0]
[ "def", "n_dims", "(", "self", ")", ":", "return", "self", ".", "theta", ".", "shape", "[", "0", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/gaussian_process/kernels.py#L208-L210
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/RecoTrack/python/plotting/ntupleDataFormat.py
python
TrackingVertex.__init__
(self, tree, index)
Constructor. Arguments: tree -- TTree object index -- Index of the TrackingVertex
Constructor.
[ "Constructor", "." ]
def __init__(self, tree, index): """Constructor. Arguments: tree -- TTree object index -- Index of the TrackingVertex """ super(TrackingVertex, self).__init__(tree, index, "simvtx")
[ "def", "__init__", "(", "self", ",", "tree", ",", "index", ")", ":", "super", "(", "TrackingVertex", ",", "self", ")", ".", "__init__", "(", "tree", ",", "index", ",", "\"simvtx\"", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/ntupleDataFormat.py#L1135-L1142
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sas/sas_xport.py
python
_parse_float_vec
(vec)
return ieee
Parse a vector of float values representing IBM 8 byte floats into native 8 byte floats.
Parse a vector of float values representing IBM 8 byte floats into native 8 byte floats.
[ "Parse", "a", "vector", "of", "float", "values", "representing", "IBM", "8", "byte", "floats", "into", "native", "8", "byte", "floats", "." ]
def _parse_float_vec(vec): """ Parse a vector of float values representing IBM 8 byte floats into native 8 byte floats. """ dtype = np.dtype(">u4,>u4") vec1 = vec.view(dtype=dtype) xport1 = vec1["f0"] xport2 = vec1["f1"] # Start by setting first half of ieee number to first half of IBM # number sans exponent ieee1 = xport1 & 0x00FFFFFF # The fraction bit to the left of the binary point in the ieee # format was set and the number was shifted 0, 1, 2, or 3 # places. This will tell us how to adjust the ibm exponent to be a # power of 2 ieee exponent and how to shift the fraction bits to # restore the correct magnitude. shift = np.zeros(len(vec), dtype=np.uint8) shift[np.where(xport1 & 0x00200000)] = 1 shift[np.where(xport1 & 0x00400000)] = 2 shift[np.where(xport1 & 0x00800000)] = 3 # shift the ieee number down the correct number of places then # set the second half of the ieee number to be the second half # of the ibm number shifted appropriately, ored with the bits # from the first half that would have been shifted in if we # could shift a double. All we are worried about are the low # order 3 bits of the first half since we're only shifting by # 1, 2, or 3. ieee1 >>= shift ieee2 = (xport2 >> shift) | ((xport1 & 0x00000007) << (29 + (3 - shift))) # clear the 1 bit to the left of the binary point ieee1 &= 0xFFEFFFFF # set the exponent of the ieee number to be the actual exponent # plus the shift count + 1023. Or this into the first half of the # ieee number. The ibm exponent is excess 64 but is adjusted by 65 # since during conversion to ibm format the exponent is # incremented by 1 and the fraction bits left 4 positions to the # right of the radix point. (had to add >> 24 because C treats & # 0x7f as 0x7f000000 and Python doesn't) ieee1 |= ((((((xport1 >> 24) & 0x7F) - 65) << 2) + shift + 1023) << 20) | ( xport1 & 0x80000000 ) ieee = np.empty((len(ieee1),), dtype=">u4,>u4") ieee["f0"] = ieee1 ieee["f1"] = ieee2 ieee = ieee.view(dtype=">f8") ieee = ieee.astype("f8") return ieee
[ "def", "_parse_float_vec", "(", "vec", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "\">u4,>u4\"", ")", "vec1", "=", "vec", ".", "view", "(", "dtype", "=", "dtype", ")", "xport1", "=", "vec1", "[", "\"f0\"", "]", "xport2", "=", "vec1", "[", "\"f1\"", "]", "# Start by setting first half of ieee number to first half of IBM", "# number sans exponent", "ieee1", "=", "xport1", "&", "0x00FFFFFF", "# The fraction bit to the left of the binary point in the ieee", "# format was set and the number was shifted 0, 1, 2, or 3", "# places. This will tell us how to adjust the ibm exponent to be a", "# power of 2 ieee exponent and how to shift the fraction bits to", "# restore the correct magnitude.", "shift", "=", "np", ".", "zeros", "(", "len", "(", "vec", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "shift", "[", "np", ".", "where", "(", "xport1", "&", "0x00200000", ")", "]", "=", "1", "shift", "[", "np", ".", "where", "(", "xport1", "&", "0x00400000", ")", "]", "=", "2", "shift", "[", "np", ".", "where", "(", "xport1", "&", "0x00800000", ")", "]", "=", "3", "# shift the ieee number down the correct number of places then", "# set the second half of the ieee number to be the second half", "# of the ibm number shifted appropriately, ored with the bits", "# from the first half that would have been shifted in if we", "# could shift a double. All we are worried about are the low", "# order 3 bits of the first half since we're only shifting by", "# 1, 2, or 3.", "ieee1", ">>=", "shift", "ieee2", "=", "(", "xport2", ">>", "shift", ")", "|", "(", "(", "xport1", "&", "0x00000007", ")", "<<", "(", "29", "+", "(", "3", "-", "shift", ")", ")", ")", "# clear the 1 bit to the left of the binary point", "ieee1", "&=", "0xFFEFFFFF", "# set the exponent of the ieee number to be the actual exponent", "# plus the shift count + 1023. Or this into the first half of the", "# ieee number. The ibm exponent is excess 64 but is adjusted by 65", "# since during conversion to ibm format the exponent is", "# incremented by 1 and the fraction bits left 4 positions to the", "# right of the radix point. (had to add >> 24 because C treats &", "# 0x7f as 0x7f000000 and Python doesn't)", "ieee1", "|=", "(", "(", "(", "(", "(", "(", "xport1", ">>", "24", ")", "&", "0x7F", ")", "-", "65", ")", "<<", "2", ")", "+", "shift", "+", "1023", ")", "<<", "20", ")", "|", "(", "xport1", "&", "0x80000000", ")", "ieee", "=", "np", ".", "empty", "(", "(", "len", "(", "ieee1", ")", ",", ")", ",", "dtype", "=", "\">u4,>u4\"", ")", "ieee", "[", "\"f0\"", "]", "=", "ieee1", "ieee", "[", "\"f1\"", "]", "=", "ieee2", "ieee", "=", "ieee", ".", "view", "(", "dtype", "=", "\">f8\"", ")", "ieee", "=", "ieee", ".", "astype", "(", "\"f8\"", ")", "return", "ieee" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/io/sas/sas_xport.py#L196-L251
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_checkparam.py
python
check_number_range
(arg_value, lower_limit, upper_limit, rel, value_type, arg_name=None, prim_name=None)
return arg_value
Method for checking whether an int value is in some range. Usage: - number = check_number_range(number, 0.0, 1.0, Rel.INC_NEITHER, "number", float) # number in [0.0, 1.0] - number = check_number_range(number, 0, 1, Rel.INC_NEITHER, "number", int) # number in [0, 1]
Method for checking whether an int value is in some range.
[ "Method", "for", "checking", "whether", "an", "int", "value", "is", "in", "some", "range", "." ]
def check_number_range(arg_value, lower_limit, upper_limit, rel, value_type, arg_name=None, prim_name=None): """ Method for checking whether an int value is in some range. Usage: - number = check_number_range(number, 0.0, 1.0, Rel.INC_NEITHER, "number", float) # number in [0.0, 1.0] - number = check_number_range(number, 0, 1, Rel.INC_NEITHER, "number", int) # number in [0, 1] """ rel_fn = Rel.get_fns(rel) prim_name = f'in `{prim_name}`' if prim_name else '' arg_name = f'`{arg_name}`' if arg_name else '' type_mismatch = not isinstance(arg_value, (np.ndarray, np.generic, value_type)) or isinstance(arg_value, bool) if type_mismatch: raise TypeError("{} {} must be `{}`, but got `{}`.".format( arg_name, prim_name, value_type.__name__, type(arg_value).__name__)) if not rel_fn(arg_value, lower_limit, upper_limit): rel_str = Rel.get_strs(rel).format(lower_limit, upper_limit) raise ValueError("{} {} should be in range of {}, but got {} with type `{}`.".format( arg_name, prim_name, rel_str, arg_value, type(arg_value).__name__)) return arg_value
[ "def", "check_number_range", "(", "arg_value", ",", "lower_limit", ",", "upper_limit", ",", "rel", ",", "value_type", ",", "arg_name", "=", "None", ",", "prim_name", "=", "None", ")", ":", "rel_fn", "=", "Rel", ".", "get_fns", "(", "rel", ")", "prim_name", "=", "f'in `{prim_name}`'", "if", "prim_name", "else", "''", "arg_name", "=", "f'`{arg_name}`'", "if", "arg_name", "else", "''", "type_mismatch", "=", "not", "isinstance", "(", "arg_value", ",", "(", "np", ".", "ndarray", ",", "np", ".", "generic", ",", "value_type", ")", ")", "or", "isinstance", "(", "arg_value", ",", "bool", ")", "if", "type_mismatch", ":", "raise", "TypeError", "(", "\"{} {} must be `{}`, but got `{}`.\"", ".", "format", "(", "arg_name", ",", "prim_name", ",", "value_type", ".", "__name__", ",", "type", "(", "arg_value", ")", ".", "__name__", ")", ")", "if", "not", "rel_fn", "(", "arg_value", ",", "lower_limit", ",", "upper_limit", ")", ":", "rel_str", "=", "Rel", ".", "get_strs", "(", "rel", ")", ".", "format", "(", "lower_limit", ",", "upper_limit", ")", "raise", "ValueError", "(", "\"{} {} should be in range of {}, but got {} with type `{}`.\"", ".", "format", "(", "arg_name", ",", "prim_name", ",", "rel_str", ",", "arg_value", ",", "type", "(", "arg_value", ")", ".", "__name__", ")", ")", "return", "arg_value" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_checkparam.py#L192-L211
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/core/numerictypes.py
python
maximum_sctype
(t)
Return the scalar type of highest precision of the same kind as the input. Parameters ---------- t : dtype or dtype specifier The input data type. This can be a `dtype` object or an object that is convertible to a `dtype`. Returns ------- out : dtype The highest precision data type of the same kind (`dtype.kind`) as `t`. See Also -------- obj2sctype, mintypecode, sctype2char dtype Examples -------- >>> np.maximum_sctype(int) <class 'numpy.int64'> >>> np.maximum_sctype(np.uint8) <class 'numpy.uint64'> >>> np.maximum_sctype(complex) <class 'numpy.complex256'> # may vary >>> np.maximum_sctype(str) <class 'numpy.str_'> >>> np.maximum_sctype('i2') <class 'numpy.int64'> >>> np.maximum_sctype('f4') <class 'numpy.float128'> # may vary
Return the scalar type of highest precision of the same kind as the input.
[ "Return", "the", "scalar", "type", "of", "highest", "precision", "of", "the", "same", "kind", "as", "the", "input", "." ]
def maximum_sctype(t): """ Return the scalar type of highest precision of the same kind as the input. Parameters ---------- t : dtype or dtype specifier The input data type. This can be a `dtype` object or an object that is convertible to a `dtype`. Returns ------- out : dtype The highest precision data type of the same kind (`dtype.kind`) as `t`. See Also -------- obj2sctype, mintypecode, sctype2char dtype Examples -------- >>> np.maximum_sctype(int) <class 'numpy.int64'> >>> np.maximum_sctype(np.uint8) <class 'numpy.uint64'> >>> np.maximum_sctype(complex) <class 'numpy.complex256'> # may vary >>> np.maximum_sctype(str) <class 'numpy.str_'> >>> np.maximum_sctype('i2') <class 'numpy.int64'> >>> np.maximum_sctype('f4') <class 'numpy.float128'> # may vary """ g = obj2sctype(t) if g is None: return t t = g base = _kind_name(dtype(t)) if base in sctypes: return sctypes[base][-1] else: return t
[ "def", "maximum_sctype", "(", "t", ")", ":", "g", "=", "obj2sctype", "(", "t", ")", "if", "g", "is", "None", ":", "return", "t", "t", "=", "g", "base", "=", "_kind_name", "(", "dtype", "(", "t", ")", ")", "if", "base", "in", "sctypes", ":", "return", "sctypes", "[", "base", "]", "[", "-", "1", "]", "else", ":", "return", "t" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/core/numerictypes.py#L135-L181
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/design-bitset.py
python
Bitset.__init__
(self, size)
:type size: int
:type size: int
[ ":", "type", "size", ":", "int" ]
def __init__(self, size): """ :type size: int """ self.__lookup = [False]*size self.__flip = False self.__cnt = 0
[ "def", "__init__", "(", "self", ",", "size", ")", ":", "self", ".", "__lookup", "=", "[", "False", "]", "*", "size", "self", ".", "__flip", "=", "False", "self", ".", "__cnt", "=", "0" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/design-bitset.py#L14-L20
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/nn_ops.py
python
_DepthwiseConv2dNativeBackpropInputShape
(op)
Shape function for the DepthwiseConv2dNativeBackpropInput op.
Shape function for the DepthwiseConv2dNativeBackpropInput op.
[ "Shape", "function", "for", "the", "DepthwiseConv2dNativeBackpropInput", "op", "." ]
def _DepthwiseConv2dNativeBackpropInputShape(op): """Shape function for the DepthwiseConv2dNativeBackpropInput op.""" input_shape = tensor_util.constant_value(op.inputs[0]) if input_shape is not None: return [tensor_shape.TensorShape(input_shape.tolist())] else: return [tensor_shape.unknown_shape(ndims=4)]
[ "def", "_DepthwiseConv2dNativeBackpropInputShape", "(", "op", ")", ":", "input_shape", "=", "tensor_util", ".", "constant_value", "(", "op", ".", "inputs", "[", "0", "]", ")", "if", "input_shape", "is", "not", "None", ":", "return", "[", "tensor_shape", ".", "TensorShape", "(", "input_shape", ".", "tolist", "(", ")", ")", "]", "else", ":", "return", "[", "tensor_shape", ".", "unknown_shape", "(", "ndims", "=", "4", ")", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/nn_ops.py#L834-L840
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Utilities/RelMon/python/dqm_interfaces.py
python
DirWalkerFile.ls
(self,directory_name="")
return contents
Return common objects to the 2 files.
Return common objects to the 2 files.
[ "Return", "common", "objects", "to", "the", "2", "files", "." ]
def ls(self,directory_name=""): """Return common objects to the 2 files. """ contents1=self.dqmrootfile1.ls(directory_name) contents2=self.dqmrootfile2.ls(directory_name) #print "cont1: %s"%(contents1) #print "cont2: %s"%(contents2) contents={} self.different_histograms['file1']= {} self.different_histograms['file2']= {} keys = [key for key in contents2.keys() if key in contents1] #set of all possible contents from both files #print " ## keys: %s" %(keys) for key in keys: #iterate on all unique keys if contents1[key]!=contents2[key]: diff_file1 = set(contents1.keys()) - set(contents2.keys()) #set of contents that file1 is missing diff_file2 = set(contents2.keys()) - set(contents1.keys()) #--'-- that file2 is missing for key1 in diff_file1: obj_type = contents1[key1] if obj_type == "TDirectoryFile": self.different_histograms['file1'][key1] = contents1[key1] #if direcory #print "\n Missing inside a dir: ", self.ls(key1) #contents[key] = contents1[key1] if obj_type[:2]!="TH" and obj_type[:3]!="TPr" : #if histogram continue self.different_histograms['file1'][key1] = contents1[key1] for key1 in diff_file2: obj_type = contents2[key1] if obj_type == "TDirectoryFile": self.different_histograms['file2'][key1] = contents2[key1] #if direcory #print "\n Missing inside a dir: ", self.ls(key1) #contents[key] = contents2[key1] if obj_type[:2]!="TH" and obj_type[:3]!="TPr" : #if histogram continue self.different_histograms['file2'][key1] = contents2[key1] contents[key]=contents1[key] return contents
[ "def", "ls", "(", "self", ",", "directory_name", "=", "\"\"", ")", ":", "contents1", "=", "self", ".", "dqmrootfile1", ".", "ls", "(", "directory_name", ")", "contents2", "=", "self", ".", "dqmrootfile2", ".", "ls", "(", "directory_name", ")", "#print \"cont1: %s\"%(contents1)", "#print \"cont2: %s\"%(contents2)", "contents", "=", "{", "}", "self", ".", "different_histograms", "[", "'file1'", "]", "=", "{", "}", "self", ".", "different_histograms", "[", "'file2'", "]", "=", "{", "}", "keys", "=", "[", "key", "for", "key", "in", "contents2", ".", "keys", "(", ")", "if", "key", "in", "contents1", "]", "#set of all possible contents from both files", "#print \" ## keys: %s\" %(keys)", "for", "key", "in", "keys", ":", "#iterate on all unique keys", "if", "contents1", "[", "key", "]", "!=", "contents2", "[", "key", "]", ":", "diff_file1", "=", "set", "(", "contents1", ".", "keys", "(", ")", ")", "-", "set", "(", "contents2", ".", "keys", "(", ")", ")", "#set of contents that file1 is missing", "diff_file2", "=", "set", "(", "contents2", ".", "keys", "(", ")", ")", "-", "set", "(", "contents1", ".", "keys", "(", ")", ")", "#--'-- that file2 is missing", "for", "key1", "in", "diff_file1", ":", "obj_type", "=", "contents1", "[", "key1", "]", "if", "obj_type", "==", "\"TDirectoryFile\"", ":", "self", ".", "different_histograms", "[", "'file1'", "]", "[", "key1", "]", "=", "contents1", "[", "key1", "]", "#if direcory", "#print \"\\n Missing inside a dir: \", self.ls(key1)", "#contents[key] = contents1[key1]", "if", "obj_type", "[", ":", "2", "]", "!=", "\"TH\"", "and", "obj_type", "[", ":", "3", "]", "!=", "\"TPr\"", ":", "#if histogram", "continue", "self", ".", "different_histograms", "[", "'file1'", "]", "[", "key1", "]", "=", "contents1", "[", "key1", "]", "for", "key1", "in", "diff_file2", ":", "obj_type", "=", "contents2", "[", "key1", "]", "if", "obj_type", "==", "\"TDirectoryFile\"", ":", "self", ".", "different_histograms", "[", "'file2'", "]", "[", "key1", "]", "=", "contents2", "[", "key1", "]", "#if direcory", "#print \"\\n Missing inside a dir: \", self.ls(key1)", "#contents[key] = contents2[key1]", "if", "obj_type", "[", ":", "2", "]", "!=", "\"TH\"", "and", "obj_type", "[", ":", "3", "]", "!=", "\"TPr\"", ":", "#if histogram", "continue", "self", ".", "different_histograms", "[", "'file2'", "]", "[", "key1", "]", "=", "contents2", "[", "key1", "]", "contents", "[", "key", "]", "=", "contents1", "[", "key", "]", "return", "contents" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Utilities/RelMon/python/dqm_interfaces.py#L592-L627
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ConvectionDiffusionApplication/python_scripts/convection_diffusion_solver.py
python
ConvectionDiffusionSolver.ImportModelPart
(self)
This function imports the ModelPart
This function imports the ModelPart
[ "This", "function", "imports", "the", "ModelPart" ]
def ImportModelPart(self): """This function imports the ModelPart""" if self.solver_imports_model_part: if not _CheckIsDistributed(): self._ImportModelPart(self.main_model_part, self.settings["model_import_settings"]) else: self.distributed_model_part_importer = distributed_import_model_part_utility.DistributedImportModelPartUtility( self.main_model_part, self.settings) self.distributed_model_part_importer.ImportModelPart()
[ "def", "ImportModelPart", "(", "self", ")", ":", "if", "self", ".", "solver_imports_model_part", ":", "if", "not", "_CheckIsDistributed", "(", ")", ":", "self", ".", "_ImportModelPart", "(", "self", ".", "main_model_part", ",", "self", ".", "settings", "[", "\"model_import_settings\"", "]", ")", "else", ":", "self", ".", "distributed_model_part_importer", "=", "distributed_import_model_part_utility", ".", "DistributedImportModelPartUtility", "(", "self", ".", "main_model_part", ",", "self", ".", "settings", ")", "self", ".", "distributed_model_part_importer", ".", "ImportModelPart", "(", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ConvectionDiffusionApplication/python_scripts/convection_diffusion_solver.py#L298-L307
keyboardio/Kaleidoscope
d59604e98b2439d108647f15be52984a6837d360
bin/cpplint.py
python
_FilterExcludedFiles
(filenames)
return [f for f in filenames if os.path.abspath(f) not in exclude_paths]
Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory
Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory
[ "Filters", "out", "files", "listed", "in", "the", "--", "exclude", "command", "line", "switch", ".", "File", "paths", "in", "the", "switch", "are", "evaluated", "relative", "to", "the", "current", "working", "directory" ]
def _FilterExcludedFiles(filenames): """Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory """ exclude_paths = [os.path.abspath(f) for f in _excludes] return [f for f in filenames if os.path.abspath(f) not in exclude_paths]
[ "def", "_FilterExcludedFiles", "(", "filenames", ")", ":", "exclude_paths", "=", "[", "os", ".", "path", ".", "abspath", "(", "f", ")", "for", "f", "in", "_excludes", "]", "return", "[", "f", "for", "f", "in", "filenames", "if", "os", ".", "path", ".", "abspath", "(", "f", ")", "not", "in", "exclude_paths", "]" ]
https://github.com/keyboardio/Kaleidoscope/blob/d59604e98b2439d108647f15be52984a6837d360/bin/cpplint.py#L6551-L6556
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_adapter.py
python
parallel_pre_compile_op
(job: TbeJob)
return True
Parallel pre compile op :param job: :return:
Parallel pre compile op :param job: :return:
[ "Parallel", "pre", "compile", "op", ":", "param", "job", ":", ":", "return", ":" ]
def parallel_pre_compile_op(job: TbeJob): """ Parallel pre compile op :param job: :return: """ compute_op_info_list = get_compute_op_list(job.content) if len(compute_op_info_list) != 1: job.error("Invalid op compute num ({}) in pre compile op".format(len(compute_op_info_list))) return False compute_op_info = compute_op_info_list[0] adjust_custom_op_info(compute_op_info) _pre_build_compute_op_info(compute_op_info, job) return True
[ "def", "parallel_pre_compile_op", "(", "job", ":", "TbeJob", ")", ":", "compute_op_info_list", "=", "get_compute_op_list", "(", "job", ".", "content", ")", "if", "len", "(", "compute_op_info_list", ")", "!=", "1", ":", "job", ".", "error", "(", "\"Invalid op compute num ({}) in pre compile op\"", ".", "format", "(", "len", "(", "compute_op_info_list", ")", ")", ")", "return", "False", "compute_op_info", "=", "compute_op_info_list", "[", "0", "]", "adjust_custom_op_info", "(", "compute_op_info", ")", "_pre_build_compute_op_info", "(", "compute_op_info", ",", "job", ")", "return", "True" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/_extends/parallel_compile/tbe_compiler/tbe_adapter.py#L368-L381
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config.py
python
IdleUserConfParser.Save
(self)
Update user configuration file. If self not empty after removing empty sections, write the file to disk. Otherwise, remove the file from disk if it exists.
Update user configuration file.
[ "Update", "user", "configuration", "file", "." ]
def Save(self): """Update user configuration file. If self not empty after removing empty sections, write the file to disk. Otherwise, remove the file from disk if it exists. """ fname = self.file if fname and fname[0] != '#': if not self.IsEmpty(): try: cfgFile = open(fname, 'w') except OSError: os.unlink(fname) cfgFile = open(fname, 'w') with cfgFile: self.write(cfgFile) elif os.path.exists(self.file): os.remove(self.file)
[ "def", "Save", "(", "self", ")", ":", "fname", "=", "self", ".", "file", "if", "fname", "and", "fname", "[", "0", "]", "!=", "'#'", ":", "if", "not", "self", ".", "IsEmpty", "(", ")", ":", "try", ":", "cfgFile", "=", "open", "(", "fname", ",", "'w'", ")", "except", "OSError", ":", "os", ".", "unlink", "(", "fname", ")", "cfgFile", "=", "open", "(", "fname", ",", "'w'", ")", "with", "cfgFile", ":", "self", ".", "write", "(", "cfgFile", ")", "elif", "os", ".", "path", ".", "exists", "(", "self", ".", "file", ")", ":", "os", ".", "remove", "(", "self", ".", "file", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/config.py#L126-L143
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/email/mime/base.py
python
MIMEBase.__init__
(self, _maintype, _subtype, **_params)
This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments.
This constructor adds a Content-Type: and a MIME-Version: header.
[ "This", "constructor", "adds", "a", "Content", "-", "Type", ":", "and", "a", "MIME", "-", "Version", ":", "header", "." ]
def __init__(self, _maintype, _subtype, **_params): """This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments. """ message.Message.__init__(self) ctype = '%s/%s' % (_maintype, _subtype) self.add_header('Content-Type', ctype, **_params) self['MIME-Version'] = '1.0'
[ "def", "__init__", "(", "self", ",", "_maintype", ",", "_subtype", ",", "*", "*", "_params", ")", ":", "message", ".", "Message", ".", "__init__", "(", "self", ")", "ctype", "=", "'%s/%s'", "%", "(", "_maintype", ",", "_subtype", ")", "self", ".", "add_header", "(", "'Content-Type'", ",", "ctype", ",", "*", "*", "_params", ")", "self", "[", "'MIME-Version'", "]", "=", "'1.0'" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/email/mime/base.py#L16-L26
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_carbon/gizmos.py
python
EditableListBox.SetStrings
(*args, **kwargs)
return _gizmos.EditableListBox_SetStrings(*args, **kwargs)
SetStrings(self, wxArrayString strings)
SetStrings(self, wxArrayString strings)
[ "SetStrings", "(", "self", "wxArrayString", "strings", ")" ]
def SetStrings(*args, **kwargs): """SetStrings(self, wxArrayString strings)""" return _gizmos.EditableListBox_SetStrings(*args, **kwargs)
[ "def", "SetStrings", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "EditableListBox_SetStrings", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L155-L157
Illumina/strelka
d7377443b62319f7c7bd70c241c4b2df3459e29a
src/python/lib/sharedWorkflow.py
python
_getDepthShared
(self,taskPrefix, dependencies, bamList, outputPath, depthFunc)
return nextStepWait
estimate chrom depth using the specified depthFunc to compute per-sample depth
estimate chrom depth using the specified depthFunc to compute per-sample depth
[ "estimate", "chrom", "depth", "using", "the", "specified", "depthFunc", "to", "compute", "per", "-", "sample", "depth" ]
def _getDepthShared(self,taskPrefix, dependencies, bamList, outputPath, depthFunc) : """ estimate chrom depth using the specified depthFunc to compute per-sample depth """ outputFilename=os.path.basename(outputPath) tmpDir=outputPath+".tmpdir" makeTmpDirCmd = getMkdirCmd() + [tmpDir] dirTask=self.addTask(preJoin(taskPrefix,"makeTmpDir"), makeTmpDirCmd, dependencies=dependencies, isForceLocal=True) tmpFiles = [] scatterTasks = set() for (bamIndex, bamFile) in enumerate(bamList) : indexStr = str(bamIndex).zfill(3) tmpFiles.append(os.path.join(tmpDir,outputFilename+"."+ indexStr +".txt")) scatterTasks |= setzer(depthFunc(self,taskPrefix+"_sample"+indexStr,dirTask,bamFile,tmpFiles[-1])) cmd = [ self.params.mergeChromDepth ] cmd.extend(["--out",outputPath]) for tmpFile in tmpFiles : cmd.extend(["--in",tmpFile]) mergeTask = self.addTask(preJoin(taskPrefix,"mergeChromDepth"),cmd,dependencies=scatterTasks,isForceLocal=True) nextStepWait = set() nextStepWait.add(mergeTask) if not self.params.isRetainTempFiles : rmTmpCmd = getRmdirCmd() + [tmpDir] rmTask=self.addTask(preJoin(taskPrefix,"removeTmpDir"),rmTmpCmd,dependencies=mergeTask, isForceLocal=True) return nextStepWait
[ "def", "_getDepthShared", "(", "self", ",", "taskPrefix", ",", "dependencies", ",", "bamList", ",", "outputPath", ",", "depthFunc", ")", ":", "outputFilename", "=", "os", ".", "path", ".", "basename", "(", "outputPath", ")", "tmpDir", "=", "outputPath", "+", "\".tmpdir\"", "makeTmpDirCmd", "=", "getMkdirCmd", "(", ")", "+", "[", "tmpDir", "]", "dirTask", "=", "self", ".", "addTask", "(", "preJoin", "(", "taskPrefix", ",", "\"makeTmpDir\"", ")", ",", "makeTmpDirCmd", ",", "dependencies", "=", "dependencies", ",", "isForceLocal", "=", "True", ")", "tmpFiles", "=", "[", "]", "scatterTasks", "=", "set", "(", ")", "for", "(", "bamIndex", ",", "bamFile", ")", "in", "enumerate", "(", "bamList", ")", ":", "indexStr", "=", "str", "(", "bamIndex", ")", ".", "zfill", "(", "3", ")", "tmpFiles", ".", "append", "(", "os", ".", "path", ".", "join", "(", "tmpDir", ",", "outputFilename", "+", "\".\"", "+", "indexStr", "+", "\".txt\"", ")", ")", "scatterTasks", "|=", "setzer", "(", "depthFunc", "(", "self", ",", "taskPrefix", "+", "\"_sample\"", "+", "indexStr", ",", "dirTask", ",", "bamFile", ",", "tmpFiles", "[", "-", "1", "]", ")", ")", "cmd", "=", "[", "self", ".", "params", ".", "mergeChromDepth", "]", "cmd", ".", "extend", "(", "[", "\"--out\"", ",", "outputPath", "]", ")", "for", "tmpFile", "in", "tmpFiles", ":", "cmd", ".", "extend", "(", "[", "\"--in\"", ",", "tmpFile", "]", ")", "mergeTask", "=", "self", ".", "addTask", "(", "preJoin", "(", "taskPrefix", ",", "\"mergeChromDepth\"", ")", ",", "cmd", ",", "dependencies", "=", "scatterTasks", ",", "isForceLocal", "=", "True", ")", "nextStepWait", "=", "set", "(", ")", "nextStepWait", ".", "add", "(", "mergeTask", ")", "if", "not", "self", ".", "params", ".", "isRetainTempFiles", ":", "rmTmpCmd", "=", "getRmdirCmd", "(", ")", "+", "[", "tmpDir", "]", "rmTask", "=", "self", ".", "addTask", "(", "preJoin", "(", "taskPrefix", ",", "\"removeTmpDir\"", ")", ",", "rmTmpCmd", ",", "dependencies", "=", "mergeTask", ",", "isForceLocal", "=", "True", ")", "return", "nextStepWait" ]
https://github.com/Illumina/strelka/blob/d7377443b62319f7c7bd70c241c4b2df3459e29a/src/python/lib/sharedWorkflow.py#L96-L129
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge3.py
python
ExodusModel.delete_element_field
(self, element_field_names, element_block_ids='all')
Delete one or more element fields. Examples: >>> model.delete_element_field('eqps') >>> model.delete_element_field('all')
Delete one or more element fields.
[ "Delete", "one", "or", "more", "element", "fields", "." ]
def delete_element_field(self, element_field_names, element_block_ids='all'): """ Delete one or more element fields. Examples: >>> model.delete_element_field('eqps') >>> model.delete_element_field('all') """ element_block_ids = self._format_element_block_id_list( element_block_ids) element_field_names = self._format_id_list( element_field_names, self.get_element_field_names(), 'element field') # for each field for element_field_name in element_field_names: any_deleted = False # for each element block for element_block_id in element_block_ids: fields = self._get_element_block_fields(element_block_id) if element_field_name in fields: any_deleted = True del fields[element_field_name] if not any_deleted: self._warning( 'Element field not defined.', 'The element field "%s" was not defined on any ' 'of the given element blocks. It cannot be ' 'deleted.' % element_field_name)
[ "def", "delete_element_field", "(", "self", ",", "element_field_names", ",", "element_block_ids", "=", "'all'", ")", ":", "element_block_ids", "=", "self", ".", "_format_element_block_id_list", "(", "element_block_ids", ")", "element_field_names", "=", "self", ".", "_format_id_list", "(", "element_field_names", ",", "self", ".", "get_element_field_names", "(", ")", ",", "'element field'", ")", "# for each field", "for", "element_field_name", "in", "element_field_names", ":", "any_deleted", "=", "False", "# for each element block", "for", "element_block_id", "in", "element_block_ids", ":", "fields", "=", "self", ".", "_get_element_block_fields", "(", "element_block_id", ")", "if", "element_field_name", "in", "fields", ":", "any_deleted", "=", "True", "del", "fields", "[", "element_field_name", "]", "if", "not", "any_deleted", ":", "self", ".", "_warning", "(", "'Element field not defined.'", ",", "'The element field \"%s\" was not defined on any '", "'of the given element blocks. It cannot be '", "'deleted.'", "%", "element_field_name", ")" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L4625-L4655
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/mem/slicc/parser.py
python
SLICC.p_statement__if
(self, p)
statement : if_statement
statement : if_statement
[ "statement", ":", "if_statement" ]
def p_statement__if(self, p): "statement : if_statement" p[0] = p[1]
[ "def", "p_statement__if", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L648-L650
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/feature_column/feature_column.py
python
_check_default_value
(shape, default_value, dtype, key)
Returns default value as tuple if it's valid, otherwise raises errors. This function verifies that `default_value` is compatible with both `shape` and `dtype`. If it is not compatible, it raises an error. If it is compatible, it casts default_value to a tuple and returns it. `key` is used only for error message. Args: shape: An iterable of integers specifies the shape of the `Tensor`. default_value: If a single value is provided, the same value will be applied as the default value for every item. If an iterable of values is provided, the shape of the `default_value` should be equal to the given `shape`. dtype: defines the type of values. Default value is `tf.float32`. Must be a non-quantized, real integer or floating point type. key: Column name, used only for error messages. Returns: A tuple which will be used as default value. Raises: TypeError: if `default_value` is an iterable but not compatible with `shape` TypeError: if `default_value` is not compatible with `dtype`. ValueError: if `dtype` is not convertible to `tf.float32`.
Returns default value as tuple if it's valid, otherwise raises errors.
[ "Returns", "default", "value", "as", "tuple", "if", "it", "s", "valid", "otherwise", "raises", "errors", "." ]
def _check_default_value(shape, default_value, dtype, key): """Returns default value as tuple if it's valid, otherwise raises errors. This function verifies that `default_value` is compatible with both `shape` and `dtype`. If it is not compatible, it raises an error. If it is compatible, it casts default_value to a tuple and returns it. `key` is used only for error message. Args: shape: An iterable of integers specifies the shape of the `Tensor`. default_value: If a single value is provided, the same value will be applied as the default value for every item. If an iterable of values is provided, the shape of the `default_value` should be equal to the given `shape`. dtype: defines the type of values. Default value is `tf.float32`. Must be a non-quantized, real integer or floating point type. key: Column name, used only for error messages. Returns: A tuple which will be used as default value. Raises: TypeError: if `default_value` is an iterable but not compatible with `shape` TypeError: if `default_value` is not compatible with `dtype`. ValueError: if `dtype` is not convertible to `tf.float32`. """ if default_value is None: return None if isinstance(default_value, int): return _create_tuple(shape, default_value) if isinstance(default_value, float) and dtype.is_floating: return _create_tuple(shape, default_value) if callable(getattr(default_value, 'tolist', None)): # Handles numpy arrays default_value = default_value.tolist() if nest.is_sequence(default_value): if not _is_shape_and_default_value_compatible(default_value, shape): raise ValueError( 'The shape of default_value must be equal to given shape. ' 'default_value: {}, shape: {}, key: {}'.format( default_value, shape, key)) # Check if the values in the list are all integers or are convertible to # floats. is_list_all_int = all( isinstance(v, int) for v in nest.flatten(default_value)) is_list_has_float = any( isinstance(v, float) for v in nest.flatten(default_value)) if is_list_all_int: return _as_tuple(default_value) if is_list_has_float and dtype.is_floating: return _as_tuple(default_value) raise TypeError('default_value must be compatible with dtype. ' 'default_value: {}, dtype: {}, key: {}'.format( default_value, dtype, key))
[ "def", "_check_default_value", "(", "shape", ",", "default_value", ",", "dtype", ",", "key", ")", ":", "if", "default_value", "is", "None", ":", "return", "None", "if", "isinstance", "(", "default_value", ",", "int", ")", ":", "return", "_create_tuple", "(", "shape", ",", "default_value", ")", "if", "isinstance", "(", "default_value", ",", "float", ")", "and", "dtype", ".", "is_floating", ":", "return", "_create_tuple", "(", "shape", ",", "default_value", ")", "if", "callable", "(", "getattr", "(", "default_value", ",", "'tolist'", ",", "None", ")", ")", ":", "# Handles numpy arrays", "default_value", "=", "default_value", ".", "tolist", "(", ")", "if", "nest", ".", "is_sequence", "(", "default_value", ")", ":", "if", "not", "_is_shape_and_default_value_compatible", "(", "default_value", ",", "shape", ")", ":", "raise", "ValueError", "(", "'The shape of default_value must be equal to given shape. '", "'default_value: {}, shape: {}, key: {}'", ".", "format", "(", "default_value", ",", "shape", ",", "key", ")", ")", "# Check if the values in the list are all integers or are convertible to", "# floats.", "is_list_all_int", "=", "all", "(", "isinstance", "(", "v", ",", "int", ")", "for", "v", "in", "nest", ".", "flatten", "(", "default_value", ")", ")", "is_list_has_float", "=", "any", "(", "isinstance", "(", "v", ",", "float", ")", "for", "v", "in", "nest", ".", "flatten", "(", "default_value", ")", ")", "if", "is_list_all_int", ":", "return", "_as_tuple", "(", "default_value", ")", "if", "is_list_has_float", "and", "dtype", ".", "is_floating", ":", "return", "_as_tuple", "(", "default_value", ")", "raise", "TypeError", "(", "'default_value must be compatible with dtype. '", "'default_value: {}, dtype: {}, key: {}'", ".", "format", "(", "default_value", ",", "dtype", ",", "key", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/feature_column/feature_column.py#L1901-L1957
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py
python
SourceLocation.from_position
(tu, file, line, column)
return conf.lib.clang_getLocation(tu, file, line, column)
Retrieve the source location associated with a given file/line/column in a particular translation unit.
Retrieve the source location associated with a given file/line/column in a particular translation unit.
[ "Retrieve", "the", "source", "location", "associated", "with", "a", "given", "file", "/", "line", "/", "column", "in", "a", "particular", "translation", "unit", "." ]
def from_position(tu, file, line, column): """ Retrieve the source location associated with a given file/line/column in a particular translation unit. """ return conf.lib.clang_getLocation(tu, file, line, column)
[ "def", "from_position", "(", "tu", ",", "file", ",", "line", ",", "column", ")", ":", "return", "conf", ".", "lib", ".", "clang_getLocation", "(", "tu", ",", "file", ",", "line", ",", "column", ")" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/tools/clang/bindings/python/clang/cindex.py#L180-L185
plumonito/dtslam
5994bb9cf7a11981b830370db206bceb654c085d
3rdparty/opencv-git/doc/pattern_tools/svgfig.py
python
funcRtoR
(expr, var="x", globals=None, locals=None)
return output
Converts a "f(x)" string to a function acceptable for Curve. expr required string in the form "f(x)" var default="x" name of the independent variable globals default=None dict of global variables used in the expression; you may want to use Python's builtin globals() locals default=None dict of local variables
Converts a "f(x)" string to a function acceptable for Curve.
[ "Converts", "a", "f", "(", "x", ")", "string", "to", "a", "function", "acceptable", "for", "Curve", "." ]
def funcRtoR(expr, var="x", globals=None, locals=None): """Converts a "f(x)" string to a function acceptable for Curve. expr required string in the form "f(x)" var default="x" name of the independent variable globals default=None dict of global variables used in the expression; you may want to use Python's builtin globals() locals default=None dict of local variables """ if locals is None: locals = {} # python 2.3's eval() won't accept None g = math.__dict__ if globals is not None: g.update(globals) output = eval("lambda %s: (%s, %s)" % (var, var, expr), g, locals) set_func_name(output, "%s -> %s" % (var, expr)) return output
[ "def", "funcRtoR", "(", "expr", ",", "var", "=", "\"x\"", ",", "globals", "=", "None", ",", "locals", "=", "None", ")", ":", "if", "locals", "is", "None", ":", "locals", "=", "{", "}", "# python 2.3's eval() won't accept None", "g", "=", "math", ".", "__dict__", "if", "globals", "is", "not", "None", ":", "g", ".", "update", "(", "globals", ")", "output", "=", "eval", "(", "\"lambda %s: (%s, %s)\"", "%", "(", "var", ",", "var", ",", "expr", ")", ",", "g", ",", "locals", ")", "set_func_name", "(", "output", ",", "\"%s -> %s\"", "%", "(", "var", ",", "expr", ")", ")", "return", "output" ]
https://github.com/plumonito/dtslam/blob/5994bb9cf7a11981b830370db206bceb654c085d/3rdparty/opencv-git/doc/pattern_tools/svgfig.py#L1610-L1626
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
buildsystem/cythonize.py
python
main
()
CLI entry point
CLI entry point
[ "CLI", "entry", "point" ]
def main(): """ CLI entry point """ cli = argparse.ArgumentParser() cli.add_argument("module_list", help=( "Module list file (semicolon-separated)." )) cli.add_argument("embedded_module_list", help=( "Embedded module list file (semicolon-separated).\n" "Modules in this list are compiled with the --embed option." )) cli.add_argument("depends_list", help=( "Dependency list file (semicolon-separated).\n" "Contains all .pxd and other files that may get included.\n" "Used to verify that all dependencies are properly listed " "in the CMake build configuration." )) cli.add_argument("--clean", action="store_true", help=( "Clean compilation results and exit." )) cli.add_argument("--build-dir", help=( "Build output directory to generate the cpp files in." "note: this is also added for module search path." )) cli.add_argument("--memcleanup", type=int, default=0, help=( "Generate memory cleanup code to make valgrind happy:\n" "0: nothing, 1+: interned objects,\n" "2+: cdef globals, 3+: types objects" )) cli.add_argument("--threads", type=int, default=cpu_count(), help="number of compilation threads to use") args = cli.parse_args() # cython emits warnings on using absolute paths to modules # https://github.com/cython/cython/issues/2323 modules = read_list_from_file(args.module_list) embedded_modules = read_list_from_file(args.embedded_module_list) depends = set(read_list_from_file(args.depends_list)) if args.clean: for module in modules + embedded_modules: rel_module = module.relative_to(Path.cwd()) build_module = args.build_dir / rel_module remove_if_exists(build_module.with_suffix('.cpp')) remove_if_exists(build_module.with_suffix('.html')) sys.exit(0) from Cython.Compiler import Options Options.annotate = True Options.fast_fail = True Options.generate_cleanup_code = args.memcleanup Options.cplus = 1 # build cython modules (emits shared libraries) cythonize_args = { 'compiler_directives': {'language_level': 3}, 'build_dir': args.build_dir, 'include_path': [args.build_dir], 'nthreads': args.threads } # this is deprecated, but still better than # writing funny lines at the head of each file. cythonize_args['language'] = 'c++' cythonize_wrapper(modules, **cythonize_args) # build standalone executables that embed the py interpreter Options.embed = "main" cythonize_wrapper(embedded_modules, **cythonize_args) # verify depends from Cython.Build.Dependencies import _dep_tree depend_failed = False # TODO figure out a less hacky way of getting the depends out of Cython # pylint: disable=no-member, protected-access for module, files in _dep_tree.__cimported_files_cache.items(): for filename in files: if not filename.startswith('.'): # system include starts with / continue if os.path.realpath(os.path.abspath(filename)) not in depends: print("\x1b[31mERR\x1b[m unlisted dependency: " + filename) depend_failed = True if depend_failed: sys.exit(1)
[ "def", "main", "(", ")", ":", "cli", "=", "argparse", ".", "ArgumentParser", "(", ")", "cli", ".", "add_argument", "(", "\"module_list\"", ",", "help", "=", "(", "\"Module list file (semicolon-separated).\"", ")", ")", "cli", ".", "add_argument", "(", "\"embedded_module_list\"", ",", "help", "=", "(", "\"Embedded module list file (semicolon-separated).\\n\"", "\"Modules in this list are compiled with the --embed option.\"", ")", ")", "cli", ".", "add_argument", "(", "\"depends_list\"", ",", "help", "=", "(", "\"Dependency list file (semicolon-separated).\\n\"", "\"Contains all .pxd and other files that may get included.\\n\"", "\"Used to verify that all dependencies are properly listed \"", "\"in the CMake build configuration.\"", ")", ")", "cli", ".", "add_argument", "(", "\"--clean\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "(", "\"Clean compilation results and exit.\"", ")", ")", "cli", ".", "add_argument", "(", "\"--build-dir\"", ",", "help", "=", "(", "\"Build output directory to generate the cpp files in.\"", "\"note: this is also added for module search path.\"", ")", ")", "cli", ".", "add_argument", "(", "\"--memcleanup\"", ",", "type", "=", "int", ",", "default", "=", "0", ",", "help", "=", "(", "\"Generate memory cleanup code to make valgrind happy:\\n\"", "\"0: nothing, 1+: interned objects,\\n\"", "\"2+: cdef globals, 3+: types objects\"", ")", ")", "cli", ".", "add_argument", "(", "\"--threads\"", ",", "type", "=", "int", ",", "default", "=", "cpu_count", "(", ")", ",", "help", "=", "\"number of compilation threads to use\"", ")", "args", "=", "cli", ".", "parse_args", "(", ")", "# cython emits warnings on using absolute paths to modules", "# https://github.com/cython/cython/issues/2323", "modules", "=", "read_list_from_file", "(", "args", ".", "module_list", ")", "embedded_modules", "=", "read_list_from_file", "(", "args", ".", "embedded_module_list", ")", "depends", "=", "set", "(", "read_list_from_file", "(", "args", ".", "depends_list", ")", ")", "if", "args", ".", "clean", ":", "for", "module", "in", "modules", "+", "embedded_modules", ":", "rel_module", "=", "module", ".", "relative_to", "(", "Path", ".", "cwd", "(", ")", ")", "build_module", "=", "args", ".", "build_dir", "/", "rel_module", "remove_if_exists", "(", "build_module", ".", "with_suffix", "(", "'.cpp'", ")", ")", "remove_if_exists", "(", "build_module", ".", "with_suffix", "(", "'.html'", ")", ")", "sys", ".", "exit", "(", "0", ")", "from", "Cython", ".", "Compiler", "import", "Options", "Options", ".", "annotate", "=", "True", "Options", ".", "fast_fail", "=", "True", "Options", ".", "generate_cleanup_code", "=", "args", ".", "memcleanup", "Options", ".", "cplus", "=", "1", "# build cython modules (emits shared libraries)", "cythonize_args", "=", "{", "'compiler_directives'", ":", "{", "'language_level'", ":", "3", "}", ",", "'build_dir'", ":", "args", ".", "build_dir", ",", "'include_path'", ":", "[", "args", ".", "build_dir", "]", ",", "'nthreads'", ":", "args", ".", "threads", "}", "# this is deprecated, but still better than", "# writing funny lines at the head of each file.", "cythonize_args", "[", "'language'", "]", "=", "'c++'", "cythonize_wrapper", "(", "modules", ",", "*", "*", "cythonize_args", ")", "# build standalone executables that embed the py interpreter", "Options", ".", "embed", "=", "\"main\"", "cythonize_wrapper", "(", "embedded_modules", ",", "*", "*", "cythonize_args", ")", "# verify depends", "from", "Cython", ".", "Build", ".", "Dependencies", "import", "_dep_tree", "depend_failed", "=", "False", "# TODO figure out a less hacky way of getting the depends out of Cython", "# pylint: disable=no-member, protected-access", "for", "module", ",", "files", "in", "_dep_tree", ".", "__cimported_files_cache", ".", "items", "(", ")", ":", "for", "filename", "in", "files", ":", "if", "not", "filename", ".", "startswith", "(", "'.'", ")", ":", "# system include starts with /", "continue", "if", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "not", "in", "depends", ":", "print", "(", "\"\\x1b[31mERR\\x1b[m unlisted dependency: \"", "+", "filename", ")", "depend_failed", "=", "True", "if", "depend_failed", ":", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/buildsystem/cythonize.py#L98-L186
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py
python
_PendingDeallocs.clear
(self)
Flush any pending deallocations unless it is disabled. Do nothing if disabled.
Flush any pending deallocations unless it is disabled. Do nothing if disabled.
[ "Flush", "any", "pending", "deallocations", "unless", "it", "is", "disabled", ".", "Do", "nothing", "if", "disabled", "." ]
def clear(self): """ Flush any pending deallocations unless it is disabled. Do nothing if disabled. """ if not self.is_disabled: while self._cons: [dtor, handle, size] = self._cons.popleft() _logger.info('dealloc: %s %s bytes', dtor.__name__, size) dtor(handle) self._size = 0
[ "def", "clear", "(", "self", ")", ":", "if", "not", "self", ".", "is_disabled", ":", "while", "self", ".", "_cons", ":", "[", "dtor", ",", "handle", ",", "size", "]", "=", "self", ".", "_cons", ".", "popleft", "(", ")", "_logger", ".", "info", "(", "'dealloc: %s %s bytes'", ",", "dtor", ".", "__name__", ",", "size", ")", "dtor", "(", "handle", ")", "self", ".", "_size", "=", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/cudadrv/driver.py#L601-L611
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextBuffer.DeleteRangeWithUndo
(*args, **kwargs)
return _richtext.RichTextBuffer_DeleteRangeWithUndo(*args, **kwargs)
DeleteRangeWithUndo(self, RichTextRange range, RichTextCtrl ctrl) -> bool
DeleteRangeWithUndo(self, RichTextRange range, RichTextCtrl ctrl) -> bool
[ "DeleteRangeWithUndo", "(", "self", "RichTextRange", "range", "RichTextCtrl", "ctrl", ")", "-", ">", "bool" ]
def DeleteRangeWithUndo(*args, **kwargs): """DeleteRangeWithUndo(self, RichTextRange range, RichTextCtrl ctrl) -> bool""" return _richtext.RichTextBuffer_DeleteRangeWithUndo(*args, **kwargs)
[ "def", "DeleteRangeWithUndo", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_DeleteRangeWithUndo", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2525-L2527
0vercl0k/rp
5fe693c26d76b514efaedb4084f6e37d820db023
src/third_party/fmt/support/docopt.py
python
parse_expr
(tokens, options)
return [Either(*result)] if len(result) > 1 else result
expr ::= seq ( '|' seq )* ;
expr ::= seq ( '|' seq )* ;
[ "expr", "::", "=", "seq", "(", "|", "seq", ")", "*", ";" ]
def parse_expr(tokens, options): """expr ::= seq ( '|' seq )* ;""" seq = parse_seq(tokens, options) if tokens.current() != '|': return seq result = [Required(*seq)] if len(seq) > 1 else seq while tokens.current() == '|': tokens.move() seq = parse_seq(tokens, options) result += [Required(*seq)] if len(seq) > 1 else seq return [Either(*result)] if len(result) > 1 else result
[ "def", "parse_expr", "(", "tokens", ",", "options", ")", ":", "seq", "=", "parse_seq", "(", "tokens", ",", "options", ")", "if", "tokens", ".", "current", "(", ")", "!=", "'|'", ":", "return", "seq", "result", "=", "[", "Required", "(", "*", "seq", ")", "]", "if", "len", "(", "seq", ")", ">", "1", "else", "seq", "while", "tokens", ".", "current", "(", ")", "==", "'|'", ":", "tokens", ".", "move", "(", ")", "seq", "=", "parse_seq", "(", "tokens", ",", "options", ")", "result", "+=", "[", "Required", "(", "*", "seq", ")", "]", "if", "len", "(", "seq", ")", ">", "1", "else", "seq", "return", "[", "Either", "(", "*", "result", ")", "]", "if", "len", "(", "result", ")", ">", "1", "else", "result" ]
https://github.com/0vercl0k/rp/blob/5fe693c26d76b514efaedb4084f6e37d820db023/src/third_party/fmt/support/docopt.py#L377-L387
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/__init__.py
python
Launcher.__LaunchProcess
(self, arg_parse_result)
after the arguments have been parsed, launch the UI in a forked process
after the arguments have been parsed, launch the UI in a forked process
[ "after", "the", "arguments", "have", "been", "parsed", "launch", "the", "UI", "in", "a", "forked", "process" ]
def __LaunchProcess(self, arg_parse_result): ''' after the arguments have been parsed, launch the UI in a forked process ''' # Initialize concurrency limit as early as possible so that it is # respected by subsequent imports. (app, appController) = self.LaunchPreamble(arg_parse_result) if arg_parse_result.quitAfterStartup: # Enqueue event to shutdown application. We don't use quit() because # it doesn't trigger the closeEvent() on the main window which is # used to orchestrate the shutdown. QtCore.QTimer.singleShot(0, app.instance().closeAllWindows) app.exec_()
[ "def", "__LaunchProcess", "(", "self", ",", "arg_parse_result", ")", ":", "# Initialize concurrency limit as early as possible so that it is", "# respected by subsequent imports.", "(", "app", ",", "appController", ")", "=", "self", ".", "LaunchPreamble", "(", "arg_parse_result", ")", "if", "arg_parse_result", ".", "quitAfterStartup", ":", "# Enqueue event to shutdown application. We don't use quit() because", "# it doesn't trigger the closeEvent() on the main window which is", "# used to orchestrate the shutdown.", "QtCore", ".", "QTimer", ".", "singleShot", "(", "0", ",", "app", ".", "instance", "(", ")", ".", "closeAllWindows", ")", "app", ".", "exec_", "(", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/__init__.py#L338-L352
timi-liuliang/echo
40a5a24d430eee4118314459ab7e03afcb3b8719
thirdparty/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__getslice__
(self, start, stop)
return self._values[start:stop]
Retrieves the subset of items from between the specified indices.
Retrieves the subset of items from between the specified indices.
[ "Retrieves", "the", "subset", "of", "items", "from", "between", "the", "specified", "indices", "." ]
def __getslice__(self, start, stop): """Retrieves the subset of items from between the specified indices.""" return self._values[start:stop]
[ "def", "__getslice__", "(", "self", ",", "start", ",", "stop", ")", ":", "return", "self", ".", "_values", "[", "start", ":", "stop", "]" ]
https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/google/protobuf/internal/containers.py#L154-L156
tpfister/caffe-heatmap
4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e
python/caffe/detector.py
python
Detector.detect_windows
(self, images_windows)
return detections
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts.
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net.
[ "Do", "windowed", "detection", "over", "given", "images", "and", "windows", ".", "Windows", "are", "extracted", "then", "warped", "to", "the", "input", "dimensions", "of", "the", "net", "." ]
def detect_windows(self, images_windows): """ Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ # Extract windows. window_inputs = [] for image_fname, windows in images_windows: image = caffe.io.load_image(image_fname).astype(np.float32) for window in windows: window_inputs.append(self.crop(image, window)) # Run through the net (warping windows to input dimensions). in_ = self.inputs[0] caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2]) + self.blobs[in_].data.shape[2:], dtype=np.float32) for ix, window_in in enumerate(window_inputs): caffe_in[ix] = self.transformer.preprocess(in_, window_in) out = self.forward_all(**{in_: caffe_in}) predictions = out[self.outputs[0]].squeeze(axis=(2, 3)) # Package predictions with images and windows. detections = [] ix = 0 for image_fname, windows in images_windows: for window in windows: detections.append({ 'window': window, 'prediction': predictions[ix], 'filename': image_fname }) ix += 1 return detections
[ "def", "detect_windows", "(", "self", ",", "images_windows", ")", ":", "# Extract windows.", "window_inputs", "=", "[", "]", "for", "image_fname", ",", "windows", "in", "images_windows", ":", "image", "=", "caffe", ".", "io", ".", "load_image", "(", "image_fname", ")", ".", "astype", "(", "np", ".", "float32", ")", "for", "window", "in", "windows", ":", "window_inputs", ".", "append", "(", "self", ".", "crop", "(", "image", ",", "window", ")", ")", "# Run through the net (warping windows to input dimensions).", "in_", "=", "self", ".", "inputs", "[", "0", "]", "caffe_in", "=", "np", ".", "zeros", "(", "(", "len", "(", "window_inputs", ")", ",", "window_inputs", "[", "0", "]", ".", "shape", "[", "2", "]", ")", "+", "self", ".", "blobs", "[", "in_", "]", ".", "data", ".", "shape", "[", "2", ":", "]", ",", "dtype", "=", "np", ".", "float32", ")", "for", "ix", ",", "window_in", "in", "enumerate", "(", "window_inputs", ")", ":", "caffe_in", "[", "ix", "]", "=", "self", ".", "transformer", ".", "preprocess", "(", "in_", ",", "window_in", ")", "out", "=", "self", ".", "forward_all", "(", "*", "*", "{", "in_", ":", "caffe_in", "}", ")", "predictions", "=", "out", "[", "self", ".", "outputs", "[", "0", "]", "]", ".", "squeeze", "(", "axis", "=", "(", "2", ",", "3", ")", ")", "# Package predictions with images and windows.", "detections", "=", "[", "]", "ix", "=", "0", "for", "image_fname", ",", "windows", "in", "images_windows", ":", "for", "window", "in", "windows", ":", "detections", ".", "append", "(", "{", "'window'", ":", "window", ",", "'prediction'", ":", "predictions", "[", "ix", "]", ",", "'filename'", ":", "image_fname", "}", ")", "ix", "+=", "1", "return", "detections" ]
https://github.com/tpfister/caffe-heatmap/blob/4db69ef53e6b8a0b3b4ebb29328b0ab3dbf67c4e/python/caffe/detector.py#L56-L99
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
ternary_search_tries/ternary_search_tries.py
python
TernarySearchTries.put
(self, key, value)
inserts new key-value pair into the ternary search tries
inserts new key-value pair into the ternary search tries
[ "inserts", "new", "key", "-", "value", "pair", "into", "the", "ternary", "search", "tries" ]
def put(self, key, value): """ inserts new key-value pair into the ternary search tries """ def _put(node, key, value, depth): """ recursive internal method which works on node level """ char = key[depth] if node is None: node = Node(char) if char < node.character: node.left = _put(node.left, key, value, depth) elif char > node.character: node.right = _put(node.right, key, value, depth) elif depth < len(key) - 1: node.middle = _put(node.middle, key, value, depth + 1) else: node.value = value return node self.root = _put(self.root, key, value, 0)
[ "def", "put", "(", "self", ",", "key", ",", "value", ")", ":", "def", "_put", "(", "node", ",", "key", ",", "value", ",", "depth", ")", ":", "\"\"\" recursive internal method which works on node level \"\"\"", "char", "=", "key", "[", "depth", "]", "if", "node", "is", "None", ":", "node", "=", "Node", "(", "char", ")", "if", "char", "<", "node", ".", "character", ":", "node", ".", "left", "=", "_put", "(", "node", ".", "left", ",", "key", ",", "value", ",", "depth", ")", "elif", "char", ">", "node", ".", "character", ":", "node", ".", "right", "=", "_put", "(", "node", ".", "right", ",", "key", ",", "value", ",", "depth", ")", "elif", "depth", "<", "len", "(", "key", ")", "-", "1", ":", "node", ".", "middle", "=", "_put", "(", "node", ".", "middle", ",", "key", ",", "value", ",", "depth", "+", "1", ")", "else", ":", "node", ".", "value", "=", "value", "return", "node", "self", ".", "root", "=", "_put", "(", "self", ".", "root", ",", "key", ",", "value", ",", "0", ")" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/ternary_search_tries/ternary_search_tries.py#L32-L50
schwehr/libais
1e19605942c8e155cd02fde6d1acde75ecd15d75
ais/tag_block.py
python
DecodeTagMultiple
(tag_block_message)
return msg['decoded']
Decode a TAG block message that spans multiple lines.
Decode a TAG block message that spans multiple lines.
[ "Decode", "a", "TAG", "block", "message", "that", "spans", "multiple", "lines", "." ]
def DecodeTagMultiple(tag_block_message): """Decode a TAG block message that spans multiple lines.""" payloads = [msg['payload'] for msg in tag_block_message['matches']] q = vdm.BareQueue() for line in vdm.VdmLines(payloads): q.put(line) if q.qsize() != 1: logger.info('Error: Should get just one message decoded from this: %s', tag_block_message) return msg = q.get() return msg['decoded']
[ "def", "DecodeTagMultiple", "(", "tag_block_message", ")", ":", "payloads", "=", "[", "msg", "[", "'payload'", "]", "for", "msg", "in", "tag_block_message", "[", "'matches'", "]", "]", "q", "=", "vdm", ".", "BareQueue", "(", ")", "for", "line", "in", "vdm", ".", "VdmLines", "(", "payloads", ")", ":", "q", ".", "put", "(", "line", ")", "if", "q", ".", "qsize", "(", ")", "!=", "1", ":", "logger", ".", "info", "(", "'Error: Should get just one message decoded from this: %s'", ",", "tag_block_message", ")", "return", "msg", "=", "q", ".", "get", "(", ")", "return", "msg", "[", "'decoded'", "]" ]
https://github.com/schwehr/libais/blob/1e19605942c8e155cd02fde6d1acde75ecd15d75/ais/tag_block.py#L213-L225
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.ShowLines
(*args, **kwargs)
return _stc.StyledTextCtrl_ShowLines(*args, **kwargs)
ShowLines(self, int lineStart, int lineEnd) Make a range of lines visible.
ShowLines(self, int lineStart, int lineEnd)
[ "ShowLines", "(", "self", "int", "lineStart", "int", "lineEnd", ")" ]
def ShowLines(*args, **kwargs): """ ShowLines(self, int lineStart, int lineEnd) Make a range of lines visible. """ return _stc.StyledTextCtrl_ShowLines(*args, **kwargs)
[ "def", "ShowLines", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_ShowLines", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3930-L3936
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py
python
FixPEP8.fix_w291
(self, result)
Remove trailing whitespace.
Remove trailing whitespace.
[ "Remove", "trailing", "whitespace", "." ]
def fix_w291(self, result): """Remove trailing whitespace.""" fixed_line = self.source[result['line'] - 1].rstrip() self.source[result['line'] - 1] = fixed_line + '\n'
[ "def", "fix_w291", "(", "self", ",", "result", ")", ":", "fixed_line", "=", "self", ".", "source", "[", "result", "[", "'line'", "]", "-", "1", "]", ".", "rstrip", "(", ")", "self", ".", "source", "[", "result", "[", "'line'", "]", "-", "1", "]", "=", "fixed_line", "+", "'\\n'" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/autopep8.py#L975-L978
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.WriteMacBundleResources
(self, resources, bundle_depends)
Writes ninja edges for 'mac_bundle_resources'.
Writes ninja edges for 'mac_bundle_resources'.
[ "Writes", "ninja", "edges", "for", "mac_bundle_resources", "." ]
def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" for output, res in gyp.xcode_emulation.GetMacBundleResources( self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.xcode_settings, map(self.GypPathToNinja, resources)): self.ninja.build(output, 'mac_tool', res, variables=[('mactool_cmd', 'copy-bundle-resource')]) bundle_depends.append(output)
[ "def", "WriteMacBundleResources", "(", "self", ",", "resources", ",", "bundle_depends", ")", ":", "for", "output", ",", "res", "in", "gyp", ".", "xcode_emulation", ".", "GetMacBundleResources", "(", "self", ".", "ExpandSpecial", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", ",", "self", ".", "xcode_settings", ",", "map", "(", "self", ".", "GypPathToNinja", ",", "resources", ")", ")", ":", "self", ".", "ninja", ".", "build", "(", "output", ",", "'mac_tool'", ",", "res", ",", "variables", "=", "[", "(", "'mactool_cmd'", ",", "'copy-bundle-resource'", ")", "]", ")", "bundle_depends", ".", "append", "(", "output", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py#L680-L687
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/tf_asymmetry_fitting_context.py
python
TFAsymmetryFittingContext.remove_workspace_by_name
(self, workspace_name: str)
Remove a Fit from the history when an ADS delete event happens on one of its output workspaces.
Remove a Fit from the history when an ADS delete event happens on one of its output workspaces.
[ "Remove", "a", "Fit", "from", "the", "history", "when", "an", "ADS", "delete", "event", "happens", "on", "one", "of", "its", "output", "workspaces", "." ]
def remove_workspace_by_name(self, workspace_name: str) -> None: """Remove a Fit from the history when an ADS delete event happens on one of its output workspaces.""" self.remove_fit_by_name(self._fit_history[TF_SINGLE_FITS_KEY], workspace_name) self.remove_fit_by_name(self._fit_history[TF_SIMULTANEOUS_FITS_KEY], workspace_name) super().remove_workspace_by_name(workspace_name)
[ "def", "remove_workspace_by_name", "(", "self", ",", "workspace_name", ":", "str", ")", "->", "None", ":", "self", ".", "remove_fit_by_name", "(", "self", ".", "_fit_history", "[", "TF_SINGLE_FITS_KEY", "]", ",", "workspace_name", ")", "self", ".", "remove_fit_by_name", "(", "self", ".", "_fit_history", "[", "TF_SIMULTANEOUS_FITS_KEY", "]", ",", "workspace_name", ")", "super", "(", ")", ".", "remove_workspace_by_name", "(", "workspace_name", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/tf_asymmetry_fitting_context.py#L70-L74
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/notebook/callback.py
python
LiveBokehChart.interval_elapsed
(self)
return time.time() - self.last_update > self.display_freq
Check whether it is time to update plot. Returns ------- Boolean value of whethe to update now
Check whether it is time to update plot. Returns ------- Boolean value of whethe to update now
[ "Check", "whether", "it", "is", "time", "to", "update", "plot", ".", "Returns", "-------", "Boolean", "value", "of", "whethe", "to", "update", "now" ]
def interval_elapsed(self): """Check whether it is time to update plot. Returns ------- Boolean value of whethe to update now """ return time.time() - self.last_update > self.display_freq
[ "def", "interval_elapsed", "(", "self", ")", ":", "return", "time", ".", "time", "(", ")", "-", "self", ".", "last_update", ">", "self", ".", "display_freq" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/notebook/callback.py#L235-L241
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/extras/review.py
python
ReviewContext.load_review_set
(self)
return ConfigSet.ConfigSet()
Load and return the review set from the cache if it exists. Otherwise, return an empty set.
Load and return the review set from the cache if it exists. Otherwise, return an empty set.
[ "Load", "and", "return", "the", "review", "set", "from", "the", "cache", "if", "it", "exists", ".", "Otherwise", "return", "an", "empty", "set", "." ]
def load_review_set(self): """ Load and return the review set from the cache if it exists. Otherwise, return an empty set. """ if os.path.isfile(self.review_path): return ConfigSet.ConfigSet(self.review_path) return ConfigSet.ConfigSet()
[ "def", "load_review_set", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "review_path", ")", ":", "return", "ConfigSet", ".", "ConfigSet", "(", "self", ".", "review_path", ")", "return", "ConfigSet", ".", "ConfigSet", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/review.py#L189-L196
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/intelhex/__init__.py
python
IntelHex.__delitem__
(self, addr)
Delete byte at address.
Delete byte at address.
[ "Delete", "byte", "at", "address", "." ]
def __delitem__(self, addr): """Delete byte at address.""" t = type(addr) if t in IntTypes: if addr < 0: raise TypeError('Address should be >= 0.') del self._buf[addr] elif t == slice: addresses = dict_keys(self._buf) if addresses: addresses.sort() start = addr.start or addresses[0] stop = addr.stop or (addresses[-1]+1) step = addr.step or 1 for i in range_g(start, stop, step): x = self._buf.get(i) if x is not None: del self._buf[i] else: raise TypeError('Address has unsupported type: %s' % t)
[ "def", "__delitem__", "(", "self", ",", "addr", ")", ":", "t", "=", "type", "(", "addr", ")", "if", "t", "in", "IntTypes", ":", "if", "addr", "<", "0", ":", "raise", "TypeError", "(", "'Address should be >= 0.'", ")", "del", "self", ".", "_buf", "[", "addr", "]", "elif", "t", "==", "slice", ":", "addresses", "=", "dict_keys", "(", "self", ".", "_buf", ")", "if", "addresses", ":", "addresses", ".", "sort", "(", ")", "start", "=", "addr", ".", "start", "or", "addresses", "[", "0", "]", "stop", "=", "addr", ".", "stop", "or", "(", "addresses", "[", "-", "1", "]", "+", "1", ")", "step", "=", "addr", ".", "step", "or", "1", "for", "i", "in", "range_g", "(", "start", ",", "stop", ",", "step", ")", ":", "x", "=", "self", ".", "_buf", ".", "get", "(", "i", ")", "if", "x", "is", "not", "None", ":", "del", "self", ".", "_buf", "[", "i", "]", "else", ":", "raise", "TypeError", "(", "'Address has unsupported type: %s'", "%", "t", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/intelhex/__init__.py#L510-L529
versatica/mediasoup
36155116316782ba747caa93f41fefb4ed1c33c8
worker/scripts/clang-tidy.py
python
get_tidy_invocation
(f, clang_tidy_binary, checks, tmpdir, build_path, header_filter, extra_arg, extra_arg_before, quiet, config)
return start
Gets a command line for clang-tidy.
Gets a command line for clang-tidy.
[ "Gets", "a", "command", "line", "for", "clang", "-", "tidy", "." ]
def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path, header_filter, extra_arg, extra_arg_before, quiet, config): """Gets a command line for clang-tidy.""" start = [clang_tidy_binary] if header_filter is not None: start.append('-header-filter=' + header_filter) else: # Show warnings in all in-project headers by default. start.append('-header-filter=^' + build_path + '/.*') if checks: start.append('-checks=' + checks) if tmpdir is not None: start.append('-export-fixes') # Get a temporary file. We immediately close the handle so clang-tidy can # overwrite it. (handle, name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir) os.close(handle) start.append(name) for arg in extra_arg: start.append('-extra-arg=%s' % arg) for arg in extra_arg_before: start.append('-extra-arg-before=%s' % arg) start.append('-p=' + build_path) if quiet: start.append('-quiet') if config: start.append('-config=' + config) start.append(f) return start
[ "def", "get_tidy_invocation", "(", "f", ",", "clang_tidy_binary", ",", "checks", ",", "tmpdir", ",", "build_path", ",", "header_filter", ",", "extra_arg", ",", "extra_arg_before", ",", "quiet", ",", "config", ")", ":", "start", "=", "[", "clang_tidy_binary", "]", "if", "header_filter", "is", "not", "None", ":", "start", ".", "append", "(", "'-header-filter='", "+", "header_filter", ")", "else", ":", "# Show warnings in all in-project headers by default.", "start", ".", "append", "(", "'-header-filter=^'", "+", "build_path", "+", "'/.*'", ")", "if", "checks", ":", "start", ".", "append", "(", "'-checks='", "+", "checks", ")", "if", "tmpdir", "is", "not", "None", ":", "start", ".", "append", "(", "'-export-fixes'", ")", "# Get a temporary file. We immediately close the handle so clang-tidy can", "# overwrite it.", "(", "handle", ",", "name", ")", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.yaml'", ",", "dir", "=", "tmpdir", ")", "os", ".", "close", "(", "handle", ")", "start", ".", "append", "(", "name", ")", "for", "arg", "in", "extra_arg", ":", "start", ".", "append", "(", "'-extra-arg=%s'", "%", "arg", ")", "for", "arg", "in", "extra_arg_before", ":", "start", ".", "append", "(", "'-extra-arg-before=%s'", "%", "arg", ")", "start", ".", "append", "(", "'-p='", "+", "build_path", ")", "if", "quiet", ":", "start", ".", "append", "(", "'-quiet'", ")", "if", "config", ":", "start", ".", "append", "(", "'-config='", "+", "config", ")", "start", ".", "append", "(", "f", ")", "return", "start" ]
https://github.com/versatica/mediasoup/blob/36155116316782ba747caa93f41fefb4ed1c33c8/worker/scripts/clang-tidy.py#L76-L105
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py
python
StringToMakefileVariable
(string)
return re.sub('[^a-zA-Z0-9_]', '_', string)
Convert a string to a value that is acceptable as a make variable name.
Convert a string to a value that is acceptable as a make variable name.
[ "Convert", "a", "string", "to", "a", "value", "that", "is", "acceptable", "as", "a", "make", "variable", "name", "." ]
def StringToMakefileVariable(string): """Convert a string to a value that is acceptable as a make variable name.""" return re.sub('[^a-zA-Z0-9_]', '_', string)
[ "def", "StringToMakefileVariable", "(", "string", ")", ":", "return", "re", ".", "sub", "(", "'[^a-zA-Z0-9_]'", ",", "'_'", ",", "string", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L634-L636
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
TreeCtrl.SetQuickBestSize
(*args, **kwargs)
return _controls_.TreeCtrl_SetQuickBestSize(*args, **kwargs)
SetQuickBestSize(self, bool q)
SetQuickBestSize(self, bool q)
[ "SetQuickBestSize", "(", "self", "bool", "q", ")" ]
def SetQuickBestSize(*args, **kwargs): """SetQuickBestSize(self, bool q)""" return _controls_.TreeCtrl_SetQuickBestSize(*args, **kwargs)
[ "def", "SetQuickBestSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_SetQuickBestSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5572-L5574