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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/functools.py
python
lru_cache
(maxsize=128, typed=False)
return decorating_function
Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results. Arguments to the cached function must be hashable. View the cache statistics named tuple (hits, misses, maxsize, currsize) with f.cache_info(). Clear the cache and statistics with f.cache_clear(). Access the underlying function with f.__wrapped__. See: http://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
Least-recently-used cache decorator.
[ "Least", "-", "recently", "-", "used", "cache", "decorator", "." ]
def lru_cache(maxsize=128, typed=False): """Least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results. Arguments to the cached function must be hashable. View the cache statistics named tuple (hits, misses, maxsize, currsize) with f.cache_info(). Clear the cache and statistics with f.cache_clear(). Access the underlying function with f.__wrapped__. See: http://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU) """ # Users should only access the lru_cache through its public API: # cache_info, cache_clear, and f.__wrapped__ # The internals of the lru_cache are encapsulated for thread safety and # to allow the implementation to change (including a possible C version). # Early detection of an erroneous call to @lru_cache without any arguments # resulting in the inner function being passed to maxsize instead of an # integer or None. Negative maxsize is treated as 0. if isinstance(maxsize, int): if maxsize < 0: maxsize = 0 elif maxsize is not None: raise TypeError('Expected maxsize to be an integer or None') def decorating_function(user_function): wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo) return update_wrapper(wrapper, user_function) return decorating_function
[ "def", "lru_cache", "(", "maxsize", "=", "128", ",", "typed", "=", "False", ")", ":", "# Users should only access the lru_cache through its public API:", "# cache_info, cache_clear, and f.__wrapped__", "# The internals of the lru_cache are encapsulated for thread safety and", "# to allow the implementation to change (including a possible C version).", "# Early detection of an erroneous call to @lru_cache without any arguments", "# resulting in the inner function being passed to maxsize instead of an", "# integer or None. Negative maxsize is treated as 0.", "if", "isinstance", "(", "maxsize", ",", "int", ")", ":", "if", "maxsize", "<", "0", ":", "maxsize", "=", "0", "elif", "maxsize", "is", "not", "None", ":", "raise", "TypeError", "(", "'Expected maxsize to be an integer or None'", ")", "def", "decorating_function", "(", "user_function", ")", ":", "wrapper", "=", "_lru_cache_wrapper", "(", "user_function", ",", "maxsize", ",", "typed", ",", "_CacheInfo", ")", "return", "update_wrapper", "(", "wrapper", ",", "user_function", ")", "return", "decorating_function" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/functools.py#L458-L496
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/datetime.py
python
_ymd2ord
(year, month, day)
return (_days_before_year(year) + _days_before_month(year, month) + day)
year, month, day -> ordinal, considering 01-Jan-0001 as day 1.
year, month, day -> ordinal, considering 01-Jan-0001 as day 1.
[ "year", "month", "day", "-", ">", "ordinal", "considering", "01", "-", "Jan", "-", "0001", "as", "day", "1", "." ]
def _ymd2ord(year, month, day): "year, month, day -> ordinal, considering 01-Jan-0001 as day 1." assert 1 <= month <= 12, 'month must be in 1..12' dim = _days_in_month(year, month) assert 1 <= day <= dim, ('day must be in 1..%d' % dim) return (_days_before_year(year) + _days_before_month(year, month) + day)
[ "def", "_ymd2ord", "(", "year", ",", "month", ",", "day", ")", ":", "assert", "1", "<=", "month", "<=", "12", ",", "'month must be in 1..12'", "dim", "=", "_days_in_month", "(", "year", ",", "month", ")", "assert", "1", "<=", "day", "<=", "dim", ",", "(", "'day must be in 1..%d'", "%", "dim", ")", "return", "(", "_days_before_year", "(", "year", ")", "+", "_days_before_month", "(", "year", ",", "month", ")", "+", "day", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/datetime.py#L62-L69
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/image_ops.py
python
rgb_to_grayscale
(images, name=None)
Converts one or more images from RGB to Grayscale. Outputs a tensor of the same `DType` and rank as `images`. The size of the last dimension of the output is 1, containing the Grayscale value of the pixels. Args: images: The RGB tensor to convert. Last dimension must have size 3 and should contain RGB values. name: A name for the operation (optional). Returns: The converted grayscale image(s).
Converts one or more images from RGB to Grayscale.
[ "Converts", "one", "or", "more", "images", "from", "RGB", "to", "Grayscale", "." ]
def rgb_to_grayscale(images, name=None): """Converts one or more images from RGB to Grayscale. Outputs a tensor of the same `DType` and rank as `images`. The size of the last dimension of the output is 1, containing the Grayscale value of the pixels. Args: images: The RGB tensor to convert. Last dimension must have size 3 and should contain RGB values. name: A name for the operation (optional). Returns: The converted grayscale image(s). """ with ops.op_scope([images], name, 'rgb_to_grayscale') as name: images = ops.convert_to_tensor(images, name='images') # Remember original dtype to so we can convert back if needed orig_dtype = images.dtype flt_image = convert_image_dtype(images, dtypes.float32) # Reference for converting between RGB and grayscale. # https://en.wikipedia.org/wiki/Luma_%28video%29 rgb_weights = [0.2989, 0.5870, 0.1140] rank_1 = array_ops.expand_dims(array_ops.rank(images) - 1, 0) gray_float = math_ops.reduce_sum(flt_image * rgb_weights, rank_1, keep_dims=True) gray_float.set_shape(images.get_shape()[:-1].concatenate([1])) return convert_image_dtype(gray_float, orig_dtype, name=name)
[ "def", "rgb_to_grayscale", "(", "images", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "images", "]", ",", "name", ",", "'rgb_to_grayscale'", ")", "as", "name", ":", "images", "=", "ops", ".", "convert_to_tensor", "(", "images", ",", "name", "=", "'images'", ")", "# Remember original dtype to so we can convert back if needed", "orig_dtype", "=", "images", ".", "dtype", "flt_image", "=", "convert_image_dtype", "(", "images", ",", "dtypes", ".", "float32", ")", "# Reference for converting between RGB and grayscale.", "# https://en.wikipedia.org/wiki/Luma_%28video%29", "rgb_weights", "=", "[", "0.2989", ",", "0.5870", ",", "0.1140", "]", "rank_1", "=", "array_ops", ".", "expand_dims", "(", "array_ops", ".", "rank", "(", "images", ")", "-", "1", ",", "0", ")", "gray_float", "=", "math_ops", ".", "reduce_sum", "(", "flt_image", "*", "rgb_weights", ",", "rank_1", ",", "keep_dims", "=", "True", ")", "gray_float", ".", "set_shape", "(", "images", ".", "get_shape", "(", ")", "[", ":", "-", "1", "]", ".", "concatenate", "(", "[", "1", "]", ")", ")", "return", "convert_image_dtype", "(", "gray_float", ",", "orig_dtype", ",", "name", "=", "name", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/image_ops.py#L1126-L1155
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/python_message.py
python
_Listener.__init__
(self, parent_message)
Args: parent_message: The message whose _Modified() method we should call when we receive Modified() messages.
Args: parent_message: The message whose _Modified() method we should call when we receive Modified() messages.
[ "Args", ":", "parent_message", ":", "The", "message", "whose", "_Modified", "()", "method", "we", "should", "call", "when", "we", "receive", "Modified", "()", "messages", "." ]
def __init__(self, parent_message): """Args: parent_message: The message whose _Modified() method we should call when we receive Modified() messages. """ # This listener establishes a back reference from a child (contained) object # to its parent (containing) object. We make this a weak reference to avoid # creating cyclic garbage when the client finishes with the 'parent' object # in the tree. if isinstance(parent_message, weakref.ProxyType): self._parent_message_weakref = parent_message else: self._parent_message_weakref = weakref.proxy(parent_message) # As an optimization, we also indicate directly on the listener whether # or not the parent message is dirty. This way we can avoid traversing # up the tree in the common case. self.dirty = False
[ "def", "__init__", "(", "self", ",", "parent_message", ")", ":", "# This listener establishes a back reference from a child (contained) object", "# to its parent (containing) object. We make this a weak reference to avoid", "# creating cyclic garbage when the client finishes with the 'parent' object", "# in the tree.", "if", "isinstance", "(", "parent_message", ",", "weakref", ".", "ProxyType", ")", ":", "self", ".", "_parent_message_weakref", "=", "parent_message", "else", ":", "self", ".", "_parent_message_weakref", "=", "weakref", ".", "proxy", "(", "parent_message", ")", "# As an optimization, we also indicate directly on the listener whether", "# or not the parent message is dirty. This way we can avoid traversing", "# up the tree in the common case.", "self", ".", "dirty", "=", "False" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/python_message.py#L1369-L1386
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Wm.wm_frame
(self)
return self.tk.call('wm', 'frame', self._w)
Return identifier for decorative frame of this widget if present.
Return identifier for decorative frame of this widget if present.
[ "Return", "identifier", "for", "decorative", "frame", "of", "this", "widget", "if", "present", "." ]
def wm_frame(self): """Return identifier for decorative frame of this widget if present.""" return self.tk.call('wm', 'frame', self._w)
[ "def", "wm_frame", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'frame'", ",", "self", ".", "_w", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L1587-L1589
pytorch/glow
15baf2376f7ebff7d4e75ccb094624a9c1e9a089
utils/compilation_filter.py
python
find_all_related_transformation
(cursor: sqlite3.Cursor, transIDs: List[str])
return transIDs
A recursive function that find all related transformations given a list of transformation IDs in the database. Args: cursor: sqlite3.Cursor. Cursor of current sqlite3 database connection. transIDs: List[str]. A list of transformation IDs.
A recursive function that find all related transformations given a list of transformation IDs in the database.
[ "A", "recursive", "function", "that", "find", "all", "related", "transformations", "given", "a", "list", "of", "transformation", "IDs", "in", "the", "database", "." ]
def find_all_related_transformation(cursor: sqlite3.Cursor, transIDs: List[str]): """A recursive function that find all related transformations given a list of transformation IDs in the database. Args: cursor: sqlite3.Cursor. Cursor of current sqlite3 database connection. transIDs: List[str]. A list of transformation IDs. """ transQueryStr = "(" + ", ".join(transIDs) + ")" cursor.execute( f""" SELECT node_name FROM Log_Transformation WHERE trans_id in {transQueryStr} and operation_type in ('ADD_OPERAND', 'REMOVE_OPERAND') GROUP BY node_name """ ) rows = cursor.fetchall() nodesList = ["'" + r[0] + "'" for r in rows] transQueryStr = "(" + ", ".join(nodesList) + ")" cursor.execute( f""" SELECT trans_id FROM Log_Transformation WHERE node_name in {transQueryStr} and operation_type in ('ADD_OPERAND', 'REMOVE_OPERAND') GROUP BY trans_id """ ) rows = cursor.fetchall() newTransIDs = [str(r[0]) for r in rows] if sorted(newTransIDs) != sorted(transIDs): transIDs = find_all_related_transformation(cursor, newTransIDs) return transIDs
[ "def", "find_all_related_transformation", "(", "cursor", ":", "sqlite3", ".", "Cursor", ",", "transIDs", ":", "List", "[", "str", "]", ")", ":", "transQueryStr", "=", "\"(\"", "+", "\", \"", ".", "join", "(", "transIDs", ")", "+", "\")\"", "cursor", ".", "execute", "(", "f\"\"\"\n SELECT node_name\n FROM Log_Transformation\n WHERE trans_id in {transQueryStr} and operation_type in ('ADD_OPERAND', 'REMOVE_OPERAND')\n GROUP BY node_name\n \"\"\"", ")", "rows", "=", "cursor", ".", "fetchall", "(", ")", "nodesList", "=", "[", "\"'\"", "+", "r", "[", "0", "]", "+", "\"'\"", "for", "r", "in", "rows", "]", "transQueryStr", "=", "\"(\"", "+", "\", \"", ".", "join", "(", "nodesList", ")", "+", "\")\"", "cursor", ".", "execute", "(", "f\"\"\"\n SELECT trans_id\n FROM Log_Transformation\n WHERE node_name in {transQueryStr} and operation_type in ('ADD_OPERAND', 'REMOVE_OPERAND')\n GROUP BY trans_id\n \"\"\"", ")", "rows", "=", "cursor", ".", "fetchall", "(", ")", "newTransIDs", "=", "[", "str", "(", "r", "[", "0", "]", ")", "for", "r", "in", "rows", "]", "if", "sorted", "(", "newTransIDs", ")", "!=", "sorted", "(", "transIDs", ")", ":", "transIDs", "=", "find_all_related_transformation", "(", "cursor", ",", "newTransIDs", ")", "return", "transIDs" ]
https://github.com/pytorch/glow/blob/15baf2376f7ebff7d4e75ccb094624a9c1e9a089/utils/compilation_filter.py#L161-L195
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/site.py
python
check_enableusersite
()
return True
Check if user site directory is safe for inclusion The function tests for the command line flag (including environment var), process uid/gid equal to effective uid/gid. None: Disabled for security reasons False: Disabled by user (command line option) True: Safe and enabled
Check if user site directory is safe for inclusion
[ "Check", "if", "user", "site", "directory", "is", "safe", "for", "inclusion" ]
def check_enableusersite(): """Check if user site directory is safe for inclusion The function tests for the command line flag (including environment var), process uid/gid equal to effective uid/gid. None: Disabled for security reasons False: Disabled by user (command line option) True: Safe and enabled """ if sys.flags.no_user_site: return False if hasattr(os, "getuid") and hasattr(os, "geteuid"): # check process uid == effective uid if os.geteuid() != os.getuid(): return None if hasattr(os, "getgid") and hasattr(os, "getegid"): # check process gid == effective gid if os.getegid() != os.getgid(): return None return True
[ "def", "check_enableusersite", "(", ")", ":", "if", "sys", ".", "flags", ".", "no_user_site", ":", "return", "False", "if", "hasattr", "(", "os", ",", "\"getuid\"", ")", "and", "hasattr", "(", "os", ",", "\"geteuid\"", ")", ":", "# check process uid == effective uid", "if", "os", ".", "geteuid", "(", ")", "!=", "os", ".", "getuid", "(", ")", ":", "return", "None", "if", "hasattr", "(", "os", ",", "\"getgid\"", ")", "and", "hasattr", "(", "os", ",", "\"getegid\"", ")", ":", "# check process gid == effective gid", "if", "os", ".", "getegid", "(", ")", "!=", "os", ".", "getgid", "(", ")", ":", "return", "None", "return", "True" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/site.py#L198-L220
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/s3fs/errors.py
python
translate_boto_error
(error, message=None, *args, **kwargs)
return constructor(message, *args, **kwargs)
Convert a ClientError exception into a Python one. Parameters ---------- error : botocore.exceptions.ClientError The exception returned by the boto API. message : str An error message to use for the returned exception. If not given, the error message returned by the server is used instead. *args, **kwargs : Additional arguments to pass to the exception constructor, after the error message. Useful for passing the filename arguments to ``IOError``. Returns ------- An instantiated exception ready to be thrown. If the error code isn't recognized, an IOError with the original error message is returned.
Convert a ClientError exception into a Python one.
[ "Convert", "a", "ClientError", "exception", "into", "a", "Python", "one", "." ]
def translate_boto_error(error, message=None, *args, **kwargs): """Convert a ClientError exception into a Python one. Parameters ---------- error : botocore.exceptions.ClientError The exception returned by the boto API. message : str An error message to use for the returned exception. If not given, the error message returned by the server is used instead. *args, **kwargs : Additional arguments to pass to the exception constructor, after the error message. Useful for passing the filename arguments to ``IOError``. Returns ------- An instantiated exception ready to be thrown. If the error code isn't recognized, an IOError with the original error message is returned. """ code = error.response['Error'].get('Code') constructor = ERROR_CODE_TO_EXCEPTION.get(code) if not constructor: # No match found, wrap this in an IOError with the appropriate message. return IOError(errno.EIO, message or str(error), *args) if not message: message = error.response['Error'].get('Message', str(error)) return constructor(message, *args, **kwargs)
[ "def", "translate_boto_error", "(", "error", ",", "message", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "code", "=", "error", ".", "response", "[", "'Error'", "]", ".", "get", "(", "'Code'", ")", "constructor", "=", "ERROR_CODE_TO_EXCEPTION", ".", "get", "(", "code", ")", "if", "not", "constructor", ":", "# No match found, wrap this in an IOError with the appropriate message.", "return", "IOError", "(", "errno", ".", "EIO", ",", "message", "or", "str", "(", "error", ")", ",", "*", "args", ")", "if", "not", "message", ":", "message", "=", "error", ".", "response", "[", "'Error'", "]", ".", "get", "(", "'Message'", ",", "str", "(", "error", ")", ")", "return", "constructor", "(", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/s3fs/errors.py#L115-L145
gv22ga/dlib-face-recognition-android
42d6305cbd85833f2b85bb79b70ab9ab004153c9
tools/lint/cpplint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", ".", "/", "*", "...", "*", "/", "comments", "are", "legit", "inside", "macros", "for", "one", "line", ".", "Otherwise", "we", "prefer", "//", "comments", "so", "it", "s", "ok", "to", "warn", "about", "the", "other", ".", "Likewise", "it", "s", "ok", "for", "strings", "to", "extend", "across", "multiple", "lines", "as", "long", "as", "a", "line", "continuation", "character", "(", "backslash", ")", "terminates", "each", "line", ".", "Although", "not", "currently", "prohibited", "by", "the", "C", "++", "style", "guide", "it", "s", "ugly", "and", "unnecessary", ".", "We", "don", "t", "do", "well", "with", "either", "in", "this", "lint", "program", "so", "we", "warn", "about", "both", ".", "Args", ":", "filename", ":", "The", "name", "of", "the", "current", "file", ".", "clean_lines", ":", "A", "CleansedLines", "instance", "containing", "the", "file", ".", "linenum", ":", "The", "number", "of", "the", "line", "to", "check", ".", "error", ":", "The", "function", "to", "call", "with", "any", "errors", "found", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/gv22ga/dlib-face-recognition-android/blob/42d6305cbd85833f2b85bb79b70ab9ab004153c9/tools/lint/cpplint.py#L1847-L1880
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/message.py
python
Message.__setitem__
(self, name, val)
Set the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers.
Set the value of a header.
[ "Set", "the", "value", "of", "a", "header", "." ]
def __setitem__(self, name, val): """Set the value of a header. Note: this does not overwrite an existing header with the same field name. Use __delitem__() first to delete any existing headers. """ self._headers.append((name, val))
[ "def", "__setitem__", "(", "self", ",", "name", ",", "val", ")", ":", "self", ".", "_headers", ".", "append", "(", "(", "name", ",", "val", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/email/message.py#L296-L302
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_menu.py
python
WalkMenu
(menu, label, collection)
return collection
Recursively walk a menu and collect all its sub items @param menu: wxMenu to walk @param label: the menu's label @param collection: dictionary to collect results in @return: dict {menulabel : [menu id, (item1 id, label1),]}
Recursively walk a menu and collect all its sub items @param menu: wxMenu to walk @param label: the menu's label @param collection: dictionary to collect results in @return: dict {menulabel : [menu id, (item1 id, label1),]}
[ "Recursively", "walk", "a", "menu", "and", "collect", "all", "its", "sub", "items", "@param", "menu", ":", "wxMenu", "to", "walk", "@param", "label", ":", "the", "menu", "s", "label", "@param", "collection", ":", "dictionary", "to", "collect", "results", "in", "@return", ":", "dict", "{", "menulabel", ":", "[", "menu", "id", "(", "item1", "id", "label1", ")", "]", "}" ]
def WalkMenu(menu, label, collection): """Recursively walk a menu and collect all its sub items @param menu: wxMenu to walk @param label: the menu's label @param collection: dictionary to collect results in @return: dict {menulabel : [menu id, (item1 id, label1),]} """ if label not in collection: collection[label] = list() for item in menu.GetMenuItems(): i_id = item.GetId() if item.IsSubMenu(): # Ignore dynamically generated menus if i_id not in (ed_glob.ID_FHIST, ed_glob.ID_LEXER, ed_glob.ID_PERSPECTIVES): ilbl = item.GetItemLabelText() collection[ilbl] = [i_id, ] WalkMenu(item.GetSubMenu(), ilbl, collection) else: continue elif item.IsSeparator(): continue elif _FindStringRep(i_id) is not None: lbl = item.GetItemLabelText().split('\t')[0].strip() # wxBug? Even the methods that are supposed to return the text # without mnemonics or accelerators on gtk return the string with # underscores where the mnemonics '&' are in the original strings if wx.Platform == '__WXGTK__': lbl = lbl.replace('_', '', 1) collection[label].append((i_id, lbl)) else: continue return collection
[ "def", "WalkMenu", "(", "menu", ",", "label", ",", "collection", ")", ":", "if", "label", "not", "in", "collection", ":", "collection", "[", "label", "]", "=", "list", "(", ")", "for", "item", "in", "menu", ".", "GetMenuItems", "(", ")", ":", "i_id", "=", "item", ".", "GetId", "(", ")", "if", "item", ".", "IsSubMenu", "(", ")", ":", "# Ignore dynamically generated menus", "if", "i_id", "not", "in", "(", "ed_glob", ".", "ID_FHIST", ",", "ed_glob", ".", "ID_LEXER", ",", "ed_glob", ".", "ID_PERSPECTIVES", ")", ":", "ilbl", "=", "item", ".", "GetItemLabelText", "(", ")", "collection", "[", "ilbl", "]", "=", "[", "i_id", ",", "]", "WalkMenu", "(", "item", ".", "GetSubMenu", "(", ")", ",", "ilbl", ",", "collection", ")", "else", ":", "continue", "elif", "item", ".", "IsSeparator", "(", ")", ":", "continue", "elif", "_FindStringRep", "(", "i_id", ")", "is", "not", "None", ":", "lbl", "=", "item", ".", "GetItemLabelText", "(", ")", ".", "split", "(", "'\\t'", ")", "[", "0", "]", ".", "strip", "(", ")", "# wxBug? Even the methods that are supposed to return the text", "# without mnemonics or accelerators on gtk return the string with", "# underscores where the mnemonics '&' are in the original strings", "if", "wx", ".", "Platform", "==", "'__WXGTK__'", ":", "lbl", "=", "lbl", ".", "replace", "(", "'_'", ",", "''", ",", "1", ")", "collection", "[", "label", "]", ".", "append", "(", "(", "i_id", ",", "lbl", ")", ")", "else", ":", "continue", "return", "collection" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_menu.py#L1194-L1228
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_pydecimal.py
python
Decimal._power_modulo
(self, other, modulo, context=None)
return _dec_from_triple(sign, str(base), 0)
Three argument version of __pow__
Three argument version of __pow__
[ "Three", "argument", "version", "of", "__pow__" ]
def _power_modulo(self, other, modulo, context=None): """Three argument version of __pow__""" other = _convert_other(other) if other is NotImplemented: return other modulo = _convert_other(modulo) if modulo is NotImplemented: return modulo if context is None: context = getcontext() # deal with NaNs: if there are any sNaNs then first one wins, # (i.e. behaviour for NaNs is identical to that of fma) self_is_nan = self._isnan() other_is_nan = other._isnan() modulo_is_nan = modulo._isnan() if self_is_nan or other_is_nan or modulo_is_nan: if self_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', self) if other_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', other) if modulo_is_nan == 2: return context._raise_error(InvalidOperation, 'sNaN', modulo) if self_is_nan: return self._fix_nan(context) if other_is_nan: return other._fix_nan(context) return modulo._fix_nan(context) # check inputs: we apply same restrictions as Python's pow() if not (self._isinteger() and other._isinteger() and modulo._isinteger()): return context._raise_error(InvalidOperation, 'pow() 3rd argument not allowed ' 'unless all arguments are integers') if other < 0: return context._raise_error(InvalidOperation, 'pow() 2nd argument cannot be ' 'negative when 3rd argument specified') if not modulo: return context._raise_error(InvalidOperation, 'pow() 3rd argument cannot be 0') # additional restriction for decimal: the modulus must be less # than 10**prec in absolute value if modulo.adjusted() >= context.prec: return context._raise_error(InvalidOperation, 'insufficient precision: pow() 3rd ' 'argument must not have more than ' 'precision digits') # define 0**0 == NaN, for consistency with two-argument pow # (even though it hurts!) if not other and not self: return context._raise_error(InvalidOperation, 'at least one of pow() 1st argument ' 'and 2nd argument must be nonzero; ' '0**0 is not defined') # compute sign of result if other._iseven(): sign = 0 else: sign = self._sign # convert modulo to a Python integer, and self and other to # Decimal integers (i.e. force their exponents to be >= 0) modulo = abs(int(modulo)) base = _WorkRep(self.to_integral_value()) exponent = _WorkRep(other.to_integral_value()) # compute result using integer pow() base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo for i in range(exponent.exp): base = pow(base, 10, modulo) base = pow(base, exponent.int, modulo) return _dec_from_triple(sign, str(base), 0)
[ "def", "_power_modulo", "(", "self", ",", "other", ",", "modulo", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "modulo", "=", "_convert_other", "(", "modulo", ")", "if", "modulo", "is", "NotImplemented", ":", "return", "modulo", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "# deal with NaNs: if there are any sNaNs then first one wins,", "# (i.e. behaviour for NaNs is identical to that of fma)", "self_is_nan", "=", "self", ".", "_isnan", "(", ")", "other_is_nan", "=", "other", ".", "_isnan", "(", ")", "modulo_is_nan", "=", "modulo", ".", "_isnan", "(", ")", "if", "self_is_nan", "or", "other_is_nan", "or", "modulo_is_nan", ":", "if", "self_is_nan", "==", "2", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'sNaN'", ",", "self", ")", "if", "other_is_nan", "==", "2", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'sNaN'", ",", "other", ")", "if", "modulo_is_nan", "==", "2", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'sNaN'", ",", "modulo", ")", "if", "self_is_nan", ":", "return", "self", ".", "_fix_nan", "(", "context", ")", "if", "other_is_nan", ":", "return", "other", ".", "_fix_nan", "(", "context", ")", "return", "modulo", ".", "_fix_nan", "(", "context", ")", "# check inputs: we apply same restrictions as Python's pow()", "if", "not", "(", "self", ".", "_isinteger", "(", ")", "and", "other", ".", "_isinteger", "(", ")", "and", "modulo", ".", "_isinteger", "(", ")", ")", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'pow() 3rd argument not allowed '", "'unless all arguments are integers'", ")", "if", "other", "<", "0", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'pow() 2nd argument cannot be '", "'negative when 3rd argument specified'", ")", "if", "not", "modulo", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'pow() 3rd argument cannot be 0'", ")", "# additional restriction for decimal: the modulus must be less", "# than 10**prec in absolute value", "if", "modulo", ".", "adjusted", "(", ")", ">=", "context", ".", "prec", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'insufficient precision: pow() 3rd '", "'argument must not have more than '", "'precision digits'", ")", "# define 0**0 == NaN, for consistency with two-argument pow", "# (even though it hurts!)", "if", "not", "other", "and", "not", "self", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ",", "'at least one of pow() 1st argument '", "'and 2nd argument must be nonzero; '", "'0**0 is not defined'", ")", "# compute sign of result", "if", "other", ".", "_iseven", "(", ")", ":", "sign", "=", "0", "else", ":", "sign", "=", "self", ".", "_sign", "# convert modulo to a Python integer, and self and other to", "# Decimal integers (i.e. force their exponents to be >= 0)", "modulo", "=", "abs", "(", "int", "(", "modulo", ")", ")", "base", "=", "_WorkRep", "(", "self", ".", "to_integral_value", "(", ")", ")", "exponent", "=", "_WorkRep", "(", "other", ".", "to_integral_value", "(", ")", ")", "# compute result using integer pow()", "base", "=", "(", "base", ".", "int", "%", "modulo", "*", "pow", "(", "10", ",", "base", ".", "exp", ",", "modulo", ")", ")", "%", "modulo", "for", "i", "in", "range", "(", "exponent", ".", "exp", ")", ":", "base", "=", "pow", "(", "base", ",", "10", ",", "modulo", ")", "base", "=", "pow", "(", "base", ",", "exponent", ".", "int", ",", "modulo", ")", "return", "_dec_from_triple", "(", "sign", ",", "str", "(", "base", ")", ",", "0", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L1966-L2049
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Context.compare
(self, a, b)
return a.compare(b, context=self)
Compares values numerically. If the signs of the operands differ, a value representing each operand ('-1' if the operand is less than zero, '0' if the operand is zero or negative zero, or '1' if the operand is greater than zero) is used in place of that operand for the comparison instead of the actual operand. The comparison is then effected by subtracting the second operand from the first and then returning a value according to the result of the subtraction: '-1' if the result is less than zero, '0' if the result is zero or negative zero, or '1' if the result is greater than zero. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) Decimal('-1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) Decimal('0') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) Decimal('0') >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) Decimal('1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) Decimal('1') >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) Decimal('-1')
Compares values numerically.
[ "Compares", "values", "numerically", "." ]
def compare(self, a, b): """Compares values numerically. If the signs of the operands differ, a value representing each operand ('-1' if the operand is less than zero, '0' if the operand is zero or negative zero, or '1' if the operand is greater than zero) is used in place of that operand for the comparison instead of the actual operand. The comparison is then effected by subtracting the second operand from the first and then returning a value according to the result of the subtraction: '-1' if the result is less than zero, '0' if the result is zero or negative zero, or '1' if the result is greater than zero. >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) Decimal('-1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) Decimal('0') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) Decimal('0') >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) Decimal('1') >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) Decimal('1') >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) Decimal('-1') """ return a.compare(b, context=self)
[ "def", "compare", "(", "self", ",", "a", ",", "b", ")", ":", "return", "a", ".", "compare", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L3829-L3856
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/keras/python/keras/models.py
python
Sequential.compile
(self, optimizer, loss, metrics=None, sample_weight_mode=None, **kwargs)
Configures the learning process. Arguments: optimizer: str (name of optimizer) or optimizer object. See [optimizers](/optimizers). loss: str (name of objective function) or objective function. See [losses](/losses). metrics: list of metrics to be evaluated by the model during training and testing. Typically you will use `metrics=['accuracy']`. See [metrics](/metrics). sample_weight_mode: if you need to do timestep-wise sample weighting (2D weights), set this to "temporal". "None" defaults to sample-wise weights (1D). **kwargs: for Theano backend, these are passed into K.function. When using the Tensorflow backend, these are passed into `tf.Session.run`. Example: ```python model = Sequential() model.add(Dense(32, input_shape=(500,))) model.add(Dense(10, activation='softmax')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) ```
Configures the learning process.
[ "Configures", "the", "learning", "process", "." ]
def compile(self, optimizer, loss, metrics=None, sample_weight_mode=None, **kwargs): """Configures the learning process. Arguments: optimizer: str (name of optimizer) or optimizer object. See [optimizers](/optimizers). loss: str (name of objective function) or objective function. See [losses](/losses). metrics: list of metrics to be evaluated by the model during training and testing. Typically you will use `metrics=['accuracy']`. See [metrics](/metrics). sample_weight_mode: if you need to do timestep-wise sample weighting (2D weights), set this to "temporal". "None" defaults to sample-wise weights (1D). **kwargs: for Theano backend, these are passed into K.function. When using the Tensorflow backend, these are passed into `tf.Session.run`. Example: ```python model = Sequential() model.add(Dense(32, input_shape=(500,))) model.add(Dense(10, activation='softmax')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) ``` """ # create the underlying model self.build() # call compile method of Model class self.model.compile( optimizer, loss, metrics=metrics, sample_weight_mode=sample_weight_mode, **kwargs) self.optimizer = self.model.optimizer self.loss = self.model.loss self.total_loss = self.model.total_loss self.loss_weights = self.model.loss_weights self.metrics = self.model.metrics self.metrics_tensors = self.model.metrics_tensors self.metrics_names = self.model.metrics_names self.sample_weight_mode = self.model.sample_weight_mode self.sample_weights = self.model.sample_weights self.targets = self.model.targets
[ "def", "compile", "(", "self", ",", "optimizer", ",", "loss", ",", "metrics", "=", "None", ",", "sample_weight_mode", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# create the underlying model", "self", ".", "build", "(", ")", "# call compile method of Model class", "self", ".", "model", ".", "compile", "(", "optimizer", ",", "loss", ",", "metrics", "=", "metrics", ",", "sample_weight_mode", "=", "sample_weight_mode", ",", "*", "*", "kwargs", ")", "self", ".", "optimizer", "=", "self", ".", "model", ".", "optimizer", "self", ".", "loss", "=", "self", ".", "model", ".", "loss", "self", ".", "total_loss", "=", "self", ".", "model", ".", "total_loss", "self", ".", "loss_weights", "=", "self", ".", "model", ".", "loss_weights", "self", ".", "metrics", "=", "self", ".", "model", ".", "metrics", "self", ".", "metrics_tensors", "=", "self", ".", "model", ".", "metrics_tensors", "self", ".", "metrics_names", "=", "self", ".", "model", ".", "metrics_names", "self", ".", "sample_weight_mode", "=", "self", ".", "model", ".", "sample_weight_mode", "self", ".", "sample_weights", "=", "self", ".", "model", ".", "sample_weights", "self", ".", "targets", "=", "self", ".", "model", ".", "targets" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/keras/python/keras/models.py#L727-L779
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py
python
Window._show_input_processor_key_buffer
(self, cli, new_screen)
When the user is typing a key binding that consists of several keys, display the last pressed key if the user is in insert mode and the key is meaningful to be displayed. E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the first 'j' needs to be displayed in order to get some feedback.
When the user is typing a key binding that consists of several keys, display the last pressed key if the user is in insert mode and the key is meaningful to be displayed. E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the first 'j' needs to be displayed in order to get some feedback.
[ "When", "the", "user", "is", "typing", "a", "key", "binding", "that", "consists", "of", "several", "keys", "display", "the", "last", "pressed", "key", "if", "the", "user", "is", "in", "insert", "mode", "and", "the", "key", "is", "meaningful", "to", "be", "displayed", ".", "E", ".", "g", ".", "Some", "people", "want", "to", "bind", "jj", "to", "escape", "in", "Vi", "insert", "mode", ".", "But", "the", "first", "j", "needs", "to", "be", "displayed", "in", "order", "to", "get", "some", "feedback", "." ]
def _show_input_processor_key_buffer(self, cli, new_screen): """ When the user is typing a key binding that consists of several keys, display the last pressed key if the user is in insert mode and the key is meaningful to be displayed. E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the first 'j' needs to be displayed in order to get some feedback. """ key_buffer = cli.input_processor.key_buffer if key_buffer and _in_insert_mode(cli) and not cli.is_done: # The textual data for the given key. (Can be a VT100 escape # sequence.) data = key_buffer[-1].data # Display only if this is a 1 cell width character. if get_cwidth(data) == 1: cpos = new_screen.cursor_position new_screen.data_buffer[cpos.y][cpos.x] = \ _CHAR_CACHE[data, Token.PartialKeyBinding]
[ "def", "_show_input_processor_key_buffer", "(", "self", ",", "cli", ",", "new_screen", ")", ":", "key_buffer", "=", "cli", ".", "input_processor", ".", "key_buffer", "if", "key_buffer", "and", "_in_insert_mode", "(", "cli", ")", "and", "not", "cli", ".", "is_done", ":", "# The textual data for the given key. (Can be a VT100 escape", "# sequence.)", "data", "=", "key_buffer", "[", "-", "1", "]", ".", "data", "# Display only if this is a 1 cell width character.", "if", "get_cwidth", "(", "data", ")", "==", "1", ":", "cpos", "=", "new_screen", ".", "cursor_position", "new_screen", ".", "data_buffer", "[", "cpos", ".", "y", "]", "[", "cpos", ".", "x", "]", "=", "_CHAR_CACHE", "[", "data", ",", "Token", ".", "PartialKeyBinding", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/layout/containers.py#L1346-L1365
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/classifier/boosted_trees_classifier.py
python
create
( dataset, target, features=None, max_iterations=10, validation_set="auto", class_weights=None, max_depth=6, step_size=0.3, min_loss_reduction=0.0, min_child_weight=0.1, row_subsample=1.0, column_subsample=1.0, verbose=True, random_seed=None, metric="auto", **kwargs )
return BoostedTreesClassifier(model.__proxy__)
Create a (binary or multi-class) classifier model of type :class:`~turicreate.boosted_trees_classifier.BoostedTreesClassifier` using gradient boosted trees (sometimes known as GBMs). Parameters ---------- dataset : SFrame A training dataset containing feature columns and a target column. target : str Name of the column containing the target variable. The values in this column must be of string or integer type. String target variables are automatically mapped to integers in alphabetical order of the variable values. For example, a target variable with 'cat', 'dog', and 'foosa' as possible values is mapped to 0, 1, and, 2 respectively. features : list[str], optional A list of columns names of features used for training the model. Defaults to None, which uses all columns in the SFrame ``dataset`` excepting the target column.. max_iterations : int, optional The maximum number of iterations for boosting. Each iteration results in the creation of an extra tree. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. For each row of the progress table, the chosen metrics are computed for both the provided training dataset and the validation_set. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. This is computed once per full iteration. Large differences in model accuracy between the training data and validation data is indicative of overfitting. The default value is 'auto'. class_weights : {dict, `auto`}, optional Weights the examples in the training data according to the given class weights. If provided, the dictionary must contain a key for each class label. The value can be any positive number greater than 1e-20. Weights are interpreted as relative to each other. So setting the weights to be 2.0 for the positive class and 1.0 for the negative class has the same effect as setting them to be 20.0 and 10.0, respectively. If set to `None`, all classes are taken to have weight 1.0. The `auto` mode sets the class weight to be inversely proportional to the number of examples in the training data with the given class. max_depth : float, optional Maximum depth of a tree. Must be at least 1. step_size : float, [0,1], optional Step size (shrinkage) used in update to prevents overfitting. It shrinks the prediction of each weak learner to make the boosting process more conservative. The smaller the step size, the more conservative the algorithm will be. Smaller step_size work well when `max_iterations` is large. min_loss_reduction : float, optional (non-negative) Minimum loss reduction required to make a further partition/split a node during the tree learning phase. Larger (more positive) values can help prevent overfitting by avoiding splits that do not sufficiently reduce the loss function. min_child_weight : float, optional (non-negative) Controls the minimum weight of each leaf node. Larger values result in more conservative tree learning and help prevent overfitting. Formally, this is minimum sum of instance weights (hessians) in each node. If the tree learning algorithm results in a leaf node with the sum of instance weights less than `min_child_weight`, tree building will terminate. row_subsample : float, [0,1], optional Subsample the ratio of the training set in each iteration of tree construction. This is called the bagging trick and can usually help prevent overfitting. Setting this to a value of 0.5 results in the model randomly sampling half of the examples (rows) to grow each tree. column_subsample : float, [0,1], optional Subsample ratio of the columns in each iteration of tree construction. Like row_subsample, this can also help prevent model overfitting. Setting this to a value of 0.5 results in the model randomly sampling half of the columns to grow each tree. verbose : boolean, optional Print progress information during training (if set to true). random_seed : int, optional Seeds random opertations such as column and row subsampling, such that results are reproducable. metric : str or list[str], optional Performance metric(s) that are tracked during training. When specified, the progress table will display the tracked metric(s) on training and validation set. Supported metrics are: {'accuracy', 'auc', 'log_loss'} kwargs : dict, optional Additional arguments for training the model. - ``early_stopping_rounds`` : int, default None If the validation metric does not improve after <early_stopping_rounds>, stop training and return the best model. If multiple metrics are being tracked, the last one is used. - ``model_checkpoint_path`` : str, default None If specified, checkpoint the model training to the given path every n iterations, where n is specified by ``model_checkpoint_interval``. For instance, if `model_checkpoint_interval` is 5, and `model_checkpoint_path` is set to ``/tmp/model_tmp``, the checkpoints will be saved into ``/tmp/model_tmp/model_checkpoint_5``, ``/tmp/model_tmp/model_checkpoint_10``, ... etc. Training can be resumed by setting ``resume_from_checkpoint`` to one of these checkpoints. - ``model_checkpoint_interval`` : int, default 5 If model_check_point_path is specified, save the model to the given path every n iterations. - ``resume_from_checkpoint`` : str, default None Continues training from a model checkpoint. The model must take exact the same training data as the checkpointed model. Returns ------- out : BoostedTreesClassifier A trained gradient boosted trees model for classifications tasks. References ---------- - `Wikipedia - Gradient tree boosting <http://en.wikipedia.org/wiki/Gradient_boosting#Gradient_tree_boosting>`_ - `Trevor Hastie's slides on Boosted Trees and Random Forest <http://jessica2.msri.org/attachments/10778/10778-boost.pdf>`_ See Also -------- BoostedTreesClassifier, turicreate.logistic_classifier.LogisticClassifier, turicreate.svm_classifier.SVMClassifier Examples -------- .. sourcecode:: python >>> url = 'https://static.turi.com/datasets/xgboost/mushroom.csv' >>> data = turicreate.SFrame.read_csv(url) >>> train, test = data.random_split(0.8) >>> model = turicreate.boosted_trees_classifier.create(train, target='label') >>> predictions = model.classify(test) >>> results = model.evaluate(test)
Create a (binary or multi-class) classifier model of type :class:`~turicreate.boosted_trees_classifier.BoostedTreesClassifier` using gradient boosted trees (sometimes known as GBMs).
[ "Create", "a", "(", "binary", "or", "multi", "-", "class", ")", "classifier", "model", "of", "type", ":", "class", ":", "~turicreate", ".", "boosted_trees_classifier", ".", "BoostedTreesClassifier", "using", "gradient", "boosted", "trees", "(", "sometimes", "known", "as", "GBMs", ")", "." ]
def create( dataset, target, features=None, max_iterations=10, validation_set="auto", class_weights=None, max_depth=6, step_size=0.3, min_loss_reduction=0.0, min_child_weight=0.1, row_subsample=1.0, column_subsample=1.0, verbose=True, random_seed=None, metric="auto", **kwargs ): """ Create a (binary or multi-class) classifier model of type :class:`~turicreate.boosted_trees_classifier.BoostedTreesClassifier` using gradient boosted trees (sometimes known as GBMs). Parameters ---------- dataset : SFrame A training dataset containing feature columns and a target column. target : str Name of the column containing the target variable. The values in this column must be of string or integer type. String target variables are automatically mapped to integers in alphabetical order of the variable values. For example, a target variable with 'cat', 'dog', and 'foosa' as possible values is mapped to 0, 1, and, 2 respectively. features : list[str], optional A list of columns names of features used for training the model. Defaults to None, which uses all columns in the SFrame ``dataset`` excepting the target column.. max_iterations : int, optional The maximum number of iterations for boosting. Each iteration results in the creation of an extra tree. validation_set : SFrame, optional A dataset for monitoring the model's generalization performance. For each row of the progress table, the chosen metrics are computed for both the provided training dataset and the validation_set. The format of this SFrame must be the same as the training set. By default this argument is set to 'auto' and a validation set is automatically sampled and used for progress printing. If validation_set is set to None, then no additional metrics are computed. This is computed once per full iteration. Large differences in model accuracy between the training data and validation data is indicative of overfitting. The default value is 'auto'. class_weights : {dict, `auto`}, optional Weights the examples in the training data according to the given class weights. If provided, the dictionary must contain a key for each class label. The value can be any positive number greater than 1e-20. Weights are interpreted as relative to each other. So setting the weights to be 2.0 for the positive class and 1.0 for the negative class has the same effect as setting them to be 20.0 and 10.0, respectively. If set to `None`, all classes are taken to have weight 1.0. The `auto` mode sets the class weight to be inversely proportional to the number of examples in the training data with the given class. max_depth : float, optional Maximum depth of a tree. Must be at least 1. step_size : float, [0,1], optional Step size (shrinkage) used in update to prevents overfitting. It shrinks the prediction of each weak learner to make the boosting process more conservative. The smaller the step size, the more conservative the algorithm will be. Smaller step_size work well when `max_iterations` is large. min_loss_reduction : float, optional (non-negative) Minimum loss reduction required to make a further partition/split a node during the tree learning phase. Larger (more positive) values can help prevent overfitting by avoiding splits that do not sufficiently reduce the loss function. min_child_weight : float, optional (non-negative) Controls the minimum weight of each leaf node. Larger values result in more conservative tree learning and help prevent overfitting. Formally, this is minimum sum of instance weights (hessians) in each node. If the tree learning algorithm results in a leaf node with the sum of instance weights less than `min_child_weight`, tree building will terminate. row_subsample : float, [0,1], optional Subsample the ratio of the training set in each iteration of tree construction. This is called the bagging trick and can usually help prevent overfitting. Setting this to a value of 0.5 results in the model randomly sampling half of the examples (rows) to grow each tree. column_subsample : float, [0,1], optional Subsample ratio of the columns in each iteration of tree construction. Like row_subsample, this can also help prevent model overfitting. Setting this to a value of 0.5 results in the model randomly sampling half of the columns to grow each tree. verbose : boolean, optional Print progress information during training (if set to true). random_seed : int, optional Seeds random opertations such as column and row subsampling, such that results are reproducable. metric : str or list[str], optional Performance metric(s) that are tracked during training. When specified, the progress table will display the tracked metric(s) on training and validation set. Supported metrics are: {'accuracy', 'auc', 'log_loss'} kwargs : dict, optional Additional arguments for training the model. - ``early_stopping_rounds`` : int, default None If the validation metric does not improve after <early_stopping_rounds>, stop training and return the best model. If multiple metrics are being tracked, the last one is used. - ``model_checkpoint_path`` : str, default None If specified, checkpoint the model training to the given path every n iterations, where n is specified by ``model_checkpoint_interval``. For instance, if `model_checkpoint_interval` is 5, and `model_checkpoint_path` is set to ``/tmp/model_tmp``, the checkpoints will be saved into ``/tmp/model_tmp/model_checkpoint_5``, ``/tmp/model_tmp/model_checkpoint_10``, ... etc. Training can be resumed by setting ``resume_from_checkpoint`` to one of these checkpoints. - ``model_checkpoint_interval`` : int, default 5 If model_check_point_path is specified, save the model to the given path every n iterations. - ``resume_from_checkpoint`` : str, default None Continues training from a model checkpoint. The model must take exact the same training data as the checkpointed model. Returns ------- out : BoostedTreesClassifier A trained gradient boosted trees model for classifications tasks. References ---------- - `Wikipedia - Gradient tree boosting <http://en.wikipedia.org/wiki/Gradient_boosting#Gradient_tree_boosting>`_ - `Trevor Hastie's slides on Boosted Trees and Random Forest <http://jessica2.msri.org/attachments/10778/10778-boost.pdf>`_ See Also -------- BoostedTreesClassifier, turicreate.logistic_classifier.LogisticClassifier, turicreate.svm_classifier.SVMClassifier Examples -------- .. sourcecode:: python >>> url = 'https://static.turi.com/datasets/xgboost/mushroom.csv' >>> data = turicreate.SFrame.read_csv(url) >>> train, test = data.random_split(0.8) >>> model = turicreate.boosted_trees_classifier.create(train, target='label') >>> predictions = model.classify(test) >>> results = model.evaluate(test) """ if random_seed is not None: kwargs["random_seed"] = random_seed if "model_checkpoint_path" in kwargs: kwargs["model_checkpoint_path"] = _make_internal_url( kwargs["model_checkpoint_path"] ) if "resume_from_checkpoint" in kwargs: kwargs["resume_from_checkpoint"] = _make_internal_url( kwargs["resume_from_checkpoint"] ) model = _sl.create( dataset=dataset, target=target, features=features, model_name="boosted_trees_classifier", max_iterations=max_iterations, validation_set=validation_set, class_weights=class_weights, max_depth=max_depth, step_size=step_size, min_loss_reduction=min_loss_reduction, min_child_weight=min_child_weight, row_subsample=row_subsample, column_subsample=column_subsample, verbose=verbose, metric=metric, **kwargs ) return BoostedTreesClassifier(model.__proxy__)
[ "def", "create", "(", "dataset", ",", "target", ",", "features", "=", "None", ",", "max_iterations", "=", "10", ",", "validation_set", "=", "\"auto\"", ",", "class_weights", "=", "None", ",", "max_depth", "=", "6", ",", "step_size", "=", "0.3", ",", "min_loss_reduction", "=", "0.0", ",", "min_child_weight", "=", "0.1", ",", "row_subsample", "=", "1.0", ",", "column_subsample", "=", "1.0", ",", "verbose", "=", "True", ",", "random_seed", "=", "None", ",", "metric", "=", "\"auto\"", ",", "*", "*", "kwargs", ")", ":", "if", "random_seed", "is", "not", "None", ":", "kwargs", "[", "\"random_seed\"", "]", "=", "random_seed", "if", "\"model_checkpoint_path\"", "in", "kwargs", ":", "kwargs", "[", "\"model_checkpoint_path\"", "]", "=", "_make_internal_url", "(", "kwargs", "[", "\"model_checkpoint_path\"", "]", ")", "if", "\"resume_from_checkpoint\"", "in", "kwargs", ":", "kwargs", "[", "\"resume_from_checkpoint\"", "]", "=", "_make_internal_url", "(", "kwargs", "[", "\"resume_from_checkpoint\"", "]", ")", "model", "=", "_sl", ".", "create", "(", "dataset", "=", "dataset", ",", "target", "=", "target", ",", "features", "=", "features", ",", "model_name", "=", "\"boosted_trees_classifier\"", ",", "max_iterations", "=", "max_iterations", ",", "validation_set", "=", "validation_set", ",", "class_weights", "=", "class_weights", ",", "max_depth", "=", "max_depth", ",", "step_size", "=", "step_size", ",", "min_loss_reduction", "=", "min_loss_reduction", ",", "min_child_weight", "=", "min_child_weight", ",", "row_subsample", "=", "row_subsample", ",", "column_subsample", "=", "column_subsample", ",", "verbose", "=", "verbose", ",", "metric", "=", "metric", ",", "*", "*", "kwargs", ")", "return", "BoostedTreesClassifier", "(", "model", ".", "__proxy__", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/classifier/boosted_trees_classifier.py#L465-L666
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py
python
FitFunctionOptionsView.start_x
(self)
return float(self.start_x_line_edit.text())
Returns the selected start X.
Returns the selected start X.
[ "Returns", "the", "selected", "start", "X", "." ]
def start_x(self) -> float: """Returns the selected start X.""" return float(self.start_x_line_edit.text())
[ "def", "start_x", "(", "self", ")", "->", "float", ":", "return", "float", "(", "self", ".", "start_x_line_edit", ".", "text", "(", ")", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py#L218-L220
godotengine/godot
39562294ff3e6a273f9a73f97bc54791a4e98f07
platform/windows/detect.py
python
setup_msvc_auto
(env)
Set up MSVC using SCons's auto-detection logic
Set up MSVC using SCons's auto-detection logic
[ "Set", "up", "MSVC", "using", "SCons", "s", "auto", "-", "detection", "logic" ]
def setup_msvc_auto(env): """Set up MSVC using SCons's auto-detection logic""" # If MSVC_VERSION is set by SCons, we know MSVC is installed. # But we may want a different version or target arch. # The env may have already been set up with default MSVC tools, so # reset a few things so we can set it up with the tools we want. # (Ideally we'd decide on the tool config before configuring any # environment, and just set the env up once, but this function runs # on an existing env so this is the simplest way.) env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool env["MSVS_VERSION"] = None env["MSVC_VERSION"] = None env["TARGET_ARCH"] = None if env["bits"] != "default": env["TARGET_ARCH"] = {"32": "x86", "64": "x86_64"}[env["bits"]] if "msvc_version" in env: env["MSVC_VERSION"] = env["msvc_version"] env.Tool("msvc") env.Tool("mssdk") # we want the MS SDK # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015 # Get actual target arch into bits (it may be "default" at this point): if env["TARGET_ARCH"] in ("amd64", "x86_64"): env["bits"] = "64" else: env["bits"] = "32" print("Found MSVC version %s, arch %s, bits=%s" % (env["MSVC_VERSION"], env["TARGET_ARCH"], env["bits"])) if env["TARGET_ARCH"] in ("amd64", "x86_64"): env["x86_libtheora_opt_vc"] = False
[ "def", "setup_msvc_auto", "(", "env", ")", ":", "# If MSVC_VERSION is set by SCons, we know MSVC is installed.", "# But we may want a different version or target arch.", "# The env may have already been set up with default MSVC tools, so", "# reset a few things so we can set it up with the tools we want.", "# (Ideally we'd decide on the tool config before configuring any", "# environment, and just set the env up once, but this function runs", "# on an existing env so this is the simplest way.)", "env", "[", "\"MSVC_SETUP_RUN\"", "]", "=", "False", "# Need to set this to re-run the tool", "env", "[", "\"MSVS_VERSION\"", "]", "=", "None", "env", "[", "\"MSVC_VERSION\"", "]", "=", "None", "env", "[", "\"TARGET_ARCH\"", "]", "=", "None", "if", "env", "[", "\"bits\"", "]", "!=", "\"default\"", ":", "env", "[", "\"TARGET_ARCH\"", "]", "=", "{", "\"32\"", ":", "\"x86\"", ",", "\"64\"", ":", "\"x86_64\"", "}", "[", "env", "[", "\"bits\"", "]", "]", "if", "\"msvc_version\"", "in", "env", ":", "env", "[", "\"MSVC_VERSION\"", "]", "=", "env", "[", "\"msvc_version\"", "]", "env", ".", "Tool", "(", "\"msvc\"", ")", "env", ".", "Tool", "(", "\"mssdk\"", ")", "# we want the MS SDK", "# Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. \"14.1\" for VS2015", "# Get actual target arch into bits (it may be \"default\" at this point):", "if", "env", "[", "\"TARGET_ARCH\"", "]", "in", "(", "\"amd64\"", ",", "\"x86_64\"", ")", ":", "env", "[", "\"bits\"", "]", "=", "\"64\"", "else", ":", "env", "[", "\"bits\"", "]", "=", "\"32\"", "print", "(", "\"Found MSVC version %s, arch %s, bits=%s\"", "%", "(", "env", "[", "\"MSVC_VERSION\"", "]", ",", "env", "[", "\"TARGET_ARCH\"", "]", ",", "env", "[", "\"bits\"", "]", ")", ")", "if", "env", "[", "\"TARGET_ARCH\"", "]", "in", "(", "\"amd64\"", ",", "\"x86_64\"", ")", ":", "env", "[", "\"x86_libtheora_opt_vc\"", "]", "=", "False" ]
https://github.com/godotengine/godot/blob/39562294ff3e6a273f9a73f97bc54791a4e98f07/platform/windows/detect.py#L138-L167
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/client/timeline.py
python
Timeline._is_gputrace_device
(self, device_name)
return '/stream:' in device_name or '/memcpy' in device_name
Returns true if this device is part of the GPUTracer logging.
Returns true if this device is part of the GPUTracer logging.
[ "Returns", "true", "if", "this", "device", "is", "part", "of", "the", "GPUTracer", "logging", "." ]
def _is_gputrace_device(self, device_name): """Returns true if this device is part of the GPUTracer logging.""" return '/stream:' in device_name or '/memcpy' in device_name
[ "def", "_is_gputrace_device", "(", "self", ",", "device_name", ")", ":", "return", "'/stream:'", "in", "device_name", "or", "'/memcpy'", "in", "device_name" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/client/timeline.py#L458-L460
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/web.py
python
RequestHandler.create_template_loader
(self, template_path: str)
return template.Loader(template_path, **kwargs)
Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead.
Returns a new template loader for the given path.
[ "Returns", "a", "new", "template", "loader", "for", "the", "given", "path", "." ]
def create_template_loader(self, template_path: str) -> template.BaseLoader: """Returns a new template loader for the given path. May be overridden by subclasses. By default returns a directory-based loader on the given path, using the ``autoescape`` and ``template_whitespace`` application settings. If a ``template_loader`` application setting is supplied, uses that instead. """ settings = self.application.settings if "template_loader" in settings: return settings["template_loader"] kwargs = {} if "autoescape" in settings: # autoescape=None means "no escaping", so we have to be sure # to only pass this kwarg if the user asked for it. kwargs["autoescape"] = settings["autoescape"] if "template_whitespace" in settings: kwargs["whitespace"] = settings["template_whitespace"] return template.Loader(template_path, **kwargs)
[ "def", "create_template_loader", "(", "self", ",", "template_path", ":", "str", ")", "->", "template", ".", "BaseLoader", ":", "settings", "=", "self", ".", "application", ".", "settings", "if", "\"template_loader\"", "in", "settings", ":", "return", "settings", "[", "\"template_loader\"", "]", "kwargs", "=", "{", "}", "if", "\"autoescape\"", "in", "settings", ":", "# autoescape=None means \"no escaping\", so we have to be sure", "# to only pass this kwarg if the user asked for it.", "kwargs", "[", "\"autoescape\"", "]", "=", "settings", "[", "\"autoescape\"", "]", "if", "\"template_whitespace\"", "in", "settings", ":", "kwargs", "[", "\"whitespace\"", "]", "=", "settings", "[", "\"template_whitespace\"", "]", "return", "template", ".", "Loader", "(", "template_path", ",", "*", "*", "kwargs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/web.py#L1037-L1056
xlgames-inc/XLE
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
Foreign/FreeType/src/tools/docmaker/content.py
python
DocBlock.get_markup
( self, tag_name )
return None
Return the DocMarkup corresponding to a given tag in a block.
Return the DocMarkup corresponding to a given tag in a block.
[ "Return", "the", "DocMarkup", "corresponding", "to", "a", "given", "tag", "in", "a", "block", "." ]
def get_markup( self, tag_name ): """Return the DocMarkup corresponding to a given tag in a block.""" for m in self.markups: if m.tag == string.lower( tag_name ): return m return None
[ "def", "get_markup", "(", "self", ",", "tag_name", ")", ":", "for", "m", "in", "self", ".", "markups", ":", "if", "m", ".", "tag", "==", "string", ".", "lower", "(", "tag_name", ")", ":", "return", "m", "return", "None" ]
https://github.com/xlgames-inc/XLE/blob/cdd8682367d9e9fdbdda9f79d72bb5b1499cec46/Foreign/FreeType/src/tools/docmaker/content.py#L597-L602
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/mem/slicc/parser.py
python
SLICC.p_decls
(self, p)
decls : declsx
decls : declsx
[ "decls", ":", "declsx" ]
def p_decls(self, p): "decls : declsx" p[0] = ast.DeclListAST(self, p[1])
[ "def", "p_decls", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "DeclListAST", "(", "self", ",", "p", "[", "1", "]", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/slicc/parser.py#L240-L242
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/XRCed/view.py
python
Frame.InitToolBar
(self, long)
Initialize toolbar, long is boolean.
Initialize toolbar, long is boolean.
[ "Initialize", "toolbar", "long", "is", "boolean", "." ]
def InitToolBar(self, long): '''Initialize toolbar, long is boolean.''' tb = self.tb tb.ClearTools() new_bmp = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_TOOLBAR) open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR) save_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR) undo_bmp = wx.ArtProvider.GetBitmap(wx.ART_UNDO, wx.ART_TOOLBAR) redo_bmp = wx.ArtProvider.GetBitmap(wx.ART_REDO, wx.ART_TOOLBAR) cut_bmp = wx.ArtProvider.GetBitmap(wx.ART_CUT, wx.ART_TOOLBAR) copy_bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_TOOLBAR) paste_bmp= wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_TOOLBAR) if g.conf.TB_file: tb.AddSimpleTool(wx.ID_NEW, new_bmp, 'New', 'New file') tb.AddSimpleTool(wx.ID_OPEN, open_bmp, 'Open', 'Open file') tb.AddSimpleTool(wx.ID_SAVE, save_bmp, 'Save', 'Save file') tb.AddSeparator() if g.conf.TB_undo: tb.AddSimpleTool(wx.ID_UNDO, undo_bmp, 'Undo', 'Undo') tb.AddSimpleTool(wx.ID_REDO, redo_bmp, 'Redo', 'Redo') tb.AddSeparator() if g.conf.TB_copy: tb.AddSimpleTool(wx.ID_CUT, cut_bmp, 'Cut', 'Cut') tb.AddSimpleTool(wx.ID_COPY, copy_bmp, 'Copy', 'Copy') tb.AddSimpleTool(self.ID_TOOL_PASTE, paste_bmp, 'Paste', 'Paste') tb.AddSeparator() if g.conf.TB_move: bmp = wx.ArtProvider.GetBitmap(self.ART_MOVEUP, wx.ART_TOOLBAR) tb.AddSimpleTool(self.ID_MOVEUP, bmp, 'Up', 'Move before previous sibling') bmp = wx.ArtProvider.GetBitmap(self.ART_MOVEDOWN, wx.ART_TOOLBAR) tb.AddSimpleTool(self.ID_MOVEDOWN, bmp, 'Down', 'Move after next sibling') bmp = wx.ArtProvider.GetBitmap(self.ART_MOVELEFT, wx.ART_TOOLBAR) tb.AddSimpleTool(self.ID_MOVELEFT, bmp, 'Make Sibling', 'Make sibling of parent') bmp = wx.ArtProvider.GetBitmap(self.ART_MOVERIGHT, wx.ART_TOOLBAR) tb.AddSimpleTool(self.ID_MOVERIGHT, bmp, 'Make Child', 'Make child of previous sibling') if long: tb.AddSeparator() bmp = wx.ArtProvider.GetBitmap(self.ART_LOCATE, wx.ART_TOOLBAR) tb.AddSimpleTool(self.ID_TOOL_LOCATE, bmp, 'Locate', 'Locate control in test window and select it', True) bmp = wx.ArtProvider.GetBitmap(self.ART_TEST, wx.ART_TOOLBAR) tb.AddSimpleTool(self.ID_TEST, bmp, 'Test', 'Test window') bmp = wx.ArtProvider.GetBitmap(self.ART_REFRESH, wx.ART_TOOLBAR) tb.AddSimpleTool(wx.ID_REFRESH, bmp, 'Refresh', 'Refresh view') bmp = wx.ArtProvider.GetBitmap(self.ART_AUTO_REFRESH, wx.ART_TOOLBAR) tb.AddSimpleTool(self.ID_AUTO_REFRESH, bmp, 'Auto-refresh', 'Toggle auto-refresh mode', True) tb.ToggleTool(self.ID_AUTO_REFRESH, g.conf.autoRefresh) tb.Realize() self.minWidth = tb.GetSize()[0]
[ "def", "InitToolBar", "(", "self", ",", "long", ")", ":", "tb", "=", "self", ".", "tb", "tb", ".", "ClearTools", "(", ")", "new_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_NORMAL_FILE", ",", "wx", ".", "ART_TOOLBAR", ")", "open_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_FILE_OPEN", ",", "wx", ".", "ART_TOOLBAR", ")", "save_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_FILE_SAVE", ",", "wx", ".", "ART_TOOLBAR", ")", "undo_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_UNDO", ",", "wx", ".", "ART_TOOLBAR", ")", "redo_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_REDO", ",", "wx", ".", "ART_TOOLBAR", ")", "cut_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_CUT", ",", "wx", ".", "ART_TOOLBAR", ")", "copy_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_COPY", ",", "wx", ".", "ART_TOOLBAR", ")", "paste_bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "wx", ".", "ART_PASTE", ",", "wx", ".", "ART_TOOLBAR", ")", "if", "g", ".", "conf", ".", "TB_file", ":", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_NEW", ",", "new_bmp", ",", "'New'", ",", "'New file'", ")", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_OPEN", ",", "open_bmp", ",", "'Open'", ",", "'Open file'", ")", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_SAVE", ",", "save_bmp", ",", "'Save'", ",", "'Save file'", ")", "tb", ".", "AddSeparator", "(", ")", "if", "g", ".", "conf", ".", "TB_undo", ":", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_UNDO", ",", "undo_bmp", ",", "'Undo'", ",", "'Undo'", ")", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_REDO", ",", "redo_bmp", ",", "'Redo'", ",", "'Redo'", ")", "tb", ".", "AddSeparator", "(", ")", "if", "g", ".", "conf", ".", "TB_copy", ":", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_CUT", ",", "cut_bmp", ",", "'Cut'", ",", "'Cut'", ")", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_COPY", ",", "copy_bmp", ",", "'Copy'", ",", "'Copy'", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_TOOL_PASTE", ",", "paste_bmp", ",", "'Paste'", ",", "'Paste'", ")", "tb", ".", "AddSeparator", "(", ")", "if", "g", ".", "conf", ".", "TB_move", ":", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_MOVEUP", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_MOVEUP", ",", "bmp", ",", "'Up'", ",", "'Move before previous sibling'", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_MOVEDOWN", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_MOVEDOWN", ",", "bmp", ",", "'Down'", ",", "'Move after next sibling'", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_MOVELEFT", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_MOVELEFT", ",", "bmp", ",", "'Make Sibling'", ",", "'Make sibling of parent'", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_MOVERIGHT", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_MOVERIGHT", ",", "bmp", ",", "'Make Child'", ",", "'Make child of previous sibling'", ")", "if", "long", ":", "tb", ".", "AddSeparator", "(", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_LOCATE", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_TOOL_LOCATE", ",", "bmp", ",", "'Locate'", ",", "'Locate control in test window and select it'", ",", "True", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_TEST", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_TEST", ",", "bmp", ",", "'Test'", ",", "'Test window'", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_REFRESH", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "wx", ".", "ID_REFRESH", ",", "bmp", ",", "'Refresh'", ",", "'Refresh view'", ")", "bmp", "=", "wx", ".", "ArtProvider", ".", "GetBitmap", "(", "self", ".", "ART_AUTO_REFRESH", ",", "wx", ".", "ART_TOOLBAR", ")", "tb", ".", "AddSimpleTool", "(", "self", ".", "ID_AUTO_REFRESH", ",", "bmp", ",", "'Auto-refresh'", ",", "'Toggle auto-refresh mode'", ",", "True", ")", "tb", ".", "ToggleTool", "(", "self", ".", "ID_AUTO_REFRESH", ",", "g", ".", "conf", ".", "autoRefresh", ")", "tb", ".", "Realize", "(", ")", "self", ".", "minWidth", "=", "tb", ".", "GetSize", "(", ")", "[", "0", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/XRCed/view.py#L291-L344
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/slim/python/slim/nets/vgg.py
python
vgg_19
(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19')
Oxford Net VGG 19-Layers version E Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. Returns: the last op containing the log predictions and end_points dict.
Oxford Net VGG 19-Layers version E Example.
[ "Oxford", "Net", "VGG", "19", "-", "Layers", "version", "E", "Example", "." ]
def vgg_19(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19'): """Oxford Net VGG 19-Layers version E Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in classification mode, resize input to 224x224. Args: inputs: a tensor of size [batch_size, height, width, channels]. num_classes: number of predicted classes. is_training: whether or not the model is being trained. dropout_keep_prob: the probability that activations are kept in the dropout layers during training. spatial_squeeze: whether or not should squeeze the spatial dimensions of the outputs. Useful to remove unnecessary dimensions for classification. scope: Optional scope for the variables. Returns: the last op containing the log predictions and end_points dict. """ with variable_scope.variable_scope(scope, 'vgg_19', [inputs]) as sc: end_points_collection = sc.name + '_end_points' # Collect outputs for conv2d, fully_connected and max_pool2d. with arg_scope( [layers.conv2d, layers_lib.fully_connected, layers_lib.max_pool2d], outputs_collections=end_points_collection): net = layers_lib.repeat( inputs, 2, layers.conv2d, 64, [3, 3], scope='conv1') net = layers_lib.max_pool2d(net, [2, 2], scope='pool1') net = layers_lib.repeat(net, 2, layers.conv2d, 128, [3, 3], scope='conv2') net = layers_lib.max_pool2d(net, [2, 2], scope='pool2') net = layers_lib.repeat(net, 4, layers.conv2d, 256, [3, 3], scope='conv3') net = layers_lib.max_pool2d(net, [2, 2], scope='pool3') net = layers_lib.repeat(net, 4, layers.conv2d, 512, [3, 3], scope='conv4') net = layers_lib.max_pool2d(net, [2, 2], scope='pool4') net = layers_lib.repeat(net, 4, layers.conv2d, 512, [3, 3], scope='conv5') net = layers_lib.max_pool2d(net, [2, 2], scope='pool5') # Use conv2d instead of fully_connected layers. net = layers.conv2d(net, 4096, [7, 7], padding='VALID', scope='fc6') net = layers_lib.dropout( net, dropout_keep_prob, is_training=is_training, scope='dropout6') net = layers.conv2d(net, 4096, [1, 1], scope='fc7') net = layers_lib.dropout( net, dropout_keep_prob, is_training=is_training, scope='dropout7') net = layers.conv2d( net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='fc8') # Convert end_points_collection into a end_point dict. end_points = utils.convert_collection_to_dict(end_points_collection) if spatial_squeeze: net = array_ops.squeeze(net, [1, 2], name='fc8/squeezed') end_points[sc.name + '/fc8'] = net return net, end_points
[ "def", "vgg_19", "(", "inputs", ",", "num_classes", "=", "1000", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.5", ",", "spatial_squeeze", "=", "True", ",", "scope", "=", "'vgg_19'", ")", ":", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "'vgg_19'", ",", "[", "inputs", "]", ")", "as", "sc", ":", "end_points_collection", "=", "sc", ".", "name", "+", "'_end_points'", "# Collect outputs for conv2d, fully_connected and max_pool2d.", "with", "arg_scope", "(", "[", "layers", ".", "conv2d", ",", "layers_lib", ".", "fully_connected", ",", "layers_lib", ".", "max_pool2d", "]", ",", "outputs_collections", "=", "end_points_collection", ")", ":", "net", "=", "layers_lib", ".", "repeat", "(", "inputs", ",", "2", ",", "layers", ".", "conv2d", ",", "64", ",", "[", "3", ",", "3", "]", ",", "scope", "=", "'conv1'", ")", "net", "=", "layers_lib", ".", "max_pool2d", "(", "net", ",", "[", "2", ",", "2", "]", ",", "scope", "=", "'pool1'", ")", "net", "=", "layers_lib", ".", "repeat", "(", "net", ",", "2", ",", "layers", ".", "conv2d", ",", "128", ",", "[", "3", ",", "3", "]", ",", "scope", "=", "'conv2'", ")", "net", "=", "layers_lib", ".", "max_pool2d", "(", "net", ",", "[", "2", ",", "2", "]", ",", "scope", "=", "'pool2'", ")", "net", "=", "layers_lib", ".", "repeat", "(", "net", ",", "4", ",", "layers", ".", "conv2d", ",", "256", ",", "[", "3", ",", "3", "]", ",", "scope", "=", "'conv3'", ")", "net", "=", "layers_lib", ".", "max_pool2d", "(", "net", ",", "[", "2", ",", "2", "]", ",", "scope", "=", "'pool3'", ")", "net", "=", "layers_lib", ".", "repeat", "(", "net", ",", "4", ",", "layers", ".", "conv2d", ",", "512", ",", "[", "3", ",", "3", "]", ",", "scope", "=", "'conv4'", ")", "net", "=", "layers_lib", ".", "max_pool2d", "(", "net", ",", "[", "2", ",", "2", "]", ",", "scope", "=", "'pool4'", ")", "net", "=", "layers_lib", ".", "repeat", "(", "net", ",", "4", ",", "layers", ".", "conv2d", ",", "512", ",", "[", "3", ",", "3", "]", ",", "scope", "=", "'conv5'", ")", "net", "=", "layers_lib", ".", "max_pool2d", "(", "net", ",", "[", "2", ",", "2", "]", ",", "scope", "=", "'pool5'", ")", "# Use conv2d instead of fully_connected layers.", "net", "=", "layers", ".", "conv2d", "(", "net", ",", "4096", ",", "[", "7", ",", "7", "]", ",", "padding", "=", "'VALID'", ",", "scope", "=", "'fc6'", ")", "net", "=", "layers_lib", ".", "dropout", "(", "net", ",", "dropout_keep_prob", ",", "is_training", "=", "is_training", ",", "scope", "=", "'dropout6'", ")", "net", "=", "layers", ".", "conv2d", "(", "net", ",", "4096", ",", "[", "1", ",", "1", "]", ",", "scope", "=", "'fc7'", ")", "net", "=", "layers_lib", ".", "dropout", "(", "net", ",", "dropout_keep_prob", ",", "is_training", "=", "is_training", ",", "scope", "=", "'dropout7'", ")", "net", "=", "layers", ".", "conv2d", "(", "net", ",", "num_classes", ",", "[", "1", ",", "1", "]", ",", "activation_fn", "=", "None", ",", "normalizer_fn", "=", "None", ",", "scope", "=", "'fc8'", ")", "# Convert end_points_collection into a end_point dict.", "end_points", "=", "utils", ".", "convert_collection_to_dict", "(", "end_points_collection", ")", "if", "spatial_squeeze", ":", "net", "=", "array_ops", ".", "squeeze", "(", "net", ",", "[", "1", ",", "2", "]", ",", "name", "=", "'fc8/squeezed'", ")", "end_points", "[", "sc", ".", "name", "+", "'/fc8'", "]", "=", "net", "return", "net", ",", "end_points" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/slim/python/slim/nets/vgg.py#L204-L263
HKUST-Aerial-Robotics/Teach-Repeat-Replan
98505a7f74b13c8b501176ff838a38423dbef536
utils/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py
python
AuxCommand._get_types
(self)
return self._slot_types
internal API method
internal API method
[ "internal", "API", "method" ]
def _get_types(self): """ internal API method """ return self._slot_types
[ "def", "_get_types", "(", "self", ")", ":", "return", "self", ".", "_slot_types" ]
https://github.com/HKUST-Aerial-Robotics/Teach-Repeat-Replan/blob/98505a7f74b13c8b501176ff838a38423dbef536/utils/quadrotor_msgs/src/quadrotor_msgs/msg/_AuxCommand.py#L56-L60
iam-abbas/cs-algorithms
d04aa8fd9a1fa290266dde96afe9b90ee23c5a92
MachineLearning/agent.py
python
DQNAgent.replay
(self, batch_size=32)
vectorized implementation; 30x speed up compared with for loop
vectorized implementation; 30x speed up compared with for loop
[ "vectorized", "implementation", ";", "30x", "speed", "up", "compared", "with", "for", "loop" ]
def replay(self, batch_size=32): """ vectorized implementation; 30x speed up compared with for loop """ minibatch = random.sample(self.memory, batch_size) states = np.array([tup[0][0] for tup in minibatch]) actions = np.array([tup[1] for tup in minibatch]) rewards = np.array([tup[2] for tup in minibatch]) next_states = np.array([tup[3][0] for tup in minibatch]) done = np.array([tup[4] for tup in minibatch]) # Q(s', a) target = rewards + self.gamma * np.amax(self.model.predict(next_states), axis=1) # end state target is reward itself (no lookahead) target[done] = rewards[done] # Q(s, a) target_f = self.model.predict(states) # make the agent to approximately map the current state to future discounted reward target_f[range(batch_size), actions] = target self.model.fit(states, target_f, epochs=1, verbose=0) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay
[ "def", "replay", "(", "self", ",", "batch_size", "=", "32", ")", ":", "minibatch", "=", "random", ".", "sample", "(", "self", ".", "memory", ",", "batch_size", ")", "states", "=", "np", ".", "array", "(", "[", "tup", "[", "0", "]", "[", "0", "]", "for", "tup", "in", "minibatch", "]", ")", "actions", "=", "np", ".", "array", "(", "[", "tup", "[", "1", "]", "for", "tup", "in", "minibatch", "]", ")", "rewards", "=", "np", ".", "array", "(", "[", "tup", "[", "2", "]", "for", "tup", "in", "minibatch", "]", ")", "next_states", "=", "np", ".", "array", "(", "[", "tup", "[", "3", "]", "[", "0", "]", "for", "tup", "in", "minibatch", "]", ")", "done", "=", "np", ".", "array", "(", "[", "tup", "[", "4", "]", "for", "tup", "in", "minibatch", "]", ")", "# Q(s', a)", "target", "=", "rewards", "+", "self", ".", "gamma", "*", "np", ".", "amax", "(", "self", ".", "model", ".", "predict", "(", "next_states", ")", ",", "axis", "=", "1", ")", "# end state target is reward itself (no lookahead)", "target", "[", "done", "]", "=", "rewards", "[", "done", "]", "# Q(s, a)", "target_f", "=", "self", ".", "model", ".", "predict", "(", "states", ")", "# make the agent to approximately map the current state to future discounted reward", "target_f", "[", "range", "(", "batch_size", ")", ",", "actions", "]", "=", "target", "self", ".", "model", ".", "fit", "(", "states", ",", "target_f", ",", "epochs", "=", "1", ",", "verbose", "=", "0", ")", "if", "self", ".", "epsilon", ">", "self", ".", "epsilon_min", ":", "self", ".", "epsilon", "*=", "self", ".", "epsilon_decay" ]
https://github.com/iam-abbas/cs-algorithms/blob/d04aa8fd9a1fa290266dde96afe9b90ee23c5a92/MachineLearning/agent.py#L32-L55
spencer-project/spencer_people_tracking
09b256ba4bc22c5cae8a5ae88960de1a387cfd7f
tracking/people/spencer_tracking_metrics/src/spencer_tracking_metrics/pymot/__init__.py
python
MOTEvaluation.resetStatistics
(self)
Reset counters and mapping.
Reset counters and mapping.
[ "Reset", "counters", "and", "mapping", "." ]
def resetStatistics(self): """Reset counters and mapping.""" self.resetMapping() # yin-yang self.recoverable_mismatches_ = 0 self.non_recoverable_mismatches_ = 0 # MOTA related self.mismatches_ = 0 self.misses_ = 0 self.false_positives_ = 0 self.total_groundtruths_ = 0 self.total_distance_ = 0.0 self.total_correspondences_ = 0 self.total_matches_ = 0 self.groundtruth_ids_ = set() self.hypothesis_ids_ = set() self.mostly_tracked_list = dict()
[ "def", "resetStatistics", "(", "self", ")", ":", "self", ".", "resetMapping", "(", ")", "# yin-yang", "self", ".", "recoverable_mismatches_", "=", "0", "self", ".", "non_recoverable_mismatches_", "=", "0", "# MOTA related", "self", ".", "mismatches_", "=", "0", "self", ".", "misses_", "=", "0", "self", ".", "false_positives_", "=", "0", "self", ".", "total_groundtruths_", "=", "0", "self", ".", "total_distance_", "=", "0.0", "self", ".", "total_correspondences_", "=", "0", "self", ".", "total_matches_", "=", "0", "self", ".", "groundtruth_ids_", "=", "set", "(", ")", "self", ".", "hypothesis_ids_", "=", "set", "(", ")", "self", ".", "mostly_tracked_list", "=", "dict", "(", ")" ]
https://github.com/spencer-project/spencer_people_tracking/blob/09b256ba4bc22c5cae8a5ae88960de1a387cfd7f/tracking/people/spencer_tracking_metrics/src/spencer_tracking_metrics/pymot/__init__.py#L591-L610
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/constants/constants.py
python
lambda2nu
(lambda_)
return _np.asanyarray(c) / lambda_
Convert wavelength to optical frequency Parameters ---------- lambda_ : array_like Wavelength(s) to be converted. Returns ------- nu : float or array of floats Equivalent optical frequency. Notes ----- Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the (vacuum) speed of light in meters/second. Examples -------- >>> from scipy.constants import lambda2nu, speed_of_light >>> lambda2nu(np.array((1, speed_of_light))) array([ 2.99792458e+08, 1.00000000e+00])
Convert wavelength to optical frequency
[ "Convert", "wavelength", "to", "optical", "frequency" ]
def lambda2nu(lambda_): """ Convert wavelength to optical frequency Parameters ---------- lambda_ : array_like Wavelength(s) to be converted. Returns ------- nu : float or array of floats Equivalent optical frequency. Notes ----- Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the (vacuum) speed of light in meters/second. Examples -------- >>> from scipy.constants import lambda2nu, speed_of_light >>> lambda2nu(np.array((1, speed_of_light))) array([ 2.99792458e+08, 1.00000000e+00]) """ return _np.asanyarray(c) / lambda_
[ "def", "lambda2nu", "(", "lambda_", ")", ":", "return", "_np", ".", "asanyarray", "(", "c", ")", "/", "lambda_" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/constants/constants.py#L466-L492
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/code.py
python
InteractiveConsole.push
(self, line)
return more
Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()).
Push a line to the interpreter.
[ "Push", "a", "line", "to", "the", "interpreter", "." ]
def push(self, line): """Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()). """ self.buffer.append(line) source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() return more
[ "def", "push", "(", "self", ",", "line", ")", ":", "self", ".", "buffer", ".", "append", "(", "line", ")", "source", "=", "\"\\n\"", ".", "join", "(", "self", ".", "buffer", ")", "more", "=", "self", ".", "runsource", "(", "source", ",", "self", ".", "filename", ")", "if", "not", "more", ":", "self", ".", "resetbuffer", "(", ")", "return", "more" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/code.py#L242-L261
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/service_reflection.py
python
_ServiceBuilder._CallMethod
(self, srvc, method_descriptor, rpc_controller, request, callback)
return method(rpc_controller, request, callback)
Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method's execution. request: Request protocol message. callback: A callback to invoke after the method has completed.
Calls the method described by a given method descriptor.
[ "Calls", "the", "method", "described", "by", "a", "given", "method", "descriptor", "." ]
def _CallMethod(self, srvc, method_descriptor, rpc_controller, request, callback): """Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method's execution. request: Request protocol message. callback: A callback to invoke after the method has completed. """ if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'CallMethod() given method descriptor for wrong service type.') method = getattr(srvc, method_descriptor.name) return method(rpc_controller, request, callback)
[ "def", "_CallMethod", "(", "self", ",", "srvc", ",", "method_descriptor", ",", "rpc_controller", ",", "request", ",", "callback", ")", ":", "if", "method_descriptor", ".", "containing_service", "!=", "self", ".", "descriptor", ":", "raise", "RuntimeError", "(", "'CallMethod() given method descriptor for wrong service type.'", ")", "method", "=", "getattr", "(", "srvc", ",", "method_descriptor", ".", "name", ")", "return", "method", "(", "rpc_controller", ",", "request", ",", "callback", ")" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/service_reflection.py#L156-L171
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ContextHelp.__init__
(self, *args, **kwargs)
__init__(self, Window window=None, bool doNow=True) -> ContextHelp Constructs a context help object, calling BeginContextHelp if doNow is true (the default). If window is None, the top window is used.
__init__(self, Window window=None, bool doNow=True) -> ContextHelp
[ "__init__", "(", "self", "Window", "window", "=", "None", "bool", "doNow", "=", "True", ")", "-", ">", "ContextHelp" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window window=None, bool doNow=True) -> ContextHelp Constructs a context help object, calling BeginContextHelp if doNow is true (the default). If window is None, the top window is used. """ _controls_.ContextHelp_swiginit(self,_controls_.new_ContextHelp(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "ContextHelp_swiginit", "(", "self", ",", "_controls_", ".", "new_ContextHelp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L6135-L6144
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
PhotoImage.__init__
(self, name=None, cnf={}, master=None, **kw)
Create an image with NAME. Valid resource names: data, format, file, gamma, height, palette, width.
Create an image with NAME.
[ "Create", "an", "image", "with", "NAME", "." ]
def __init__(self, name=None, cnf={}, master=None, **kw): """Create an image with NAME. Valid resource names: data, format, file, gamma, height, palette, width.""" Image.__init__(self, 'photo', name, cnf, master, **kw)
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "cnf", "=", "{", "}", ",", "master", "=", "None", ",", "*", "*", "kw", ")", ":", "Image", ".", "__init__", "(", "self", ",", "'photo'", ",", "name", ",", "cnf", ",", "master", ",", "*", "*", "kw", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3301-L3306
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/jormungandr/jormungandr/authentication.py
python
cache_get_user
(token)
return user
We allow this method to be cached even if it depends on the current time because we assume the cache time is small and the error can be tolerated.
We allow this method to be cached even if it depends on the current time because we assume the cache time is small and the error can be tolerated.
[ "We", "allow", "this", "method", "to", "be", "cached", "even", "if", "it", "depends", "on", "the", "current", "time", "because", "we", "assume", "the", "cache", "time", "is", "small", "and", "the", "error", "can", "be", "tolerated", "." ]
def cache_get_user(token): """ We allow this method to be cached even if it depends on the current time because we assume the cache time is small and the error can be tolerated. """ if not can_connect_to_database(): return None try: user = User.get_from_token(token, datetime.datetime.now()) except Exception as e: logging.getLogger(__name__).error('No access to table User (error: {})'.format(e)) g.can_connect_to_database = False return None return user
[ "def", "cache_get_user", "(", "token", ")", ":", "if", "not", "can_connect_to_database", "(", ")", ":", "return", "None", "try", ":", "user", "=", "User", ".", "get_from_token", "(", "token", ",", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "except", "Exception", "as", "e", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "error", "(", "'No access to table User (error: {})'", ".", "format", "(", "e", ")", ")", "g", ".", "can_connect_to_database", "=", "False", "return", "None", "return", "user" ]
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/authentication.py#L177-L191
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookies.py
python
BaseCookie.__setitem__
(self, key, value)
Dictionary style assignment.
Dictionary style assignment.
[ "Dictionary", "style", "assignment", "." ]
def __setitem__(self, key, value): """Dictionary style assignment.""" if isinstance(value, Morsel): # allow assignment of constructed Morsels (e.g. for pickling) dict.__setitem__(self, key, value) else: rval, cval = self.value_encode(value) self.__set(key, rval, cval)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Morsel", ")", ":", "# allow assignment of constructed Morsels (e.g. for pickling)", "dict", ".", "__setitem__", "(", "self", ",", "key", ",", "value", ")", "else", ":", "rval", ",", "cval", "=", "self", ".", "value_encode", "(", "value", ")", "self", ".", "__set", "(", "key", ",", "rval", ",", "cval", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookies.py#L488-L495
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Warnings.py
python
process_warn_strings
(arguments)
Process string specifications of enabling/disabling warnings, as passed to the --warn option or the SetOption('warn') function. An argument to this option should be of the form <warning-class> or no-<warning-class>. The warning class is munged in order to get an actual class name from the classes above, which we need to pass to the {enable,disable}WarningClass() functions. The supplied <warning-class> is split on hyphens, each element is capitalized, then smushed back together. Then the string "Warning" is appended to get the class name. For example, 'deprecated' will enable the DeprecatedWarning class. 'no-dependency' will disable the DependencyWarning class. As a special case, --warn=all and --warn=no-all will enable or disable (respectively) the base Warning class of all warnings.
Process string specifications of enabling/disabling warnings, as passed to the --warn option or the SetOption('warn') function.
[ "Process", "string", "specifications", "of", "enabling", "/", "disabling", "warnings", "as", "passed", "to", "the", "--", "warn", "option", "or", "the", "SetOption", "(", "warn", ")", "function", "." ]
def process_warn_strings(arguments): """Process string specifications of enabling/disabling warnings, as passed to the --warn option or the SetOption('warn') function. An argument to this option should be of the form <warning-class> or no-<warning-class>. The warning class is munged in order to get an actual class name from the classes above, which we need to pass to the {enable,disable}WarningClass() functions. The supplied <warning-class> is split on hyphens, each element is capitalized, then smushed back together. Then the string "Warning" is appended to get the class name. For example, 'deprecated' will enable the DeprecatedWarning class. 'no-dependency' will disable the DependencyWarning class. As a special case, --warn=all and --warn=no-all will enable or disable (respectively) the base Warning class of all warnings. """ def _capitalize(s): if s[:5] == "scons": return "SCons" + s[5:] else: return s.capitalize() for arg in arguments: elems = arg.lower().split('-') enable = 1 if elems[0] == 'no': enable = 0 del elems[0] if len(elems) == 1 and elems[0] == 'all': class_name = "Warning" else: class_name = ''.join(map(_capitalize, elems)) + "Warning" try: clazz = globals()[class_name] except KeyError: sys.stderr.write("No warning type: '%s'\n" % arg) else: if enable: enableWarningClass(clazz) elif issubclass(clazz, MandatoryDeprecatedWarning): fmt = "Can not disable mandataory warning: '%s'\n" sys.stderr.write(fmt % arg) else: suppressWarningClass(clazz)
[ "def", "process_warn_strings", "(", "arguments", ")", ":", "def", "_capitalize", "(", "s", ")", ":", "if", "s", "[", ":", "5", "]", "==", "\"scons\"", ":", "return", "\"SCons\"", "+", "s", "[", "5", ":", "]", "else", ":", "return", "s", ".", "capitalize", "(", ")", "for", "arg", "in", "arguments", ":", "elems", "=", "arg", ".", "lower", "(", ")", ".", "split", "(", "'-'", ")", "enable", "=", "1", "if", "elems", "[", "0", "]", "==", "'no'", ":", "enable", "=", "0", "del", "elems", "[", "0", "]", "if", "len", "(", "elems", ")", "==", "1", "and", "elems", "[", "0", "]", "==", "'all'", ":", "class_name", "=", "\"Warning\"", "else", ":", "class_name", "=", "''", ".", "join", "(", "map", "(", "_capitalize", ",", "elems", ")", ")", "+", "\"Warning\"", "try", ":", "clazz", "=", "globals", "(", ")", "[", "class_name", "]", "except", "KeyError", ":", "sys", ".", "stderr", ".", "write", "(", "\"No warning type: '%s'\\n\"", "%", "arg", ")", "else", ":", "if", "enable", ":", "enableWarningClass", "(", "clazz", ")", "elif", "issubclass", "(", "clazz", ",", "MandatoryDeprecatedWarning", ")", ":", "fmt", "=", "\"Can not disable mandataory warning: '%s'\\n\"", "sys", ".", "stderr", ".", "write", "(", "fmt", "%", "arg", ")", "else", ":", "suppressWarningClass", "(", "clazz", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Warnings.py#L198-L248
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_schema_compiler/cpp_type_generator.py
python
CppTypeGenerator.GenerateForwardDeclarations
(self)
return c
Returns the forward declarations for self._default_namespace.
Returns the forward declarations for self._default_namespace.
[ "Returns", "the", "forward", "declarations", "for", "self", ".", "_default_namespace", "." ]
def GenerateForwardDeclarations(self): """Returns the forward declarations for self._default_namespace. """ c = Code() for namespace, deps in self._NamespaceTypeDependencies().iteritems(): filtered_deps = [ dep for dep in deps # Add more ways to forward declare things as necessary. if (not dep.hard and dep.type_.property_type in (PropertyType.CHOICES, PropertyType.OBJECT))] if not filtered_deps: continue cpp_namespace = cpp_util.GetCppNamespace( namespace.environment.namespace_pattern, namespace.unix_name) c.Concat(cpp_util.OpenNamespace(cpp_namespace)) for dep in filtered_deps: c.Append('struct %s;' % dep.type_.name) c.Concat(cpp_util.CloseNamespace(cpp_namespace)) return c
[ "def", "GenerateForwardDeclarations", "(", "self", ")", ":", "c", "=", "Code", "(", ")", "for", "namespace", ",", "deps", "in", "self", ".", "_NamespaceTypeDependencies", "(", ")", ".", "iteritems", "(", ")", ":", "filtered_deps", "=", "[", "dep", "for", "dep", "in", "deps", "# Add more ways to forward declare things as necessary.", "if", "(", "not", "dep", ".", "hard", "and", "dep", ".", "type_", ".", "property_type", "in", "(", "PropertyType", ".", "CHOICES", ",", "PropertyType", ".", "OBJECT", ")", ")", "]", "if", "not", "filtered_deps", ":", "continue", "cpp_namespace", "=", "cpp_util", ".", "GetCppNamespace", "(", "namespace", ".", "environment", ".", "namespace_pattern", ",", "namespace", ".", "unix_name", ")", "c", ".", "Concat", "(", "cpp_util", ".", "OpenNamespace", "(", "cpp_namespace", ")", ")", "for", "dep", "in", "filtered_deps", ":", "c", ".", "Append", "(", "'struct %s;'", "%", "dep", ".", "type_", ".", "name", ")", "c", ".", "Concat", "(", "cpp_util", ".", "CloseNamespace", "(", "cpp_namespace", ")", ")", "return", "c" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/cpp_type_generator.py#L138-L159
strukturag/libheif
0082fea96ee70a20c8906a0373bedec0c01777bc
scripts/cpplint.py
python
NestingState.Update
(self, filename, clean_lines, linenum, error)
Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Update nesting state with current line.
[ "Update", "nesting", "state", "with", "current", "line", "." ]
def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remember top of the previous nesting stack. # # The stack is always pushed/popped and not modified in place, so # we can just do a shallow copy instead of copy.deepcopy. Using # deepcopy would slow down cpplint by ~28%. if self.stack: self.previous_stack_top = self.stack[-1] else: self.previous_stack_top = None # Update pp_stack self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; class_decl_match = Match( r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?' r'(class|struct)\s+(?:[A-Z0-9_]+\s+)*(\w+(?:::\w+)*))' r'(.*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): # We do not want to accept classes that are actually template arguments: # template <class Ignore1, # class Ignore2 = Default<Args>, # template <Args> class Ignore3> # void Function() {}; # # To avoid template argument cases, we scan forward and look for # an unmatched '>'. If we see one, assume we are inside a # template argument list. end_declaration = len(class_decl_match.group(1)) if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): self.stack.append(_ClassInfo( class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(4) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True elif Match(r'^extern\s*"[^"]*"\s*\{', line): self.stack.append(_ExternCInfo(linenum)) else: self.stack.append(_BlockInfo(linenum, True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2)
[ "def", "Update", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remember top of the previous nesting stack.", "#", "# The stack is always pushed/popped and not modified in place, so", "# we can just do a shallow copy instead of copy.deepcopy. Using", "# deepcopy would slow down cpplint by ~28%.", "if", "self", ".", "stack", ":", "self", ".", "previous_stack_top", "=", "self", ".", "stack", "[", "-", "1", "]", "else", ":", "self", ".", "previous_stack_top", "=", "None", "# Update pp_stack", "self", ".", "UpdatePreprocessor", "(", "line", ")", "# Count parentheses. This is to avoid adding struct arguments to", "# the nesting stack.", "if", "self", ".", "stack", ":", "inner_block", "=", "self", ".", "stack", "[", "-", "1", "]", "depth_change", "=", "line", ".", "count", "(", "'('", ")", "-", "line", ".", "count", "(", "')'", ")", "inner_block", ".", "open_parentheses", "+=", "depth_change", "# Also check if we are starting or ending an inline assembly block.", "if", "inner_block", ".", "inline_asm", "in", "(", "_NO_ASM", ",", "_END_ASM", ")", ":", "if", "(", "depth_change", "!=", "0", "and", "inner_block", ".", "open_parentheses", "==", "1", "and", "_MATCH_ASM", ".", "match", "(", "line", ")", ")", ":", "# Enter assembly block", "inner_block", ".", "inline_asm", "=", "_INSIDE_ASM", "else", ":", "# Not entering assembly block. If previous line was _END_ASM,", "# we will now shift to _NO_ASM state.", "inner_block", ".", "inline_asm", "=", "_NO_ASM", "elif", "(", "inner_block", ".", "inline_asm", "==", "_INSIDE_ASM", "and", "inner_block", ".", "open_parentheses", "==", "0", ")", ":", "# Exit assembly block", "inner_block", ".", "inline_asm", "=", "_END_ASM", "# Consume namespace declaration at the beginning of the line. Do", "# this in a loop so that we catch same line declarations like this:", "# namespace proto2 { namespace bridge { class MessageSet; } }", "while", "True", ":", "# Match start of namespace. The \"\\b\\s*\" below catches namespace", "# declarations even if it weren't followed by a whitespace, this", "# is so that we don't confuse our namespace checker. The", "# missing spaces will be flagged by CheckSpacing.", "namespace_decl_match", "=", "Match", "(", "r'^\\s*namespace\\b\\s*([:\\w]+)?(.*)$'", ",", "line", ")", "if", "not", "namespace_decl_match", ":", "break", "new_namespace", "=", "_NamespaceInfo", "(", "namespace_decl_match", ".", "group", "(", "1", ")", ",", "linenum", ")", "self", ".", "stack", ".", "append", "(", "new_namespace", ")", "line", "=", "namespace_decl_match", ".", "group", "(", "2", ")", "if", "line", ".", "find", "(", "'{'", ")", "!=", "-", "1", ":", "new_namespace", ".", "seen_open_brace", "=", "True", "line", "=", "line", "[", "line", ".", "find", "(", "'{'", ")", "+", "1", ":", "]", "# Look for a class declaration in whatever is left of the line", "# after parsing namespaces. The regexp accounts for decorated classes", "# such as in:", "# class LOCKABLE API Object {", "# };", "class_decl_match", "=", "Match", "(", "r'^(\\s*(?:template\\s*<[\\w\\s<>,:]*>\\s*)?'", "r'(class|struct)\\s+(?:[A-Z0-9_]+\\s+)*(\\w+(?:::\\w+)*))'", "r'(.*)$'", ",", "line", ")", "if", "(", "class_decl_match", "and", "(", "not", "self", ".", "stack", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "open_parentheses", "==", "0", ")", ")", ":", "# We do not want to accept classes that are actually template arguments:", "# template <class Ignore1,", "# class Ignore2 = Default<Args>,", "# template <Args> class Ignore3>", "# void Function() {};", "#", "# To avoid template argument cases, we scan forward and look for", "# an unmatched '>'. If we see one, assume we are inside a", "# template argument list.", "end_declaration", "=", "len", "(", "class_decl_match", ".", "group", "(", "1", ")", ")", "if", "not", "self", ".", "InTemplateArgumentList", "(", "clean_lines", ",", "linenum", ",", "end_declaration", ")", ":", "self", ".", "stack", ".", "append", "(", "_ClassInfo", "(", "class_decl_match", ".", "group", "(", "3", ")", ",", "class_decl_match", ".", "group", "(", "2", ")", ",", "clean_lines", ",", "linenum", ")", ")", "line", "=", "class_decl_match", ".", "group", "(", "4", ")", "# If we have not yet seen the opening brace for the innermost block,", "# run checks here.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "CheckBegin", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "# Update access control if we are inside a class/struct", "if", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_ClassInfo", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "-", "1", "]", "access_match", "=", "Match", "(", "r'^(.*)\\b(public|private|protected|signals)(\\s+(?:slots\\s*)?)?'", "r':(?:[^:]|$)'", ",", "line", ")", "if", "access_match", ":", "classinfo", ".", "access", "=", "access_match", ".", "group", "(", "2", ")", "# Check that access keywords are indented +1 space. Skip this", "# check if the keywords are not preceded by whitespaces.", "indent", "=", "access_match", ".", "group", "(", "1", ")", "if", "(", "len", "(", "indent", ")", "!=", "classinfo", ".", "class_indent", "+", "1", "and", "Match", "(", "r'^\\s*$'", ",", "indent", ")", ")", ":", "if", "classinfo", ".", "is_struct", ":", "parent", "=", "'struct '", "+", "classinfo", ".", "name", "else", ":", "parent", "=", "'class '", "+", "classinfo", ".", "name", "slots", "=", "''", "if", "access_match", ".", "group", "(", "3", ")", ":", "slots", "=", "access_match", ".", "group", "(", "3", ")", "error", "(", "filename", ",", "linenum", ",", "'whitespace/indent'", ",", "3", ",", "'%s%s: should be indented +1 space inside %s'", "%", "(", "access_match", ".", "group", "(", "2", ")", ",", "slots", ",", "parent", ")", ")", "# Consume braces or semicolons from what's left of the line", "while", "True", ":", "# Match first brace, semicolon, or closed parenthesis.", "matched", "=", "Match", "(", "r'^[^{;)}]*([{;)}])(.*)$'", ",", "line", ")", "if", "not", "matched", ":", "break", "token", "=", "matched", ".", "group", "(", "1", ")", "if", "token", "==", "'{'", ":", "# If namespace or class hasn't seen a opening brace yet, mark", "# namespace/class head as complete. Push a new block onto the", "# stack otherwise.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace", "=", "True", "elif", "Match", "(", "r'^extern\\s*\"[^\"]*\"\\s*\\{'", ",", "line", ")", ":", "self", ".", "stack", ".", "append", "(", "_ExternCInfo", "(", "linenum", ")", ")", "else", ":", "self", ".", "stack", ".", "append", "(", "_BlockInfo", "(", "linenum", ",", "True", ")", ")", "if", "_MATCH_ASM", ".", "match", "(", "line", ")", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "inline_asm", "=", "_BLOCK_ASM", "elif", "token", "==", "';'", "or", "token", "==", "')'", ":", "# If we haven't seen an opening brace yet, but we already saw", "# a semicolon, this is probably a forward declaration. Pop", "# the stack for these.", "#", "# Similarly, if we haven't seen an opening brace yet, but we", "# already saw a closing parenthesis, then these are probably", "# function arguments with extra \"class\" or \"struct\" keywords.", "# Also pop these stack for these.", "if", "not", "self", ".", "SeenOpenBrace", "(", ")", ":", "self", ".", "stack", ".", "pop", "(", ")", "else", ":", "# token == '}'", "# Perform end of block checks and pop the stack.", "if", "self", ".", "stack", ":", "self", ".", "stack", "[", "-", "1", "]", ".", "CheckEnd", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", "self", ".", "stack", ".", "pop", "(", ")", "line", "=", "matched", ".", "group", "(", "2", ")" ]
https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L2461-L2623
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
scripts/cpp_lint.py
python
CheckCaffeRandom
(filename, clean_lines, linenum, error)
Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for calls to C random functions (rand, rand_r, random, ...).
[ "Checks", "for", "calls", "to", "C", "random", "functions", "(", "rand", "rand_r", "random", "...", ")", "." ]
def CheckCaffeRandom(filename, clean_lines, linenum, error): """Checks for calls to C random functions (rand, rand_r, random, ...). Caffe code should (almost) always use the caffe_rng_* functions rather than these, as the internal state of these C functions is independent of the native Caffe RNG system which should produce deterministic results for a fixed Caffe seed set using Caffe::set_random_seed(...). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for function in c_random_function_list: ix = line.find(function) # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and line[ix - 1] not in ('_', '.', '>'))): error(filename, linenum, 'caffe/random_fn', 2, 'Use caffe_rng_rand() (or other caffe_rng_* function) instead of ' + function + ') to ensure results are deterministic for a fixed Caffe seed.')
[ "def", "CheckCaffeRandom", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "for", "function", "in", "c_random_function_list", ":", "ix", "=", "line", ".", "find", "(", "function", ")", "# Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison", "if", "ix", ">=", "0", "and", "(", "ix", "==", "0", "or", "(", "not", "line", "[", "ix", "-", "1", "]", ".", "isalnum", "(", ")", "and", "line", "[", "ix", "-", "1", "]", "not", "in", "(", "'_'", ",", "'.'", ",", "'>'", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'caffe/random_fn'", ",", "2", ",", "'Use caffe_rng_rand() (or other caffe_rng_* function) instead of '", "+", "function", "+", "') to ensure results are deterministic for a fixed Caffe seed.'", ")" ]
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L1640-L1663
limbo018/DREAMPlace
146c3b9fd003d1acd52c96d9fd02e3f0a05154e4
dreamplace/ops/dct/discrete_spectral_transform.py
python
dst
(x, expkp1=None)
return y
Batch Discrete Sine Transformation without normalization to coefficients. Compute y_u = \sum_i x_i sin(pi*(2i+1)*(u+1)/(2N)), Impelements the 2N padding trick to solve DCT with FFT in the following link, https://dsp.stackexchange.com/questions/2807/fast-cosine-transform-via-fft 1. Pad x by zeros 2. Perform FFT 3. Multiply by 2*exp(-1j*pi*u/(2N)) 4. Extract the real part
Batch Discrete Sine Transformation without normalization to coefficients. Compute y_u = \sum_i x_i sin(pi*(2i+1)*(u+1)/(2N)), Impelements the 2N padding trick to solve DCT with FFT in the following link, https://dsp.stackexchange.com/questions/2807/fast-cosine-transform-via-fft
[ "Batch", "Discrete", "Sine", "Transformation", "without", "normalization", "to", "coefficients", ".", "Compute", "y_u", "=", "\\", "sum_i", "x_i", "sin", "(", "pi", "*", "(", "2i", "+", "1", ")", "*", "(", "u", "+", "1", ")", "/", "(", "2N", "))", "Impelements", "the", "2N", "padding", "trick", "to", "solve", "DCT", "with", "FFT", "in", "the", "following", "link", "https", ":", "//", "dsp", ".", "stackexchange", ".", "com", "/", "questions", "/", "2807", "/", "fast", "-", "cosine", "-", "transform", "-", "via", "-", "fft" ]
def dst(x, expkp1=None): """ Batch Discrete Sine Transformation without normalization to coefficients. Compute y_u = \sum_i x_i sin(pi*(2i+1)*(u+1)/(2N)), Impelements the 2N padding trick to solve DCT with FFT in the following link, https://dsp.stackexchange.com/questions/2807/fast-cosine-transform-via-fft 1. Pad x by zeros 2. Perform FFT 3. Multiply by 2*exp(-1j*pi*u/(2N)) 4. Extract the real part """ # last dimension N = x.size(-1) # pad last dimension x_pad = F.pad(x, (0, N), 'constant', 0) # the last dimension here becomes -2 because complex numbers introduce a new dimension y = torch_fft_api.rfft(x_pad, signal_ndim=1, normalized=False, onesided=True)[..., 1:N+1, :] if expkp1 is None: expkp1 = get_expkp1(N, dtype=x.dtype, device=x.device) # get imag part y = y[..., 1].mul(expkp1[:, 0]) - y[..., 0].mul(expkp1[:, 1]) return y
[ "def", "dst", "(", "x", ",", "expkp1", "=", "None", ")", ":", "# last dimension", "N", "=", "x", ".", "size", "(", "-", "1", ")", "# pad last dimension", "x_pad", "=", "F", ".", "pad", "(", "x", ",", "(", "0", ",", "N", ")", ",", "'constant'", ",", "0", ")", "# the last dimension here becomes -2 because complex numbers introduce a new dimension", "y", "=", "torch_fft_api", ".", "rfft", "(", "x_pad", ",", "signal_ndim", "=", "1", ",", "normalized", "=", "False", ",", "onesided", "=", "True", ")", "[", "...", ",", "1", ":", "N", "+", "1", ",", ":", "]", "if", "expkp1", "is", "None", ":", "expkp1", "=", "get_expkp1", "(", "N", ",", "dtype", "=", "x", ".", "dtype", ",", "device", "=", "x", ".", "device", ")", "# get imag part", "y", "=", "y", "[", "...", ",", "1", "]", ".", "mul", "(", "expkp1", "[", ":", ",", "0", "]", ")", "-", "y", "[", "...", ",", "0", "]", ".", "mul", "(", "expkp1", "[", ":", ",", "1", "]", ")", "return", "y" ]
https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/ops/dct/discrete_spectral_transform.py#L217-L242
BitcoinUnlimited/BitcoinUnlimited
05de381c02eb4bfca94957733acadfa217527f25
contrib/devtools/security-check.py
python
get_ELF_program_headers
(executable)
return headers
Return type and flags for ELF program headers
Return type and flags for ELF program headers
[ "Return", "type", "and", "flags", "for", "ELF", "program", "headers" ]
def get_ELF_program_headers(executable): '''Return type and flags for ELF program headers''' p = subprocess.Popen([READELF_CMD, '-l', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Error opening file') in_headers = False count = 0 headers = [] for line in stdout.split(b'\n'): if line.startswith(b'Program Headers:'): in_headers = True if line == b'': in_headers = False if in_headers: if count == 1: # header line ofs_typ = line.find(b'Type') ofs_offset = line.find(b'Offset') ofs_flags = line.find(b'Flg') ofs_align = line.find(b'Align') if ofs_typ == -1 or ofs_offset == -1 or ofs_flags == -1 or ofs_align == -1: raise ValueError('Cannot parse elfread -lW output') elif count > 1: typ = line[ofs_typ:ofs_offset].rstrip() flags = line[ofs_flags:ofs_align].rstrip() headers.append((typ, flags)) count += 1 return headers
[ "def", "get_ELF_program_headers", "(", "executable", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "READELF_CMD", ",", "'-l'", ",", "'-W'", ",", "executable", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", "(", "stdout", ",", "stderr", ")", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "raise", "IOError", "(", "'Error opening file'", ")", "in_headers", "=", "False", "count", "=", "0", "headers", "=", "[", "]", "for", "line", "in", "stdout", ".", "split", "(", "b'\\n'", ")", ":", "if", "line", ".", "startswith", "(", "b'Program Headers:'", ")", ":", "in_headers", "=", "True", "if", "line", "==", "b''", ":", "in_headers", "=", "False", "if", "in_headers", ":", "if", "count", "==", "1", ":", "# header line", "ofs_typ", "=", "line", ".", "find", "(", "b'Type'", ")", "ofs_offset", "=", "line", ".", "find", "(", "b'Offset'", ")", "ofs_flags", "=", "line", ".", "find", "(", "b'Flg'", ")", "ofs_align", "=", "line", ".", "find", "(", "b'Align'", ")", "if", "ofs_typ", "==", "-", "1", "or", "ofs_offset", "==", "-", "1", "or", "ofs_flags", "==", "-", "1", "or", "ofs_align", "==", "-", "1", ":", "raise", "ValueError", "(", "'Cannot parse elfread -lW output'", ")", "elif", "count", ">", "1", ":", "typ", "=", "line", "[", "ofs_typ", ":", "ofs_offset", "]", ".", "rstrip", "(", ")", "flags", "=", "line", "[", "ofs_flags", ":", "ofs_align", "]", ".", "rstrip", "(", ")", "headers", ".", "append", "(", "(", "typ", ",", "flags", ")", ")", "count", "+=", "1", "return", "headers" ]
https://github.com/BitcoinUnlimited/BitcoinUnlimited/blob/05de381c02eb4bfca94957733acadfa217527f25/contrib/devtools/security-check.py#L32-L59
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py
python
_nbits
(n, correction = { '0': 4, '1': 3, '2': 2, '3': 2, '4': 1, '5': 1, '6': 1, '7': 1, '8': 0, '9': 0, 'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0})
return 4*len(hex_n) - correction[hex_n[0]]
Number of bits in binary representation of the positive integer n, or 0 if n == 0.
Number of bits in binary representation of the positive integer n, or 0 if n == 0.
[ "Number", "of", "bits", "in", "binary", "representation", "of", "the", "positive", "integer", "n", "or", "0", "if", "n", "==", "0", "." ]
def _nbits(n, correction = { '0': 4, '1': 3, '2': 2, '3': 2, '4': 1, '5': 1, '6': 1, '7': 1, '8': 0, '9': 0, 'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0}): """Number of bits in binary representation of the positive integer n, or 0 if n == 0. """ if n < 0: raise ValueError("The argument to _nbits should be nonnegative.") hex_n = "%x" % n return 4*len(hex_n) - correction[hex_n[0]]
[ "def", "_nbits", "(", "n", ",", "correction", "=", "{", "'0'", ":", "4", ",", "'1'", ":", "3", ",", "'2'", ":", "2", ",", "'3'", ":", "2", ",", "'4'", ":", "1", ",", "'5'", ":", "1", ",", "'6'", ":", "1", ",", "'7'", ":", "1", ",", "'8'", ":", "0", ",", "'9'", ":", "0", ",", "'a'", ":", "0", ",", "'b'", ":", "0", ",", "'c'", ":", "0", ",", "'d'", ":", "0", ",", "'e'", ":", "0", ",", "'f'", ":", "0", "}", ")", ":", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "\"The argument to _nbits should be nonnegative.\"", ")", "hex_n", "=", "\"%x\"", "%", "n", "return", "4", "*", "len", "(", "hex_n", ")", "-", "correction", "[", "hex_n", "[", "0", "]", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L5481-L5492
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
doc/examples/5_misc/plot_1_dcem.py
python
DCEM1dModelling.response
(self, model)
return pg.cat(self.fDC_(model), self.fEM_(model))
Return concatenated response of DC and EM FOPs.
Return concatenated response of DC and EM FOPs.
[ "Return", "concatenated", "response", "of", "DC", "and", "EM", "FOPs", "." ]
def response(self, model): """Return concatenated response of DC and EM FOPs.""" return pg.cat(self.fDC_(model), self.fEM_(model))
[ "def", "response", "(", "self", ",", "model", ")", ":", "return", "pg", ".", "cat", "(", "self", ".", "fDC_", "(", "model", ")", ",", "self", ".", "fEM_", "(", "model", ")", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/doc/examples/5_misc/plot_1_dcem.py#L38-L40
NERSC/timemory
431912b360ff50d1a160d7826e2eea04fbd1037f
scripts/gprof2dot.py
python
Function.stripped_name
(self)
return name
Remove extraneous information from C++ demangled function names.
Remove extraneous information from C++ demangled function names.
[ "Remove", "extraneous", "information", "from", "C", "++", "demangled", "function", "names", "." ]
def stripped_name(self): """Remove extraneous information from C++ demangled function names.""" name = self.name # Strip function parameters from name by recursively removing paired parenthesis while True: name, n = self._parenthesis_re.subn('', name) if not n: break # Strip const qualifier name = self._const_re.sub('', name) # Strip template parameters from name by recursively removing paired angles while True: name, n = self._angles_re.subn('', name) if not n: break return name
[ "def", "stripped_name", "(", "self", ")", ":", "name", "=", "self", ".", "name", "# Strip function parameters from name by recursively removing paired parenthesis", "while", "True", ":", "name", ",", "n", "=", "self", ".", "_parenthesis_re", ".", "subn", "(", "''", ",", "name", ")", "if", "not", "n", ":", "break", "# Strip const qualifier", "name", "=", "self", ".", "_const_re", ".", "sub", "(", "''", ",", "name", ")", "# Strip template parameters from name by recursively removing paired angles", "while", "True", ":", "name", ",", "n", "=", "self", ".", "_angles_re", ".", "subn", "(", "''", ",", "name", ")", "if", "not", "n", ":", "break", "return", "name" ]
https://github.com/NERSC/timemory/blob/431912b360ff50d1a160d7826e2eea04fbd1037f/scripts/gprof2dot.py#L244-L264
gromacs/gromacs
7dec3a3f99993cf5687a122de3e12de31c21c399
docs/doxygen/doxygenxml.py
python
Compound.get_xml_path
(self)
return os.path.join(self._docset.get_xmlroot(), self.get_id() + '.xml')
Return path to the details XML file for this compound.
Return path to the details XML file for this compound.
[ "Return", "path", "to", "the", "details", "XML", "file", "for", "this", "compound", "." ]
def get_xml_path(self): """Return path to the details XML file for this compound.""" return os.path.join(self._docset.get_xmlroot(), self.get_id() + '.xml')
[ "def", "get_xml_path", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_docset", ".", "get_xmlroot", "(", ")", ",", "self", ".", "get_id", "(", ")", "+", "'.xml'", ")" ]
https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/docs/doxygen/doxygenxml.py#L606-L608
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/ndimage/_ni_support.py
python
_extend_mode_to_code
(mode)
Convert an extension mode to the corresponding integer code.
Convert an extension mode to the corresponding integer code.
[ "Convert", "an", "extension", "mode", "to", "the", "corresponding", "integer", "code", "." ]
def _extend_mode_to_code(mode): """Convert an extension mode to the corresponding integer code. """ if mode == 'nearest': return 0 elif mode == 'wrap': return 1 elif mode == 'reflect': return 2 elif mode == 'mirror': return 3 elif mode == 'constant': return 4 else: raise RuntimeError('boundary mode not supported')
[ "def", "_extend_mode_to_code", "(", "mode", ")", ":", "if", "mode", "==", "'nearest'", ":", "return", "0", "elif", "mode", "==", "'wrap'", ":", "return", "1", "elif", "mode", "==", "'reflect'", ":", "return", "2", "elif", "mode", "==", "'mirror'", ":", "return", "3", "elif", "mode", "==", "'constant'", ":", "return", "4", "else", ":", "raise", "RuntimeError", "(", "'boundary mode not supported'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/ndimage/_ni_support.py#L38-L52
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/summary/plugin_asset.py
python
PluginAsset.assets
(self)
Provide all of the assets contained by the PluginAsset instance. The assets method should return a dictionary structured as {asset_name: asset_contents}. asset_contents is a string. This method will be called by the tf.summary.FileWriter when it is time to write the assets out to disk.
Provide all of the assets contained by the PluginAsset instance.
[ "Provide", "all", "of", "the", "assets", "contained", "by", "the", "PluginAsset", "instance", "." ]
def assets(self): """Provide all of the assets contained by the PluginAsset instance. The assets method should return a dictionary structured as {asset_name: asset_contents}. asset_contents is a string. This method will be called by the tf.summary.FileWriter when it is time to write the assets out to disk. """ raise NotImplementedError()
[ "def", "assets", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/summary/plugin_asset.py#L132-L141
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/volumes/fs/async_cloner.py
python
Cloner.cancel_job
(self, volname, job)
override base class `cancel_job`. interpret @job as (clone, group) tuple.
override base class `cancel_job`. interpret
[ "override", "base", "class", "cancel_job", ".", "interpret" ]
def cancel_job(self, volname, job): """ override base class `cancel_job`. interpret @job as (clone, group) tuple. """ clonename = job[0] groupname = job[1] track_idx = None try: with open_volume(self.fs_client, volname) as fs_handle: with open_group(fs_handle, self.vc.volspec, groupname) as group: with open_subvol(self.fs_client.mgr, fs_handle, self.vc.volspec, group, clonename, SubvolumeOpType.CLONE_CANCEL) as clone_subvolume: status = clone_subvolume.status clone_state = SubvolumeStates.from_value(status['state']) if not self.is_clone_cancelable(clone_state): raise VolumeException(-errno.EINVAL, "cannot cancel -- clone finished (check clone status)") track_idx = self.get_clone_tracking_index(fs_handle, clone_subvolume) if not track_idx: log.warning("cannot lookup clone tracking index for {0}".format(clone_subvolume.base_path)) raise VolumeException(-errno.EINVAL, "error canceling clone") clone_job = (track_idx, clone_subvolume.base_path) jobs = [j[0] for j in self.jobs[volname]] with lock_timeout_log(self.lock): if SubvolumeOpSm.is_init_state(SubvolumeTypes.TYPE_CLONE, clone_state) and not clone_job in jobs: logging.debug("Cancelling pending job {0}".format(clone_job)) # clone has not started yet -- cancel right away. self._cancel_pending_clone(fs_handle, clone_subvolume, clonename, groupname, status, track_idx) return # cancelling an on-going clone would persist "canceled" state in subvolume metadata. # to persist the new state, async cloner accesses the volume in exclusive mode. # accessing the volume in exclusive mode here would lead to deadlock. assert track_idx is not None with lock_timeout_log(self.lock): with open_volume_lockless(self.fs_client, volname) as fs_handle: with open_group(fs_handle, self.vc.volspec, groupname) as group: with open_subvol(self.fs_client.mgr, fs_handle, self.vc.volspec, group, clonename, SubvolumeOpType.CLONE_CANCEL) as clone_subvolume: if not self._cancel_job(volname, (track_idx, clone_subvolume.base_path)): raise VolumeException(-errno.EINVAL, "cannot cancel -- clone finished (check clone status)") except (IndexException, MetadataMgrException) as e: log.error("error cancelling clone {0}: ({1})".format(job, e)) raise VolumeException(-errno.EINVAL, "error canceling clone")
[ "def", "cancel_job", "(", "self", ",", "volname", ",", "job", ")", ":", "clonename", "=", "job", "[", "0", "]", "groupname", "=", "job", "[", "1", "]", "track_idx", "=", "None", "try", ":", "with", "open_volume", "(", "self", ".", "fs_client", ",", "volname", ")", "as", "fs_handle", ":", "with", "open_group", "(", "fs_handle", ",", "self", ".", "vc", ".", "volspec", ",", "groupname", ")", "as", "group", ":", "with", "open_subvol", "(", "self", ".", "fs_client", ".", "mgr", ",", "fs_handle", ",", "self", ".", "vc", ".", "volspec", ",", "group", ",", "clonename", ",", "SubvolumeOpType", ".", "CLONE_CANCEL", ")", "as", "clone_subvolume", ":", "status", "=", "clone_subvolume", ".", "status", "clone_state", "=", "SubvolumeStates", ".", "from_value", "(", "status", "[", "'state'", "]", ")", "if", "not", "self", ".", "is_clone_cancelable", "(", "clone_state", ")", ":", "raise", "VolumeException", "(", "-", "errno", ".", "EINVAL", ",", "\"cannot cancel -- clone finished (check clone status)\"", ")", "track_idx", "=", "self", ".", "get_clone_tracking_index", "(", "fs_handle", ",", "clone_subvolume", ")", "if", "not", "track_idx", ":", "log", ".", "warning", "(", "\"cannot lookup clone tracking index for {0}\"", ".", "format", "(", "clone_subvolume", ".", "base_path", ")", ")", "raise", "VolumeException", "(", "-", "errno", ".", "EINVAL", ",", "\"error canceling clone\"", ")", "clone_job", "=", "(", "track_idx", ",", "clone_subvolume", ".", "base_path", ")", "jobs", "=", "[", "j", "[", "0", "]", "for", "j", "in", "self", ".", "jobs", "[", "volname", "]", "]", "with", "lock_timeout_log", "(", "self", ".", "lock", ")", ":", "if", "SubvolumeOpSm", ".", "is_init_state", "(", "SubvolumeTypes", ".", "TYPE_CLONE", ",", "clone_state", ")", "and", "not", "clone_job", "in", "jobs", ":", "logging", ".", "debug", "(", "\"Cancelling pending job {0}\"", ".", "format", "(", "clone_job", ")", ")", "# clone has not started yet -- cancel right away.", "self", ".", "_cancel_pending_clone", "(", "fs_handle", ",", "clone_subvolume", ",", "clonename", ",", "groupname", ",", "status", ",", "track_idx", ")", "return", "# cancelling an on-going clone would persist \"canceled\" state in subvolume metadata.", "# to persist the new state, async cloner accesses the volume in exclusive mode.", "# accessing the volume in exclusive mode here would lead to deadlock.", "assert", "track_idx", "is", "not", "None", "with", "lock_timeout_log", "(", "self", ".", "lock", ")", ":", "with", "open_volume_lockless", "(", "self", ".", "fs_client", ",", "volname", ")", "as", "fs_handle", ":", "with", "open_group", "(", "fs_handle", ",", "self", ".", "vc", ".", "volspec", ",", "groupname", ")", "as", "group", ":", "with", "open_subvol", "(", "self", ".", "fs_client", ".", "mgr", ",", "fs_handle", ",", "self", ".", "vc", ".", "volspec", ",", "group", ",", "clonename", ",", "SubvolumeOpType", ".", "CLONE_CANCEL", ")", "as", "clone_subvolume", ":", "if", "not", "self", ".", "_cancel_job", "(", "volname", ",", "(", "track_idx", ",", "clone_subvolume", ".", "base_path", ")", ")", ":", "raise", "VolumeException", "(", "-", "errno", ".", "EINVAL", ",", "\"cannot cancel -- clone finished (check clone status)\"", ")", "except", "(", "IndexException", ",", "MetadataMgrException", ")", "as", "e", ":", "log", ".", "error", "(", "\"error cancelling clone {0}: ({1})\"", ".", "format", "(", "job", ",", "e", ")", ")", "raise", "VolumeException", "(", "-", "errno", ".", "EINVAL", ",", "\"error canceling clone\"", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/volumes/fs/async_cloner.py#L337-L377
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py
python
_call_with_frames_removed
(f, *args, **kwds)
return f(*args, **kwds)
remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceback (e.g. when executing module code)
remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function
[ "remove_importlib_frames", "in", "import", ".", "c", "will", "always", "remove", "sequences", "of", "importlib", "frames", "that", "end", "with", "a", "call", "to", "this", "function" ]
def _call_with_frames_removed(f, *args, **kwds): """remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceback (e.g. when executing module code) """ return f(*args, **kwds)
[ "def", "_call_with_frames_removed", "(", "f", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwds", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py#L211-L219
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/feature_column/feature_column.py
python
_transform_features
(features, feature_columns)
return outputs
Returns transformed features based on features columns passed in. Please note that most probably you would not need to use this function. Please check `input_layer` and `linear_model` to see whether they will satisfy your use case or not. Example: ```python # Define features and transformations crosses_a_x_b = crossed_column( columns=["sparse_feature_a", "sparse_feature_b"], hash_bucket_size=10000) price_buckets = bucketized_column( source_column=numeric_column("price"), boundaries=[...]) columns = [crosses_a_x_b, price_buckets] features = tf.parse_example(..., features=make_parse_example_spec(columns)) transformed = transform_features(features=features, feature_columns=columns) assertCountEqual(columns, transformed.keys()) ``` Args: features: A mapping from key to tensors. `_FeatureColumn`s look up via these keys. For example `numeric_column('price')` will look at 'price' key in this dict. Values can be a `SparseTensor` or a `Tensor` depends on corresponding `_FeatureColumn`. feature_columns: An iterable containing all the `_FeatureColumn`s. Returns: A `dict` mapping `_FeatureColumn` to `Tensor` and `SparseTensor` values.
Returns transformed features based on features columns passed in.
[ "Returns", "transformed", "features", "based", "on", "features", "columns", "passed", "in", "." ]
def _transform_features(features, feature_columns): """Returns transformed features based on features columns passed in. Please note that most probably you would not need to use this function. Please check `input_layer` and `linear_model` to see whether they will satisfy your use case or not. Example: ```python # Define features and transformations crosses_a_x_b = crossed_column( columns=["sparse_feature_a", "sparse_feature_b"], hash_bucket_size=10000) price_buckets = bucketized_column( source_column=numeric_column("price"), boundaries=[...]) columns = [crosses_a_x_b, price_buckets] features = tf.parse_example(..., features=make_parse_example_spec(columns)) transformed = transform_features(features=features, feature_columns=columns) assertCountEqual(columns, transformed.keys()) ``` Args: features: A mapping from key to tensors. `_FeatureColumn`s look up via these keys. For example `numeric_column('price')` will look at 'price' key in this dict. Values can be a `SparseTensor` or a `Tensor` depends on corresponding `_FeatureColumn`. feature_columns: An iterable containing all the `_FeatureColumn`s. Returns: A `dict` mapping `_FeatureColumn` to `Tensor` and `SparseTensor` values. """ feature_columns = _clean_feature_columns(feature_columns) outputs = {} with ops.name_scope( None, default_name='transform_features', values=features.values()): builder = _LazyBuilder(features) for column in sorted(feature_columns, key=lambda x: x.name): with ops.name_scope(None, default_name=column.name): outputs[column] = builder.get(column) return outputs
[ "def", "_transform_features", "(", "features", ",", "feature_columns", ")", ":", "feature_columns", "=", "_clean_feature_columns", "(", "feature_columns", ")", "outputs", "=", "{", "}", "with", "ops", ".", "name_scope", "(", "None", ",", "default_name", "=", "'transform_features'", ",", "values", "=", "features", ".", "values", "(", ")", ")", ":", "builder", "=", "_LazyBuilder", "(", "features", ")", "for", "column", "in", "sorted", "(", "feature_columns", ",", "key", "=", "lambda", "x", ":", "x", ".", "name", ")", ":", "with", "ops", ".", "name_scope", "(", "None", ",", "default_name", "=", "column", ".", "name", ")", ":", "outputs", "[", "column", "]", "=", "builder", ".", "get", "(", "column", ")", "return", "outputs" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/feature_column/feature_column.py#L379-L420
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/isis_reduction_steps.py
python
ConvertToQISIS._set_up_diameter
(self, h, w)
return 2 * math.sqrt((h * h + w * w) / 6)
Prepare the diameter parameter. If there are corresponding H and W values, then use them instead. Richard provided the formula: A = 2*sqrt((H^2 + W^2)/6) @param h: the height @param w: the width @returns the new diameter
Prepare the diameter parameter. If there are corresponding H and W values, then use them instead. Richard provided the formula: A = 2*sqrt((H^2 + W^2)/6)
[ "Prepare", "the", "diameter", "parameter", ".", "If", "there", "are", "corresponding", "H", "and", "W", "values", "then", "use", "them", "instead", ".", "Richard", "provided", "the", "formula", ":", "A", "=", "2", "*", "sqrt", "((", "H^2", "+", "W^2", ")", "/", "6", ")" ]
def _set_up_diameter(self, h, w): ''' Prepare the diameter parameter. If there are corresponding H and W values, then use them instead. Richard provided the formula: A = 2*sqrt((H^2 + W^2)/6) @param h: the height @param w: the width @returns the new diameter ''' return 2 * math.sqrt((h * h + w * w) / 6)
[ "def", "_set_up_diameter", "(", "self", ",", "h", ",", "w", ")", ":", "return", "2", "*", "math", ".", "sqrt", "(", "(", "h", "*", "h", "+", "w", "*", "w", ")", "/", "6", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_reduction_steps.py#L3003-L3011
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Modules/Scripted/VectorToScalarVolume/VectorToScalarVolume.py
python
MyObjectsBlockSignals
(*qobjects)
Context manager to block/reset signals of any number of input qobjects. Usage: with MyObjectsBlockSignals(self.aComboBox, self.otherComboBox):
Context manager to block/reset signals of any number of input qobjects. Usage: with MyObjectsBlockSignals(self.aComboBox, self.otherComboBox):
[ "Context", "manager", "to", "block", "/", "reset", "signals", "of", "any", "number", "of", "input", "qobjects", ".", "Usage", ":", "with", "MyObjectsBlockSignals", "(", "self", ".", "aComboBox", "self", ".", "otherComboBox", ")", ":" ]
def MyObjectsBlockSignals(*qobjects): """ Context manager to block/reset signals of any number of input qobjects. Usage: with MyObjectsBlockSignals(self.aComboBox, self.otherComboBox): """ # TODO: Move it to slicer.utils and delete it here. previousValues = list() for qobject in qobjects: # blockedSignal returns the previous value of signalsBlocked() previousValues.append(qobject.blockSignals(True)) yield for (qobject, previousValue) in zip(qobjects, previousValues): qobject.blockSignals(previousValue)
[ "def", "MyObjectsBlockSignals", "(", "*", "qobjects", ")", ":", "# TODO: Move it to slicer.utils and delete it here.", "previousValues", "=", "list", "(", ")", "for", "qobject", "in", "qobjects", ":", "# blockedSignal returns the previous value of signalsBlocked()", "previousValues", ".", "append", "(", "qobject", ".", "blockSignals", "(", "True", ")", ")", "yield", "for", "(", "qobject", ",", "previousValue", ")", "in", "zip", "(", "qobjects", ",", "previousValues", ")", ":", "qobject", ".", "blockSignals", "(", "previousValue", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Modules/Scripted/VectorToScalarVolume/VectorToScalarVolume.py#L22-L35
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibar.py
python
AuiToolBar.SetAuiManager
(self, auiManager)
Sets the :class:`~lib.agw.aui.framemanager.AuiManager` which manages the toolbar.
Sets the :class:`~lib.agw.aui.framemanager.AuiManager` which manages the toolbar.
[ "Sets", "the", ":", "class", ":", "~lib", ".", "agw", ".", "aui", ".", "framemanager", ".", "AuiManager", "which", "manages", "the", "toolbar", "." ]
def SetAuiManager(self, auiManager): """ Sets the :class:`~lib.agw.aui.framemanager.AuiManager` which manages the toolbar. """ self._auiManager = auiManager
[ "def", "SetAuiManager", "(", "self", ",", "auiManager", ")", ":", "self", ".", "_auiManager", "=", "auiManager" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L3233-L3236
dmlc/xgboost
2775c2a1abd4b5b759ff517617434c8b9aeb4cc0
demo/json-model/json_parser.py
python
Tree.parent
(self, node_id: int)
return self.nodes[node_id][self._parent]
Parent ID of a node.
Parent ID of a node.
[ "Parent", "ID", "of", "a", "node", "." ]
def parent(self, node_id: int): '''Parent ID of a node.''' return self.nodes[node_id][self._parent]
[ "def", "parent", "(", "self", ",", "node_id", ":", "int", ")", ":", "return", "self", ".", "nodes", "[", "node_id", "]", "[", "self", ".", "_parent", "]" ]
https://github.com/dmlc/xgboost/blob/2775c2a1abd4b5b759ff517617434c8b9aeb4cc0/demo/json-model/json_parser.py#L47-L49
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/pkg_resources/__init__.py
python
EntryPoint.resolve
(self)
Resolve the entry point from its module and attrs.
Resolve the entry point from its module and attrs.
[ "Resolve", "the", "entry", "point", "from", "its", "module", "and", "attrs", "." ]
def resolve(self): """ Resolve the entry point from its module and attrs. """ module = __import__(self.module_name, fromlist=['__name__'], level=0) try: return functools.reduce(getattr, self.attrs, module) except AttributeError as exc: raise ImportError(str(exc))
[ "def", "resolve", "(", "self", ")", ":", "module", "=", "__import__", "(", "self", ".", "module_name", ",", "fromlist", "=", "[", "'__name__'", "]", ",", "level", "=", "0", ")", "try", ":", "return", "functools", ".", "reduce", "(", "getattr", ",", "self", ".", "attrs", ",", "module", ")", "except", "AttributeError", "as", "exc", ":", "raise", "ImportError", "(", "str", "(", "exc", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L2445-L2453
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
Display.GetFromPoint
(*args, **kwargs)
return _misc_.Display_GetFromPoint(*args, **kwargs)
GetFromPoint(Point pt) -> int Find the display where the given point lies, return wx.NOT_FOUND if it doesn't belong to any display
GetFromPoint(Point pt) -> int
[ "GetFromPoint", "(", "Point", "pt", ")", "-", ">", "int" ]
def GetFromPoint(*args, **kwargs): """ GetFromPoint(Point pt) -> int Find the display where the given point lies, return wx.NOT_FOUND if it doesn't belong to any display """ return _misc_.Display_GetFromPoint(*args, **kwargs)
[ "def", "GetFromPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Display_GetFromPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L6093-L6100
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/tensor/creation.py
python
arange
(start=0, end=None, step=1, dtype=None, name=None)
return paddle.fluid.layers.range(start, end, step, dtype, name)
This OP returns a 1-D Tensor with spaced values within a given interval. Values are generated into the half-open interval [``start``, ``end``) with the ``step``. (the interval including ``start`` but excluding ``end``). If ``dtype`` is float32 or float64, we advise adding a small epsilon to ``end`` to avoid floating point rounding errors when comparing against ``end``. Parameters: start(float|int|Tensor): Start of interval. The interval includes this value. If ``end`` is None, the half-open interval is [0, ``start``). If ``start`` is a Tensor, it is a 1-D Tensor with shape [1], with data type int32, int64, float32, float64. Default is 0. end(float|int|Tensor, optional): End of interval. The interval does not include this value. If ``end`` is a Tensor, it is a 1-D Tensor with shape [1], with data type int32, int64, float32, float64. If ``end`` is None, the half-open interval is [0, ``start``). Default is None. step(float|int|Tensor, optional): Spacing between values. For any out, it is the istance between two adjacent values, out[i+1] - out[i]. If ``step`` is a Tensor, it is a 1-D Tensor with shape [1], with data type int32, int64, float32, float64. Default is 1. dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the output tensor. Supported data types: int32, int64, float32, float64. If ``dytpe`` is None, the data type is float32. Default is None. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: A 1-D Tensor with values from the interval [``start``, ``end``) taken with common difference ``step`` beginning from ``start``. Its data type is set by ``dtype``. Raises: TypeError: If ``dtype`` is not int32, int64, float32, float64. Examples: .. code-block:: python import paddle out1 = paddle.arange(5) # [0, 1, 2, 3, 4] out2 = paddle.arange(3, 9, 2.0) # [3, 5, 7] # use 4.999 instead of 5.0 to avoid floating point rounding errors out3 = paddle.arange(4.999, dtype='float32') # [0., 1., 2., 3., 4.] start_var = paddle.to_tensor([3]) out4 = paddle.arange(start_var, 7) # [3, 4, 5, 6]
This OP returns a 1-D Tensor with spaced values within a given interval.
[ "This", "OP", "returns", "a", "1", "-", "D", "Tensor", "with", "spaced", "values", "within", "a", "given", "interval", "." ]
def arange(start=0, end=None, step=1, dtype=None, name=None): """ This OP returns a 1-D Tensor with spaced values within a given interval. Values are generated into the half-open interval [``start``, ``end``) with the ``step``. (the interval including ``start`` but excluding ``end``). If ``dtype`` is float32 or float64, we advise adding a small epsilon to ``end`` to avoid floating point rounding errors when comparing against ``end``. Parameters: start(float|int|Tensor): Start of interval. The interval includes this value. If ``end`` is None, the half-open interval is [0, ``start``). If ``start`` is a Tensor, it is a 1-D Tensor with shape [1], with data type int32, int64, float32, float64. Default is 0. end(float|int|Tensor, optional): End of interval. The interval does not include this value. If ``end`` is a Tensor, it is a 1-D Tensor with shape [1], with data type int32, int64, float32, float64. If ``end`` is None, the half-open interval is [0, ``start``). Default is None. step(float|int|Tensor, optional): Spacing between values. For any out, it is the istance between two adjacent values, out[i+1] - out[i]. If ``step`` is a Tensor, it is a 1-D Tensor with shape [1], with data type int32, int64, float32, float64. Default is 1. dtype(str|np.dtype|core.VarDesc.VarType, optional): The data type of the output tensor. Supported data types: int32, int64, float32, float64. If ``dytpe`` is None, the data type is float32. Default is None. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. Returns: Tensor: A 1-D Tensor with values from the interval [``start``, ``end``) taken with common difference ``step`` beginning from ``start``. Its data type is set by ``dtype``. Raises: TypeError: If ``dtype`` is not int32, int64, float32, float64. Examples: .. code-block:: python import paddle out1 = paddle.arange(5) # [0, 1, 2, 3, 4] out2 = paddle.arange(3, 9, 2.0) # [3, 5, 7] # use 4.999 instead of 5.0 to avoid floating point rounding errors out3 = paddle.arange(4.999, dtype='float32') # [0., 1., 2., 3., 4.] start_var = paddle.to_tensor([3]) out4 = paddle.arange(start_var, 7) # [3, 4, 5, 6] """ if dtype is None: dtype = 'int64' if end is None: end = start start = 0 return paddle.fluid.layers.range(start, end, step, dtype, name)
[ "def", "arange", "(", "start", "=", "0", ",", "end", "=", "None", ",", "step", "=", "1", ",", "dtype", "=", "None", ",", "name", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "'int64'", "if", "end", "is", "None", ":", "end", "=", "start", "start", "=", "0", "return", "paddle", ".", "fluid", ".", "layers", ".", "range", "(", "start", ",", "end", ",", "step", ",", "dtype", ",", "name", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/creation.py#L488-L552
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/managers.py
python
Server.debug_info
(self, c)
Return some info --- useful to spot problems with refcounting
Return some info --- useful to spot problems with refcounting
[ "Return", "some", "info", "---", "useful", "to", "spot", "problems", "with", "refcounting" ]
def debug_info(self, c): ''' Return some info --- useful to spot problems with refcounting ''' # Perhaps include debug info about 'c'? with self.mutex: result = [] keys = list(self.id_to_refcount.keys()) keys.sort() for ident in keys: if ident != '0': result.append(' %s: refcount=%s\n %s' % (ident, self.id_to_refcount[ident], str(self.id_to_obj[ident][0])[:75])) return '\n'.join(result)
[ "def", "debug_info", "(", "self", ",", "c", ")", ":", "# Perhaps include debug info about 'c'?", "with", "self", ".", "mutex", ":", "result", "=", "[", "]", "keys", "=", "list", "(", "self", ".", "id_to_refcount", ".", "keys", "(", ")", ")", "keys", ".", "sort", "(", ")", "for", "ident", "in", "keys", ":", "if", "ident", "!=", "'0'", ":", "result", ".", "append", "(", "' %s: refcount=%s\\n %s'", "%", "(", "ident", ",", "self", ".", "id_to_refcount", "[", "ident", "]", ",", "str", "(", "self", ".", "id_to_obj", "[", "ident", "]", "[", "0", "]", ")", "[", ":", "75", "]", ")", ")", "return", "'\\n'", ".", "join", "(", "result", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/managers.py#L318-L332
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/message.py
python
Message.__getstate__
(self)
return dict(serialized=self.SerializePartialToString())
Support the pickle protocol.
Support the pickle protocol.
[ "Support", "the", "pickle", "protocol", "." ]
def __getstate__(self): """Support the pickle protocol.""" return dict(serialized=self.SerializePartialToString())
[ "def", "__getstate__", "(", "self", ")", ":", "return", "dict", "(", "serialized", "=", "self", ".", "SerializePartialToString", "(", ")", ")" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/message.py#L273-L275
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/WebOb/webob/request.py
python
BaseRequest.path_qs
(self)
return path
The path of the request, without host but with query string
The path of the request, without host but with query string
[ "The", "path", "of", "the", "request", "without", "host", "but", "with", "query", "string" ]
def path_qs(self): """ The path of the request, without host but with query string """ path = self.path qs = self.environ.get('QUERY_STRING') if qs: path += '?' + qs return path
[ "def", "path_qs", "(", "self", ")", ":", "path", "=", "self", ".", "path", "qs", "=", "self", ".", "environ", ".", "get", "(", "'QUERY_STRING'", ")", "if", "qs", ":", "path", "+=", "'?'", "+", "qs", "return", "path" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/WebOb/webob/request.py#L490-L498
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.GetMsvsToolchainEnv
(self, additional_settings=None)
return self.msvs_settings.GetVSMacroEnv( "$!PRODUCT_DIR", config=self.config_name )
Returns the variables Visual Studio would set for build steps.
Returns the variables Visual Studio would set for build steps.
[ "Returns", "the", "variables", "Visual", "Studio", "would", "set", "for", "build", "steps", "." ]
def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv( "$!PRODUCT_DIR", config=self.config_name )
[ "def", "GetMsvsToolchainEnv", "(", "self", ",", "additional_settings", "=", "None", ")", ":", "return", "self", ".", "msvs_settings", ".", "GetVSMacroEnv", "(", "\"$!PRODUCT_DIR\"", ",", "config", "=", "self", ".", "config_name", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/ninja.py#L1686-L1690
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/scripts/cpp_lint.py
python
FindPreviousMatchingAngleBracket
(clean_lines, linenum, init_prefix)
return False
Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists.
Find the corresponding < that started a template.
[ "Find", "the", "corresponding", "<", "that", "started", "a", "template", "." ]
def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): """Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists. """ line = init_prefix nesting_stack = ['>'] while True: # Find the previous operator match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) if match: # Found an operator, update nesting stack operator = match.group(2) line = match.group(1) if nesting_stack[-1] == '>': # Expecting opening angle bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator == '<': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma before a bracket, this is most likely a # template argument. The opening angle bracket is probably # there if we look for it, so just return early here. return True else: # Got some other operator. return False else: # Expecting opening parenthesis or opening bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator in ('(', '['): nesting_stack.pop() else: # Scan the previous line linenum -= 1 if linenum < 0: break line = clean_lines.elided[linenum] # Exhausted all earlier lines and still no matching angle bracket. return False
[ "def", "FindPreviousMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_prefix", ")", ":", "line", "=", "init_prefix", "nesting_stack", "=", "[", "'>'", "]", "while", "True", ":", "# Find the previous operator", "match", "=", "Search", "(", "r'^(.*)([<>(),;\\[\\]])[^<>(),;\\[\\]]*$'", ",", "line", ")", "if", "match", ":", "# Found an operator, update nesting stack", "operator", "=", "match", ".", "group", "(", "2", ")", "line", "=", "match", ".", "group", "(", "1", ")", "if", "nesting_stack", "[", "-", "1", "]", "==", "'>'", ":", "# Expecting opening angle bracket", "if", "operator", "in", "(", "'>'", ",", "')'", ",", "']'", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "==", "'<'", ":", "nesting_stack", ".", "pop", "(", ")", "if", "not", "nesting_stack", ":", "# Found matching angle bracket", "return", "True", "elif", "operator", "==", "','", ":", "# Got a comma before a bracket, this is most likely a", "# template argument. The opening angle bracket is probably", "# there if we look for it, so just return early here.", "return", "True", "else", ":", "# Got some other operator.", "return", "False", "else", ":", "# Expecting opening parenthesis or opening bracket", "if", "operator", "in", "(", "'>'", ",", "')'", ",", "']'", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "in", "(", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "pop", "(", ")", "else", ":", "# Scan the previous line", "linenum", "-=", "1", "if", "linenum", "<", "0", ":", "break", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Exhausted all earlier lines and still no matching angle bracket.", "return", "False" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/scripts/cpp_lint.py#L2586-L2640
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/agents/tools/in_graph_batch_env.py
python
InGraphBatchEnv._parse_dtype
(self, space)
Get a tensor dtype from a OpenAI Gym space. Args: space: Gym space. Returns: TensorFlow data type.
Get a tensor dtype from a OpenAI Gym space.
[ "Get", "a", "tensor", "dtype", "from", "a", "OpenAI", "Gym", "space", "." ]
def _parse_dtype(self, space): """Get a tensor dtype from a OpenAI Gym space. Args: space: Gym space. Returns: TensorFlow data type. """ if isinstance(space, gym.spaces.Discrete): return tf.int32 if isinstance(space, gym.spaces.Box): return tf.float32 raise NotImplementedError()
[ "def", "_parse_dtype", "(", "self", ",", "space", ")", ":", "if", "isinstance", "(", "space", ",", "gym", ".", "spaces", ".", "Discrete", ")", ":", "return", "tf", ".", "int32", "if", "isinstance", "(", "space", ",", "gym", ".", "spaces", ".", "Box", ")", ":", "return", "tf", ".", "float32", "raise", "NotImplementedError", "(", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/agents/tools/in_graph_batch_env.py#L161-L174
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py
python
Series.dot
(self, other)
Compute the dot product between the Series and the columns of other. This method computes the dot product between the Series and another one, or the Series and each columns of a DataFrame, or the Series and each columns of an array. It can also be called using `self @ other` in Python >= 3.5. Parameters ---------- other : Series, DataFrame or array-like The other object to compute the dot product with its columns. Returns ------- scalar, Series or numpy.ndarray Return the dot product of the Series and other if other is a Series, the Series of the dot product of Series and each rows of other if other is a DataFrame or a numpy.ndarray between the Series and each columns of the numpy array. See Also -------- DataFrame.dot: Compute the matrix product with the DataFrame. Series.mul: Multiplication of series and other, element-wise. Notes ----- The Series and other has to share the same index if other is a Series or a DataFrame. Examples -------- >>> s = pd.Series([0, 1, 2, 3]) >>> other = pd.Series([-1, 2, -3, 4]) >>> s.dot(other) 8 >>> s @ other 8 >>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]]) >>> s.dot(df) 0 24 1 14 dtype: int64 >>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]]) >>> s.dot(arr) array([24, 14])
Compute the dot product between the Series and the columns of other.
[ "Compute", "the", "dot", "product", "between", "the", "Series", "and", "the", "columns", "of", "other", "." ]
def dot(self, other): """ Compute the dot product between the Series and the columns of other. This method computes the dot product between the Series and another one, or the Series and each columns of a DataFrame, or the Series and each columns of an array. It can also be called using `self @ other` in Python >= 3.5. Parameters ---------- other : Series, DataFrame or array-like The other object to compute the dot product with its columns. Returns ------- scalar, Series or numpy.ndarray Return the dot product of the Series and other if other is a Series, the Series of the dot product of Series and each rows of other if other is a DataFrame or a numpy.ndarray between the Series and each columns of the numpy array. See Also -------- DataFrame.dot: Compute the matrix product with the DataFrame. Series.mul: Multiplication of series and other, element-wise. Notes ----- The Series and other has to share the same index if other is a Series or a DataFrame. Examples -------- >>> s = pd.Series([0, 1, 2, 3]) >>> other = pd.Series([-1, 2, -3, 4]) >>> s.dot(other) 8 >>> s @ other 8 >>> df = pd.DataFrame([[0, 1], [-2, 3], [4, -5], [6, 7]]) >>> s.dot(df) 0 24 1 14 dtype: int64 >>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]]) >>> s.dot(arr) array([24, 14]) """ if isinstance(other, (Series, ABCDataFrame)): common = self.index.union(other.index) if len(common) > len(self.index) or len(common) > len(other.index): raise ValueError("matrices are not aligned") left = self.reindex(index=common, copy=False) right = other.reindex(index=common, copy=False) lvals = left.values rvals = right.values else: lvals = self.values rvals = np.asarray(other) if lvals.shape[0] != rvals.shape[0]: raise Exception( f"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}" ) if isinstance(other, ABCDataFrame): return self._constructor( np.dot(lvals, rvals), index=other.columns ).__finalize__(self) elif isinstance(other, Series): return np.dot(lvals, rvals) elif isinstance(rvals, np.ndarray): return np.dot(lvals, rvals) else: # pragma: no cover raise TypeError(f"unsupported type: {type(other)}")
[ "def", "dot", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "(", "Series", ",", "ABCDataFrame", ")", ")", ":", "common", "=", "self", ".", "index", ".", "union", "(", "other", ".", "index", ")", "if", "len", "(", "common", ")", ">", "len", "(", "self", ".", "index", ")", "or", "len", "(", "common", ")", ">", "len", "(", "other", ".", "index", ")", ":", "raise", "ValueError", "(", "\"matrices are not aligned\"", ")", "left", "=", "self", ".", "reindex", "(", "index", "=", "common", ",", "copy", "=", "False", ")", "right", "=", "other", ".", "reindex", "(", "index", "=", "common", ",", "copy", "=", "False", ")", "lvals", "=", "left", ".", "values", "rvals", "=", "right", ".", "values", "else", ":", "lvals", "=", "self", ".", "values", "rvals", "=", "np", ".", "asarray", "(", "other", ")", "if", "lvals", ".", "shape", "[", "0", "]", "!=", "rvals", ".", "shape", "[", "0", "]", ":", "raise", "Exception", "(", "f\"Dot product shape mismatch, {lvals.shape} vs {rvals.shape}\"", ")", "if", "isinstance", "(", "other", ",", "ABCDataFrame", ")", ":", "return", "self", ".", "_constructor", "(", "np", ".", "dot", "(", "lvals", ",", "rvals", ")", ",", "index", "=", "other", ".", "columns", ")", ".", "__finalize__", "(", "self", ")", "elif", "isinstance", "(", "other", ",", "Series", ")", ":", "return", "np", ".", "dot", "(", "lvals", ",", "rvals", ")", "elif", "isinstance", "(", "rvals", ",", "np", ".", "ndarray", ")", ":", "return", "np", ".", "dot", "(", "lvals", ",", "rvals", ")", "else", ":", "# pragma: no cover", "raise", "TypeError", "(", "f\"unsupported type: {type(other)}\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py#L2406-L2482
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/InstanceTopologyChannelsHTMLVisitor.py
python
InstanceTopologyChannelsHTMLVisitor.initFilesVisit
(self, obj)
Defined to generate files for generated code products. @param obj: the instance of the model to visit.
Defined to generate files for generated code products.
[ "Defined", "to", "generate", "files", "for", "generated", "code", "products", "." ]
def initFilesVisit(self, obj): """ Defined to generate files for generated code products. @param obj: the instance of the model to visit. """ # Check for command dir here and if none create it but always switch into it if not os.path.exists(self.__cmd_dir): os.mkdir(self.__cmd_dir) os.chdir(self.__cmd_dir) # Iterate over types for k in list(obj.get_base_id_dict().keys()): tlist = obj.get_base_id_dict()[k] # print "Type: %s\n" % k, # Iterate over instances and get name # Open file if commands exist if not do nothing for t in tlist: # print "\tInstance: %s, Base ID: %s\n" % (t[0],t[1]) name = t[0] ch_list = t[3].get_comp_xml().get_channels() if len(ch_list) > 0: filename = "%s_channels.html" % t[0] # Open file for writing here... DEBUG.info("Open file: %s" % filename) try: self.__fp_dict[name] = open(filename, "w") DEBUG.info("Completed") except OSError: PRINT.info("Could not open %s file." % filename) sys.exit(-1) DEBUG.info( "Generating HTML Channels Table for %s:%s component instance..." % (t[0], k) ) os.chdir("..")
[ "def", "initFilesVisit", "(", "self", ",", "obj", ")", ":", "# Check for command dir here and if none create it but always switch into it", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "__cmd_dir", ")", ":", "os", ".", "mkdir", "(", "self", ".", "__cmd_dir", ")", "os", ".", "chdir", "(", "self", ".", "__cmd_dir", ")", "# Iterate over types", "for", "k", "in", "list", "(", "obj", ".", "get_base_id_dict", "(", ")", ".", "keys", "(", ")", ")", ":", "tlist", "=", "obj", ".", "get_base_id_dict", "(", ")", "[", "k", "]", "# print \"Type: %s\\n\" % k,", "# Iterate over instances and get name", "# Open file if commands exist if not do nothing", "for", "t", "in", "tlist", ":", "# print \"\\tInstance: %s, Base ID: %s\\n\" % (t[0],t[1])", "name", "=", "t", "[", "0", "]", "ch_list", "=", "t", "[", "3", "]", ".", "get_comp_xml", "(", ")", ".", "get_channels", "(", ")", "if", "len", "(", "ch_list", ")", ">", "0", ":", "filename", "=", "\"%s_channels.html\"", "%", "t", "[", "0", "]", "# Open file for writing here...", "DEBUG", ".", "info", "(", "\"Open file: %s\"", "%", "filename", ")", "try", ":", "self", ".", "__fp_dict", "[", "name", "]", "=", "open", "(", "filename", ",", "\"w\"", ")", "DEBUG", ".", "info", "(", "\"Completed\"", ")", "except", "OSError", ":", "PRINT", ".", "info", "(", "\"Could not open %s file.\"", "%", "filename", ")", "sys", ".", "exit", "(", "-", "1", ")", "DEBUG", ".", "info", "(", "\"Generating HTML Channels Table for %s:%s component instance...\"", "%", "(", "t", "[", "0", "]", ",", "k", ")", ")", "os", ".", "chdir", "(", "\"..\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/InstanceTopologyChannelsHTMLVisitor.py#L91-L124
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/shampoo.py
python
ShampooOptimizer._weighted_average
(self, var, weight, weight_t, rest)
return var.assign_add((weight_t - 1) * var + rest)
Computes exponential weighted average: var = weight_t * var + rest. Important to ensure that var does not occur in rest, otherwise we can get race conditions in a distributed setting. Args: var: variable to be updated weight: parameter to be checked. If it is a constant, we can optimize. weight_t: current value of parameter, used for weighting rest: the remaining tensor to be added Returns: updated variable.
Computes exponential weighted average: var = weight_t * var + rest.
[ "Computes", "exponential", "weighted", "average", ":", "var", "=", "weight_t", "*", "var", "+", "rest", "." ]
def _weighted_average(self, var, weight, weight_t, rest): """Computes exponential weighted average: var = weight_t * var + rest. Important to ensure that var does not occur in rest, otherwise we can get race conditions in a distributed setting. Args: var: variable to be updated weight: parameter to be checked. If it is a constant, we can optimize. weight_t: current value of parameter, used for weighting rest: the remaining tensor to be added Returns: updated variable. """ if weight == 0.0: return rest # no need to update var, we will never use it. if weight == 1.0: # common case return state_ops.assign_add(var, rest) # The op below can cause race conditions in a distributed setting, # since computing weight_t * var + rest can take some time, during # which var may be set by another worker. To prevent this, it should # be implemented as a C++ op. return var.assign_add((weight_t - 1) * var + rest)
[ "def", "_weighted_average", "(", "self", ",", "var", ",", "weight", ",", "weight_t", ",", "rest", ")", ":", "if", "weight", "==", "0.0", ":", "return", "rest", "# no need to update var, we will never use it.", "if", "weight", "==", "1.0", ":", "# common case", "return", "state_ops", ".", "assign_add", "(", "var", ",", "rest", ")", "# The op below can cause race conditions in a distributed setting,", "# since computing weight_t * var + rest can take some time, during", "# which var may be set by another worker. To prevent this, it should", "# be implemented as a C++ op.", "return", "var", ".", "assign_add", "(", "(", "weight_t", "-", "1", ")", "*", "var", "+", "rest", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/opt/python/training/shampoo.py#L178-L201
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosgraph/src/rosgraph/masterapi.py
python
Master.getSystemState
(self)
return self._succeed(self.handle.getSystemState(self.caller_id))
Retrieve list representation of system state (i.e. publishers, subscribers, and services). @rtype: [[str,[str]], [str,[str]], [str,[str]]] @return: systemState System state is in list representation:: [publishers, subscribers, services]. publishers is of the form:: [ [topic1, [topic1Publisher1...topic1PublisherN]] ... ] subscribers is of the form:: [ [topic1, [topic1Subscriber1...topic1SubscriberN]] ... ] services is of the form:: [ [service1, [service1Provider1...service1ProviderN]] ... ] @raise rosgraph.masterapi.Error: if Master returns ERROR. @raise rosgraph.masterapi.Failure: if Master returns FAILURE.
Retrieve list representation of system state (i.e. publishers, subscribers, and services). @rtype: [[str,[str]], [str,[str]], [str,[str]]] @return: systemState
[ "Retrieve", "list", "representation", "of", "system", "state", "(", "i", ".", "e", ".", "publishers", "subscribers", "and", "services", ")", ".", "@rtype", ":", "[[", "str", "[", "str", "]]", "[", "str", "[", "str", "]]", "[", "str", "[", "str", "]]]", "@return", ":", "systemState" ]
def getSystemState(self): """ Retrieve list representation of system state (i.e. publishers, subscribers, and services). @rtype: [[str,[str]], [str,[str]], [str,[str]]] @return: systemState System state is in list representation:: [publishers, subscribers, services]. publishers is of the form:: [ [topic1, [topic1Publisher1...topic1PublisherN]] ... ] subscribers is of the form:: [ [topic1, [topic1Subscriber1...topic1SubscriberN]] ... ] services is of the form:: [ [service1, [service1Provider1...service1ProviderN]] ... ] @raise rosgraph.masterapi.Error: if Master returns ERROR. @raise rosgraph.masterapi.Failure: if Master returns FAILURE. """ return self._succeed(self.handle.getSystemState(self.caller_id))
[ "def", "getSystemState", "(", "self", ")", ":", "return", "self", ".", "_succeed", "(", "self", ".", "handle", ".", "getSystemState", "(", "self", ".", "caller_id", ")", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosgraph/src/rosgraph/masterapi.py#L475-L496
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PreHScrolledWindow
(*args, **kwargs)
return val
PreHScrolledWindow() -> HScrolledWindow
PreHScrolledWindow() -> HScrolledWindow
[ "PreHScrolledWindow", "()", "-", ">", "HScrolledWindow" ]
def PreHScrolledWindow(*args, **kwargs): """PreHScrolledWindow() -> HScrolledWindow""" val = _windows_.new_PreHScrolledWindow(*args, **kwargs) return val
[ "def", "PreHScrolledWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_windows_", ".", "new_PreHScrolledWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L2530-L2533
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/cell.py
python
Cell.parameters_broadcast_dict
(self, recurse=True)
return param_dict
Gets the parameters broadcast dictionary of this cell. Args: recurse (bool): Whether contains the parameters of subcells. Default: True. Returns: OrderedDict, return parameters broadcast dictionary.
Gets the parameters broadcast dictionary of this cell.
[ "Gets", "the", "parameters", "broadcast", "dictionary", "of", "this", "cell", "." ]
def parameters_broadcast_dict(self, recurse=True): """ Gets the parameters broadcast dictionary of this cell. Args: recurse (bool): Whether contains the parameters of subcells. Default: True. Returns: OrderedDict, return parameters broadcast dictionary. """ param_dict = OrderedDict() for param in self.get_parameters(expand=recurse): if param.layerwise_parallel is False: param_dict[param.name] = param if not param_dict: return None return param_dict
[ "def", "parameters_broadcast_dict", "(", "self", ",", "recurse", "=", "True", ")", ":", "param_dict", "=", "OrderedDict", "(", ")", "for", "param", "in", "self", ".", "get_parameters", "(", "expand", "=", "recurse", ")", ":", "if", "param", ".", "layerwise_parallel", "is", "False", ":", "param_dict", "[", "param", ".", "name", "]", "=", "param", "if", "not", "param_dict", ":", "return", "None", "return", "param_dict" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/cell.py#L1027-L1043
google/skia
82d65d0487bd72f5f7332d002429ec2dc61d2463
infra/bots/utils.py
python
git_clone
(repo_url, dest_dir)
Clone the given repo into the given destination directory.
Clone the given repo into the given destination directory.
[ "Clone", "the", "given", "repo", "into", "the", "given", "destination", "directory", "." ]
def git_clone(repo_url, dest_dir): """Clone the given repo into the given destination directory.""" subprocess.check_call([GIT, 'clone', repo_url, dest_dir])
[ "def", "git_clone", "(", "repo_url", ",", "dest_dir", ")", ":", "subprocess", ".", "check_call", "(", "[", "GIT", ",", "'clone'", ",", "repo_url", ",", "dest_dir", "]", ")" ]
https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/utils.py#L77-L79
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/rpn/anchor_target_layer.py
python
AnchorTargetLayer.backward
(self, top, propagate_down, bottom)
This layer does not propagate gradients.
This layer does not propagate gradients.
[ "This", "layer", "does", "not", "propagate", "gradients", "." ]
def backward(self, top, propagate_down, bottom): """This layer does not propagate gradients.""" pass
[ "def", "backward", "(", "self", ",", "top", ",", "propagate_down", ",", "bottom", ")", ":", "pass" ]
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/rpn/anchor_target_layer.py#L252-L254
Tencent/PhoenixGo
fbf67f9aec42531bff9569c44b85eb4c3f37b7be
configure.py
python
set_action_env_var
(environ_cp, var_name, query_item, enabled_by_default, question=None, yes_reply=None, no_reply=None)
Set boolean action_env variable. Ask user if query_item will be enabled. Default is used if no input is given. Set environment variable and write to .bazelrc. Args: environ_cp: copy of the os.environ. var_name: string for name of environment variable, e.g. "TF_NEED_HDFS". query_item: string for feature related to the variable, e.g. "Hadoop File System". enabled_by_default: boolean for default behavior. question: optional string for how to ask for user input. yes_reply: optional string for reply when feature is enabled. no_reply: optional string for reply when feature is disabled.
Set boolean action_env variable.
[ "Set", "boolean", "action_env", "variable", "." ]
def set_action_env_var(environ_cp, var_name, query_item, enabled_by_default, question=None, yes_reply=None, no_reply=None): """Set boolean action_env variable. Ask user if query_item will be enabled. Default is used if no input is given. Set environment variable and write to .bazelrc. Args: environ_cp: copy of the os.environ. var_name: string for name of environment variable, e.g. "TF_NEED_HDFS". query_item: string for feature related to the variable, e.g. "Hadoop File System". enabled_by_default: boolean for default behavior. question: optional string for how to ask for user input. yes_reply: optional string for reply when feature is enabled. no_reply: optional string for reply when feature is disabled. """ var = int( get_var(environ_cp, var_name, query_item, enabled_by_default, question, yes_reply, no_reply)) write_action_env_to_bazelrc(var_name, var) environ_cp[var_name] = str(var)
[ "def", "set_action_env_var", "(", "environ_cp", ",", "var_name", ",", "query_item", ",", "enabled_by_default", ",", "question", "=", "None", ",", "yes_reply", "=", "None", ",", "no_reply", "=", "None", ")", ":", "var", "=", "int", "(", "get_var", "(", "environ_cp", ",", "var_name", ",", "query_item", ",", "enabled_by_default", ",", "question", ",", "yes_reply", ",", "no_reply", ")", ")", "write_action_env_to_bazelrc", "(", "var_name", ",", "var", ")", "environ_cp", "[", "var_name", "]", "=", "str", "(", "var", ")" ]
https://github.com/Tencent/PhoenixGo/blob/fbf67f9aec42531bff9569c44b85eb4c3f37b7be/configure.py#L391-L418
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/math_grad.py
python
_ZetaGrad
(op, grad)
Returns gradient of zeta(x, q) with respect to x and q.
Returns gradient of zeta(x, q) with respect to x and q.
[ "Returns", "gradient", "of", "zeta", "(", "x", "q", ")", "with", "respect", "to", "x", "and", "q", "." ]
def _ZetaGrad(op, grad): """Returns gradient of zeta(x, q) with respect to x and q.""" # TODO(tillahoffmann): Add derivative with respect to x x = op.inputs[0] q = op.inputs[1] # Broadcast gradients sx = array_ops.shape(x) sq = array_ops.shape(q) unused_rx, rq = gen_array_ops._broadcast_gradient_args(sx, sq) # Evaluate gradient with ops.control_dependencies([grad.op]): x = math_ops.conj(x) q = math_ops.conj(q) partial_q = -x * math_ops.zeta(x + 1, q) return (None, array_ops.reshape(math_ops.reduce_sum(partial_q * grad, rq), sq))
[ "def", "_ZetaGrad", "(", "op", ",", "grad", ")", ":", "# TODO(tillahoffmann): Add derivative with respect to x", "x", "=", "op", ".", "inputs", "[", "0", "]", "q", "=", "op", ".", "inputs", "[", "1", "]", "# Broadcast gradients", "sx", "=", "array_ops", ".", "shape", "(", "x", ")", "sq", "=", "array_ops", ".", "shape", "(", "q", ")", "unused_rx", ",", "rq", "=", "gen_array_ops", ".", "_broadcast_gradient_args", "(", "sx", ",", "sq", ")", "# Evaluate gradient", "with", "ops", ".", "control_dependencies", "(", "[", "grad", ".", "op", "]", ")", ":", "x", "=", "math_ops", ".", "conj", "(", "x", ")", "q", "=", "math_ops", ".", "conj", "(", "q", ")", "partial_q", "=", "-", "x", "*", "math_ops", ".", "zeta", "(", "x", "+", "1", ",", "q", ")", "return", "(", "None", ",", "array_ops", ".", "reshape", "(", "math_ops", ".", "reduce_sum", "(", "partial_q", "*", "grad", ",", "rq", ")", ",", "sq", ")", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/math_grad.py#L411-L426
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py
python
Node.get_implicit_deps
(self, env, initial_scanner, path_func, kw = {})
return dependencies
Return a list of implicit dependencies for this node. This method exists to handle recursive invocation of the scanner on the implicit dependencies returned by the scanner, if the scanner's recursive flag says that we should.
Return a list of implicit dependencies for this node.
[ "Return", "a", "list", "of", "implicit", "dependencies", "for", "this", "node", "." ]
def get_implicit_deps(self, env, initial_scanner, path_func, kw = {}): """Return a list of implicit dependencies for this node. This method exists to handle recursive invocation of the scanner on the implicit dependencies returned by the scanner, if the scanner's recursive flag says that we should. """ nodes = [self] seen = {} seen[self] = 1 dependencies = [] root_node_scanner = self._get_scanner(env, initial_scanner, None, kw) while nodes: node = nodes.pop(0) scanner = node._get_scanner(env, initial_scanner, root_node_scanner, kw) if not scanner: continue path = path_func(scanner) included_deps = [x for x in node.get_found_includes(env, scanner, path) if x not in seen] if included_deps: dependencies.extend(included_deps) for dep in included_deps: seen[dep] = 1 nodes.extend(scanner.recurse_nodes(included_deps)) return dependencies
[ "def", "get_implicit_deps", "(", "self", ",", "env", ",", "initial_scanner", ",", "path_func", ",", "kw", "=", "{", "}", ")", ":", "nodes", "=", "[", "self", "]", "seen", "=", "{", "}", "seen", "[", "self", "]", "=", "1", "dependencies", "=", "[", "]", "root_node_scanner", "=", "self", ".", "_get_scanner", "(", "env", ",", "initial_scanner", ",", "None", ",", "kw", ")", "while", "nodes", ":", "node", "=", "nodes", ".", "pop", "(", "0", ")", "scanner", "=", "node", ".", "_get_scanner", "(", "env", ",", "initial_scanner", ",", "root_node_scanner", ",", "kw", ")", "if", "not", "scanner", ":", "continue", "path", "=", "path_func", "(", "scanner", ")", "included_deps", "=", "[", "x", "for", "x", "in", "node", ".", "get_found_includes", "(", "env", ",", "scanner", ",", "path", ")", "if", "x", "not", "in", "seen", "]", "if", "included_deps", ":", "dependencies", ".", "extend", "(", "included_deps", ")", "for", "dep", "in", "included_deps", ":", "seen", "[", "dep", "]", "=", "1", "nodes", ".", "extend", "(", "scanner", ".", "recurse_nodes", "(", "included_deps", ")", ")", "return", "dependencies" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py#L919-L950
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/train/train_thor/model_thor.py
python
_exec_datagraph
(exec_dataset, dataset_size, phase='dataset')
Initialize and execute the dataset graph.
Initialize and execute the dataset graph.
[ "Initialize", "and", "execute", "the", "dataset", "graph", "." ]
def _exec_datagraph(exec_dataset, dataset_size, phase='dataset'): """Initialize and execute the dataset graph.""" batch_size = exec_dataset.get_batch_size() input_indexs = exec_dataset.input_indexs # transform data format dataset_types, dataset_shapes = _get_types_and_shapes(exec_dataset) init_exec_dataset(exec_dataset.__transfer_dataset__.queue_name, dataset_size, batch_size, dataset_types, dataset_shapes, input_indexs, phase=phase, need_run=False)
[ "def", "_exec_datagraph", "(", "exec_dataset", ",", "dataset_size", ",", "phase", "=", "'dataset'", ")", ":", "batch_size", "=", "exec_dataset", ".", "get_batch_size", "(", ")", "input_indexs", "=", "exec_dataset", ".", "input_indexs", "# transform data format", "dataset_types", ",", "dataset_shapes", "=", "_get_types_and_shapes", "(", "exec_dataset", ")", "init_exec_dataset", "(", "exec_dataset", ".", "__transfer_dataset__", ".", "queue_name", ",", "dataset_size", ",", "batch_size", ",", "dataset_types", ",", "dataset_shapes", ",", "input_indexs", ",", "phase", "=", "phase", ",", "need_run", "=", "False", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/train/train_thor/model_thor.py#L57-L71
sebastianstarke/AI4Animation
e2cd539816b1cb1fa0a57e9d21df21d48467b313
AI4Animation/SIGGRAPH_Asia_2019/TensorFlow/NSM/Lib_Expert/ComponentNN.py
python
ComponentNN.saveNN
(self, sess, savepath, index_component)
:param index_component: index of current component
:param index_component: index of current component
[ ":", "param", "index_component", ":", "index", "of", "current", "component" ]
def saveNN(self, sess, savepath, index_component): """ :param index_component: index of current component """ for i in range(self.num_layers): for j in range(self.num_experts): sess.run(self.experts[i].alpha[j]).tofile(savepath + '/wc%0i%0i%0i_w.bin' % (index_component, i, j)) sess.run(self.experts[i].beta[j]).tofile(savepath + '/wc%0i%0i%0i_b.bin' % (index_component, i, j))
[ "def", "saveNN", "(", "self", ",", "sess", ",", "savepath", ",", "index_component", ")", ":", "for", "i", "in", "range", "(", "self", ".", "num_layers", ")", ":", "for", "j", "in", "range", "(", "self", ".", "num_experts", ")", ":", "sess", ".", "run", "(", "self", ".", "experts", "[", "i", "]", ".", "alpha", "[", "j", "]", ")", ".", "tofile", "(", "savepath", "+", "'/wc%0i%0i%0i_w.bin'", "%", "(", "index_component", ",", "i", ",", "j", ")", ")", "sess", ".", "run", "(", "self", ".", "experts", "[", "i", "]", ".", "beta", "[", "j", "]", ")", ".", "tofile", "(", "savepath", "+", "'/wc%0i%0i%0i_b.bin'", "%", "(", "index_component", ",", "i", ",", "j", ")", ")" ]
https://github.com/sebastianstarke/AI4Animation/blob/e2cd539816b1cb1fa0a57e9d21df21d48467b313/AI4Animation/SIGGRAPH_Asia_2019/TensorFlow/NSM/Lib_Expert/ComponentNN.py#L90-L97
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/graph_editor/transform.py
python
Transformer._copy_ops
(self, info)
Copy ops without connecting them.
Copy ops without connecting them.
[ "Copy", "ops", "without", "connecting", "them", "." ]
def _copy_ops(self, info): """Copy ops without connecting them.""" for op in info.sgv.ops: logging.debug("Copying op: %s", op.name) # TODO(fkp): return a subgraph? op_, op_outputs_ = self.transform_op_handler(info, op) if op is op_: raise ValueError("In-place transformation not allowed.") # Process op. info.transformed_ops[op] = op_ self.assign_collections_handler(info, op, op_) # Process output tensors. for op_output, op_output_ in zip(op.outputs, op_outputs_): info.transformed_ts[op_output] = op_output_ self.assign_collections_handler(info, op_output, op_output_)
[ "def", "_copy_ops", "(", "self", ",", "info", ")", ":", "for", "op", "in", "info", ".", "sgv", ".", "ops", ":", "logging", ".", "debug", "(", "\"Copying op: %s\"", ",", "op", ".", "name", ")", "# TODO(fkp): return a subgraph?", "op_", ",", "op_outputs_", "=", "self", ".", "transform_op_handler", "(", "info", ",", "op", ")", "if", "op", "is", "op_", ":", "raise", "ValueError", "(", "\"In-place transformation not allowed.\"", ")", "# Process op.", "info", ".", "transformed_ops", "[", "op", "]", "=", "op_", "self", ".", "assign_collections_handler", "(", "info", ",", "op", ",", "op_", ")", "# Process output tensors.", "for", "op_output", ",", "op_output_", "in", "zip", "(", "op", ".", "outputs", ",", "op_outputs_", ")", ":", "info", ".", "transformed_ts", "[", "op_output", "]", "=", "op_output_", "self", ".", "assign_collections_handler", "(", "info", ",", "op_output", ",", "op_output_", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/graph_editor/transform.py#L441-L457
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.GetMultiPaste
(*args, **kwargs)
return _stc.StyledTextCtrl_GetMultiPaste(*args, **kwargs)
GetMultiPaste(self) -> int
GetMultiPaste(self) -> int
[ "GetMultiPaste", "(", "self", ")", "-", ">", "int" ]
def GetMultiPaste(*args, **kwargs): """GetMultiPaste(self) -> int""" return _stc.StyledTextCtrl_GetMultiPaste(*args, **kwargs)
[ "def", "GetMultiPaste", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetMultiPaste", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L4281-L4283
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/client/session.py
python
register_session_run_conversion_functions
(tensor_type, fetch_function, feed_function=None, feed_function_for_partial_run=None)
Register fetch and feed conversion functions for `tf.Session.run()`. This function registers a triple of conversion functions for fetching and/or feeding values of user-defined types in a call to tf.Session.run(). An example ```python class SquaredTensor(object): def __init__(self, tensor): self.sq = tf.square(tensor) #you can define conversion functions as follows: fetch_function = lambda squared_tensor:([squared_tensor.sq], lambda val: val[0]) feed_function = lambda feed, feed_val: [(feed.sq, feed_val)] feed_function_for_partial_run = lambda feed: [feed.sq] #then after invoking this register function, you can use as follows: session.run(squared_tensor1, feed_dict = {squared_tensor2 : some_numpy_array}) ``` Args: tensor_type: The type for which you want to register a conversion function. fetch_function: A callable that takes an object of type `tensor_type` and returns a tuple, where the first element is a list of `tf.Tensor` objects, and the second element is a callable that takes a list of ndarrays and returns an object of some value type that corresponds to `tensor_type`. fetch_function describes how to expand fetch into its component Tensors and how to contract the fetched results back into a single return value. feed_function: A callable that takes feed_key and feed_value as input, and returns a list of tuples (feed_tensor, feed_val), feed_key must have type `tensor_type`, and feed_tensor must have type `tf.Tensor`. Each feed function describes how to unpack a single fed value and map it to feeds of one or more tensors and their corresponding values. feed_function_for_partial_run: A callable for specifying tensor values to feed when setting up a partial run, which takes a `tensor_type` type object as input, and returns a list of Tensors.
Register fetch and feed conversion functions for `tf.Session.run()`.
[ "Register", "fetch", "and", "feed", "conversion", "functions", "for", "tf", ".", "Session", ".", "run", "()", "." ]
def register_session_run_conversion_functions(tensor_type, fetch_function, feed_function=None, feed_function_for_partial_run=None): """Register fetch and feed conversion functions for `tf.Session.run()`. This function registers a triple of conversion functions for fetching and/or feeding values of user-defined types in a call to tf.Session.run(). An example ```python class SquaredTensor(object): def __init__(self, tensor): self.sq = tf.square(tensor) #you can define conversion functions as follows: fetch_function = lambda squared_tensor:([squared_tensor.sq], lambda val: val[0]) feed_function = lambda feed, feed_val: [(feed.sq, feed_val)] feed_function_for_partial_run = lambda feed: [feed.sq] #then after invoking this register function, you can use as follows: session.run(squared_tensor1, feed_dict = {squared_tensor2 : some_numpy_array}) ``` Args: tensor_type: The type for which you want to register a conversion function. fetch_function: A callable that takes an object of type `tensor_type` and returns a tuple, where the first element is a list of `tf.Tensor` objects, and the second element is a callable that takes a list of ndarrays and returns an object of some value type that corresponds to `tensor_type`. fetch_function describes how to expand fetch into its component Tensors and how to contract the fetched results back into a single return value. feed_function: A callable that takes feed_key and feed_value as input, and returns a list of tuples (feed_tensor, feed_val), feed_key must have type `tensor_type`, and feed_tensor must have type `tf.Tensor`. Each feed function describes how to unpack a single fed value and map it to feeds of one or more tensors and their corresponding values. feed_function_for_partial_run: A callable for specifying tensor values to feed when setting up a partial run, which takes a `tensor_type` type object as input, and returns a list of Tensors. """ for conversion_function in _REGISTERED_EXPANSIONS: if issubclass(conversion_function[0], tensor_type): raise ValueError( '%s has already been registered so ignore it.', tensor_type) return _REGISTERED_EXPANSIONS.insert(0, (tensor_type, fetch_function, feed_function, feed_function_for_partial_run))
[ "def", "register_session_run_conversion_functions", "(", "tensor_type", ",", "fetch_function", ",", "feed_function", "=", "None", ",", "feed_function_for_partial_run", "=", "None", ")", ":", "for", "conversion_function", "in", "_REGISTERED_EXPANSIONS", ":", "if", "issubclass", "(", "conversion_function", "[", "0", "]", ",", "tensor_type", ")", ":", "raise", "ValueError", "(", "'%s has already been registered so ignore it.'", ",", "tensor_type", ")", "return", "_REGISTERED_EXPANSIONS", ".", "insert", "(", "0", ",", "(", "tensor_type", ",", "fetch_function", ",", "feed_function", ",", "feed_function_for_partial_run", ")", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/client/session.py#L128-L174
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/network/network.py
python
Network.set_boundaries
(self, convBoundary, origBoundary=None)
Format of Boundary box [MinX, MinY ,MaxX, MaxY ]
Format of Boundary box [MinX, MinY ,MaxX, MaxY ]
[ "Format", "of", "Boundary", "box", "[", "MinX", "MinY", "MaxX", "MaxY", "]" ]
def set_boundaries(self, convBoundary, origBoundary=None): """ Format of Boundary box [MinX, MinY ,MaxX, MaxY ] """ self._boundaries = convBoundary if origBoundary is None: self._boundaries_orig = self._boundaries else: self._boundaries_orig = origBoundary
[ "def", "set_boundaries", "(", "self", ",", "convBoundary", ",", "origBoundary", "=", "None", ")", ":", "self", ".", "_boundaries", "=", "convBoundary", "if", "origBoundary", "is", "None", ":", "self", ".", "_boundaries_orig", "=", "self", ".", "_boundaries", "else", ":", "self", ".", "_boundaries_orig", "=", "origBoundary" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/network/network.py#L3369-L3379
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/bayesian-methods/data_loader.py
python
load_mnist
(training_num=50000)
return X, Y, X_test, Y_test
Load mnist dataset
Load mnist dataset
[ "Load", "mnist", "dataset" ]
def load_mnist(training_num=50000): """Load mnist dataset""" data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from %s to %s' % (origin, data_path)) ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f: f.write(u.read()) print('Done!') dat = numpy.load(data_path) X = (dat['X'][:training_num] / 126.0).astype('float32') Y = dat['Y'][:training_num] X_test = (dat['X_test'] / 126.0).astype('float32') Y_test = dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test, Y_test
[ "def", "load_mnist", "(", "training_num", "=", "50000", ")", ":", "data_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "'__file__'", ")", ")", ",", "'mnist.npz'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "data_path", ")", ":", "from", "six", ".", "moves", "import", "urllib", "origin", "=", "(", "'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz'", ")", "print", "(", "'Downloading data from %s to %s'", "%", "(", "origin", ",", "data_path", ")", ")", "ctx", "=", "ssl", ".", "_create_unverified_context", "(", ")", "with", "urllib", ".", "request", ".", "urlopen", "(", "origin", ",", "context", "=", "ctx", ")", "as", "u", ",", "open", "(", "data_path", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "u", ".", "read", "(", ")", ")", "print", "(", "'Done!'", ")", "dat", "=", "numpy", ".", "load", "(", "data_path", ")", "X", "=", "(", "dat", "[", "'X'", "]", "[", ":", "training_num", "]", "/", "126.0", ")", ".", "astype", "(", "'float32'", ")", "Y", "=", "dat", "[", "'Y'", "]", "[", ":", "training_num", "]", "X_test", "=", "(", "dat", "[", "'X_test'", "]", "/", "126.0", ")", ".", "astype", "(", "'float32'", ")", "Y_test", "=", "dat", "[", "'Y_test'", "]", "Y", "=", "Y", ".", "reshape", "(", "(", "Y", ".", "shape", "[", "0", "]", ",", ")", ")", "Y_test", "=", "Y_test", ".", "reshape", "(", "(", "Y_test", ".", "shape", "[", "0", "]", ",", ")", ")", "return", "X", ",", "Y", ",", "X_test", ",", "Y_test" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/bayesian-methods/data_loader.py#L24-L44
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Tools/webchecker/tktools.py
python
test
()
Test make_text_box(), make_form_entry(), flatten(), boolean().
Test make_text_box(), make_form_entry(), flatten(), boolean().
[ "Test", "make_text_box", "()", "make_form_entry", "()", "flatten", "()", "boolean", "()", "." ]
def test(): """Test make_text_box(), make_form_entry(), flatten(), boolean().""" import sys root = Tk() entry, eframe = make_form_entry(root, 'Boolean:') text, tframe = make_text_box(root) def enter(event, entry=entry, text=text): s = boolean(entry.get()) and '\nyes' or '\nno' text.insert('end', s) entry.bind('<Return>', enter) entry.insert(END, flatten(sys.argv)) root.mainloop()
[ "def", "test", "(", ")", ":", "import", "sys", "root", "=", "Tk", "(", ")", "entry", ",", "eframe", "=", "make_form_entry", "(", "root", ",", "'Boolean:'", ")", "text", ",", "tframe", "=", "make_text_box", "(", "root", ")", "def", "enter", "(", "event", ",", "entry", "=", "entry", ",", "text", "=", "text", ")", ":", "s", "=", "boolean", "(", "entry", ".", "get", "(", ")", ")", "and", "'\\nyes'", "or", "'\\nno'", "text", ".", "insert", "(", "'end'", ",", "s", ")", "entry", ".", "bind", "(", "'<Return>'", ",", "enter", ")", "entry", ".", "insert", "(", "END", ",", "flatten", "(", "sys", ".", "argv", ")", ")", "root", ".", "mainloop", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Tools/webchecker/tktools.py#L351-L362
rbgirshick/caffe-fast-rcnn
28a579eaf0668850705598b3075b8969f22226d9
scripts/cpp_lint.py
python
CheckSpacingForFunctionCall
(filename, line, linenum, error)
Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, line, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. line: The text of the line to check. linenum: The number of the line to check. error: The function to call with any errors found. """ # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)): error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "line", ",", "linenum", ",", "error", ")", ":", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have their own, more liberal conventions - we", "# first see if we should be looking inside such an expression for a", "# function call, to which we can apply more strict standards.", "fncall", "=", "line", "# if there's no control flow construct, look at whole line", "for", "pattern", "in", "(", "r'\\bif\\s*\\((.*)\\)\\s*{'", ",", "r'\\bfor\\s*\\((.*)\\)\\s*{'", ",", "r'\\bwhile\\s*\\((.*)\\)\\s*[{;]'", ",", "r'\\bswitch\\s*\\((.*)\\)\\s*{'", ")", ":", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "match", ":", "fncall", "=", "match", ".", "group", "(", "1", ")", "# look inside the parens for function calls", "break", "# Except in if/for/while/switch, there should never be space", "# immediately inside parens (eg \"f( 3, 4 )\"). We make an exception", "# for nested parens ( (a+b) + c ). Likewise, there should never be", "# a space before a ( when it's a function argument. I assume it's a", "# function argument when the char before the whitespace is legal in", "# a function name (alnum + _) and we're not starting a macro. Also ignore", "# pointers and references to arrays and functions coz they're too tricky:", "# we use a very simple way to recognize these:", "# \" (something)(maybe-something)\" or", "# \" (something)(maybe-something,\" or", "# \" (something)[something]\"", "# Note that we assume the contents of [] to be short enough that", "# they'll never need to wrap.", "if", "(", "# Ignore control structures.", "not", "Search", "(", "r'\\b(if|for|while|switch|return|new|delete|catch|sizeof)\\b'", ",", "fncall", ")", "and", "# Ignore pointers/references to functions.", "not", "Search", "(", "r' \\([^)]+\\)\\([^)]*(\\)|,$)'", ",", "fncall", ")", "and", "# Ignore pointers/references to arrays.", "not", "Search", "(", "r' \\([^)]+\\)\\[[^\\]]+\\]'", ",", "fncall", ")", ")", ":", "if", "Search", "(", "r'\\w\\s*\\(\\s(?!\\s*\\\\$)'", ",", "fncall", ")", ":", "# a ( used for a fn call", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space after ( in function call'", ")", "elif", "Search", "(", "r'\\(\\s+(?!(\\s*\\\\)|\\()'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space after ('", ")", "if", "(", "Search", "(", "r'\\w\\s+\\('", ",", "fncall", ")", "and", "not", "Search", "(", "r'#\\s*define|typedef'", ",", "fncall", ")", "and", "not", "Search", "(", "r'\\w\\s+\\((\\w+::)*\\*\\w+\\)\\('", ",", "fncall", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "4", ",", "'Extra space before ( in function call'", ")", "# If the ) is followed only by a newline or a { + newline, assume it's", "# part of a control statement (if/while/etc), and don't complain", "if", "Search", "(", "r'[^)]\\s+\\)\\s*[^{\\s]'", ",", "fncall", ")", ":", "# If the closing parenthesis is preceded by only whitespaces,", "# try to give a more descriptive error message.", "if", "Search", "(", "r'^\\s+\\)'", ",", "fncall", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Closing ) should be moved to the previous line'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/parens'", ",", "2", ",", "'Extra space before )'", ")" ]
https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L2301-L2366
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
utils/vim-lldb/python-vim-lldb/vim_panes.py
python
goto_window
(nr)
go to window number nr
go to window number nr
[ "go", "to", "window", "number", "nr" ]
def goto_window(nr): """ go to window number nr""" if nr != winnr(): vim.command(str(nr) + ' wincmd w')
[ "def", "goto_window", "(", "nr", ")", ":", "if", "nr", "!=", "winnr", "(", ")", ":", "vim", ".", "command", "(", "str", "(", "nr", ")", "+", "' wincmd w'", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/utils/vim-lldb/python-vim-lldb/vim_panes.py#L123-L126
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/generator/make.py
python
QuoteIfNecessary
(string)
return string
TODO: Should this ideally be replaced with one or more of the above functions?
TODO: Should this ideally be replaced with one or more of the above functions?
[ "TODO", ":", "Should", "this", "ideally", "be", "replaced", "with", "one", "or", "more", "of", "the", "above", "functions?" ]
def QuoteIfNecessary(string): """TODO: Should this ideally be replaced with one or more of the above functions?""" if '"' in string: string = '"' + string.replace('"', '\\"') + '"' return string
[ "def", "QuoteIfNecessary", "(", "string", ")", ":", "if", "'\"'", "in", "string", ":", "string", "=", "'\"'", "+", "string", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "+", "'\"'", "return", "string" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/make.py#L600-L605
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/generator.py
python
_CppSourceFileWriter.gen_op_msg_request_serializer_method
(self, struct)
Generate the serialzer method definition for OpMsgRequest.
Generate the serialzer method definition for OpMsgRequest.
[ "Generate", "the", "serialzer", "method", "definition", "for", "OpMsgRequest", "." ]
def gen_op_msg_request_serializer_method(self, struct): # type: (ast.Struct) -> None """Generate the serialzer method definition for OpMsgRequest.""" # pylint: disable=invalid-name if not isinstance(struct, ast.Command): return struct_type_info = struct_types.get_struct_info(struct) with self._block('%s {' % (struct_type_info.get_op_msg_request_serializer_method().get_definition()), '}'): self._writer.write_line('BSONObjBuilder localBuilder;') with self._block('{', '}'): self._writer.write_line('BSONObjBuilder* builder = &localBuilder;') self._gen_serializer_methods_common(struct, True) self._writer.write_line('OpMsgRequest request;') self._writer.write_line('request.body = localBuilder.obj();') self._gen_doc_sequence_serializer(struct) self._writer.write_line('return request;')
[ "def", "gen_op_msg_request_serializer_method", "(", "self", ",", "struct", ")", ":", "# type: (ast.Struct) -> None", "# pylint: disable=invalid-name", "if", "not", "isinstance", "(", "struct", ",", "ast", ".", "Command", ")", ":", "return", "struct_type_info", "=", "struct_types", ".", "get_struct_info", "(", "struct", ")", "with", "self", ".", "_block", "(", "'%s {'", "%", "(", "struct_type_info", ".", "get_op_msg_request_serializer_method", "(", ")", ".", "get_definition", "(", ")", ")", ",", "'}'", ")", ":", "self", ".", "_writer", ".", "write_line", "(", "'BSONObjBuilder localBuilder;'", ")", "with", "self", ".", "_block", "(", "'{'", ",", "'}'", ")", ":", "self", ".", "_writer", ".", "write_line", "(", "'BSONObjBuilder* builder = &localBuilder;'", ")", "self", ".", "_gen_serializer_methods_common", "(", "struct", ",", "True", ")", "self", ".", "_writer", ".", "write_line", "(", "'OpMsgRequest request;'", ")", "self", ".", "_writer", ".", "write_line", "(", "'request.body = localBuilder.obj();'", ")", "self", ".", "_gen_doc_sequence_serializer", "(", "struct", ")", "self", ".", "_writer", ".", "write_line", "(", "'return request;'", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/generator.py#L1308-L1332
TheLegendAli/DeepLab-Context
fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c
scripts/cpp_lint.py
python
CheckCheck
(filename, clean_lines, linenum, error)
Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks the use of CHECK and EXPECT macros.
[ "Checks", "the", "use", "of", "CHECK", "and", "EXPECT", "macros", "." ]
def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided check_macro = None start_pos = -1 for macro in _CHECK_MACROS: i = lines[linenum].find(macro) if i >= 0: check_macro = macro # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum]) if not matched: continue start_pos = len(matched.group(1)) break if not check_macro or start_pos < 0: # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')') if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator))
[ "def", "CheckCheck", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Decide the set of replacement macros that should be suggested", "lines", "=", "clean_lines", ".", "elided", "check_macro", "=", "None", "start_pos", "=", "-", "1", "for", "macro", "in", "_CHECK_MACROS", ":", "i", "=", "lines", "[", "linenum", "]", ".", "find", "(", "macro", ")", "if", "i", ">=", "0", ":", "check_macro", "=", "macro", "# Find opening parenthesis. Do a regular expression match here", "# to make sure that we are matching the expected CHECK macro, as", "# opposed to some other macro that happens to contain the CHECK", "# substring.", "matched", "=", "Match", "(", "r'^(.*\\b'", "+", "check_macro", "+", "r'\\s*)\\('", ",", "lines", "[", "linenum", "]", ")", "if", "not", "matched", ":", "continue", "start_pos", "=", "len", "(", "matched", ".", "group", "(", "1", ")", ")", "break", "if", "not", "check_macro", "or", "start_pos", "<", "0", ":", "# Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'", "return", "# Find end of the boolean expression by matching parentheses", "(", "last_line", ",", "end_line", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "start_pos", ")", "if", "end_pos", "<", "0", ":", "return", "if", "linenum", "==", "end_line", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "end_pos", "-", "1", "]", "else", ":", "expression", "=", "lines", "[", "linenum", "]", "[", "start_pos", "+", "1", ":", "]", "for", "i", "in", "xrange", "(", "linenum", "+", "1", ",", "end_line", ")", ":", "expression", "+=", "lines", "[", "i", "]", "expression", "+=", "last_line", "[", "0", ":", "end_pos", "-", "1", "]", "# Parse expression so that we can take parentheses into account.", "# This avoids false positives for inputs like \"CHECK((a < 4) == b)\",", "# which is not replaceable by CHECK_LE.", "lhs", "=", "''", "rhs", "=", "''", "operator", "=", "None", "while", "expression", ":", "matched", "=", "Match", "(", "r'^\\s*(<<|<<=|>>|>>=|->\\*|->|&&|\\|\\||'", "r'==|!=|>=|>|<=|<|\\()(.*)$'", ",", "expression", ")", "if", "matched", ":", "token", "=", "matched", ".", "group", "(", "1", ")", "if", "token", "==", "'('", ":", "# Parenthesized operand", "expression", "=", "matched", ".", "group", "(", "2", ")", "(", "end", ",", "_", ")", "=", "FindEndOfExpressionInLine", "(", "expression", ",", "0", ",", "1", ",", "'('", ",", "')'", ")", "if", "end", "<", "0", ":", "return", "# Unmatched parenthesis", "lhs", "+=", "'('", "+", "expression", "[", "0", ":", "end", "]", "expression", "=", "expression", "[", "end", ":", "]", "elif", "token", "in", "(", "'&&'", ",", "'||'", ")", ":", "# Logical and/or operators. This means the expression", "# contains more than one term, for example:", "# CHECK(42 < a && a < b);", "#", "# These are not replaceable with CHECK_LE, so bail out early.", "return", "elif", "token", "in", "(", "'<<'", ",", "'<<='", ",", "'>>'", ",", "'>>='", ",", "'->*'", ",", "'->'", ")", ":", "# Non-relational operator", "lhs", "+=", "token", "expression", "=", "matched", ".", "group", "(", "2", ")", "else", ":", "# Relational operator", "operator", "=", "token", "rhs", "=", "matched", ".", "group", "(", "2", ")", "break", "else", ":", "# Unparenthesized operand. Instead of appending to lhs one character", "# at a time, we do another regular expression match to consume several", "# characters at once if possible. Trivial benchmark shows that this", "# is more efficient when the operands are longer than a single", "# character, which is generally the case.", "matched", "=", "Match", "(", "r'^([^-=!<>()&|]+)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "matched", "=", "Match", "(", "r'^(\\s*\\S)(.*)$'", ",", "expression", ")", "if", "not", "matched", ":", "break", "lhs", "+=", "matched", ".", "group", "(", "1", ")", "expression", "=", "matched", ".", "group", "(", "2", ")", "# Only apply checks if we got all parts of the boolean expression", "if", "not", "(", "lhs", "and", "operator", "and", "rhs", ")", ":", "return", "# Check that rhs do not contain logical operators. We already know", "# that lhs is fine since the loop above parses out && and ||.", "if", "rhs", ".", "find", "(", "'&&'", ")", ">", "-", "1", "or", "rhs", ".", "find", "(", "'||'", ")", ">", "-", "1", ":", "return", "# At least one of the operands must be a constant literal. This is", "# to avoid suggesting replacements for unprintable things like", "# CHECK(variable != iterator)", "#", "# The following pattern matches decimal, hex integers, strings, and", "# characters (in that order).", "lhs", "=", "lhs", ".", "strip", "(", ")", "rhs", "=", "rhs", ".", "strip", "(", ")", "match_constant", "=", "r'^([-+]?(\\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|\".*\"|\\'.*\\')$'", "if", "Match", "(", "match_constant", ",", "lhs", ")", "or", "Match", "(", "match_constant", ",", "rhs", ")", ":", "# Note: since we know both lhs and rhs, we can provide a more", "# descriptive error message like:", "# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)", "# Instead of:", "# Consider using CHECK_EQ instead of CHECK(a == b)", "#", "# We are still keeping the less descriptive message because if lhs", "# or rhs gets long, the error message might become unreadable.", "error", "(", "filename", ",", "linenum", ",", "'readability/check'", ",", "2", ",", "'Consider using %s instead of %s(a %s b)'", "%", "(", "_CHECK_REPLACEMENT", "[", "check_macro", "]", "[", "operator", "]", ",", "check_macro", ",", "operator", ")", ")" ]
https://github.com/TheLegendAli/DeepLab-Context/blob/fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c/scripts/cpp_lint.py#L3278-L3402
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/predict-the-winner.py
python
Solution.PredictTheWinner
(self, nums)
return dp[-1] >= 0
:type nums: List[int] :rtype: bool
:type nums: List[int] :rtype: bool
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "bool" ]
def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) % 2 == 0 or len(nums) == 1: return True dp = [0] * len(nums) for i in reversed(xrange(len(nums))): dp[i] = nums[i] for j in xrange(i+1, len(nums)): dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1]) return dp[-1] >= 0
[ "def", "PredictTheWinner", "(", "self", ",", "nums", ")", ":", "if", "len", "(", "nums", ")", "%", "2", "==", "0", "or", "len", "(", "nums", ")", "==", "1", ":", "return", "True", "dp", "=", "[", "0", "]", "*", "len", "(", "nums", ")", "for", "i", "in", "reversed", "(", "xrange", "(", "len", "(", "nums", ")", ")", ")", ":", "dp", "[", "i", "]", "=", "nums", "[", "i", "]", "for", "j", "in", "xrange", "(", "i", "+", "1", ",", "len", "(", "nums", ")", ")", ":", "dp", "[", "j", "]", "=", "max", "(", "nums", "[", "i", "]", "-", "dp", "[", "j", "]", ",", "nums", "[", "j", "]", "-", "dp", "[", "j", "-", "1", "]", ")", "return", "dp", "[", "-", "1", "]", ">=", "0" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/predict-the-winner.py#L5-L19
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/utils/tf_inspect.py
python
getargspec
(obj)
return _getargspec(type(target).__call__)
TFDecorator-aware replacement for `inspect.getargspec`. Note: `getfullargspec` is recommended as the python 2/3 compatible replacement for this function. Args: obj: A function, partial function, or callable object, possibly decorated. Returns: The `ArgSpec` that describes the signature of the outermost decorator that changes the callable's signature, or the `ArgSpec` that describes the object if not decorated. Raises: ValueError: When callable's signature can not be expressed with ArgSpec. TypeError: For objects of unsupported types.
TFDecorator-aware replacement for `inspect.getargspec`.
[ "TFDecorator", "-", "aware", "replacement", "for", "inspect", ".", "getargspec", "." ]
def getargspec(obj): """TFDecorator-aware replacement for `inspect.getargspec`. Note: `getfullargspec` is recommended as the python 2/3 compatible replacement for this function. Args: obj: A function, partial function, or callable object, possibly decorated. Returns: The `ArgSpec` that describes the signature of the outermost decorator that changes the callable's signature, or the `ArgSpec` that describes the object if not decorated. Raises: ValueError: When callable's signature can not be expressed with ArgSpec. TypeError: For objects of unsupported types. """ if isinstance(obj, functools.partial): return _get_argspec_for_partial(obj) decorators, target = tf_decorator.unwrap(obj) spec = next((d.decorator_argspec for d in decorators if d.decorator_argspec is not None), None) if spec: return spec try: # Python3 will handle most callables here (not partial). return _getargspec(target) except TypeError: pass if isinstance(target, type): try: return _getargspec(target.__init__) except TypeError: pass try: return _getargspec(target.__new__) except TypeError: pass # The `type(target)` ensures that if a class is received we don't return # the signature of its __call__ method. return _getargspec(type(target).__call__)
[ "def", "getargspec", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "functools", ".", "partial", ")", ":", "return", "_get_argspec_for_partial", "(", "obj", ")", "decorators", ",", "target", "=", "tf_decorator", ".", "unwrap", "(", "obj", ")", "spec", "=", "next", "(", "(", "d", ".", "decorator_argspec", "for", "d", "in", "decorators", "if", "d", ".", "decorator_argspec", "is", "not", "None", ")", ",", "None", ")", "if", "spec", ":", "return", "spec", "try", ":", "# Python3 will handle most callables here (not partial).", "return", "_getargspec", "(", "target", ")", "except", "TypeError", ":", "pass", "if", "isinstance", "(", "target", ",", "type", ")", ":", "try", ":", "return", "_getargspec", "(", "target", ".", "__init__", ")", "except", "TypeError", ":", "pass", "try", ":", "return", "_getargspec", "(", "target", ".", "__new__", ")", "except", "TypeError", ":", "pass", "# The `type(target)` ensures that if a class is received we don't return", "# the signature of its __call__ method.", "return", "_getargspec", "(", "type", "(", "target", ")", ".", "__call__", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/tf_inspect.py#L93-L142
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/reshape/reshape.py
python
stack
(frame, level=-1, dropna=True)
return frame._constructor_sliced(new_values, index=new_index)
Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series
Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index
[ "Convert", "DataFrame", "to", "Series", "with", "multi", "-", "level", "Index", ".", "Columns", "become", "the", "second", "level", "of", "the", "resulting", "hierarchical", "index" ]
def stack(frame, level=-1, dropna=True): """ Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series """ def factorize(index): if index.is_unique: return index, np.arange(len(index)) codes, categories = factorize_from_iterable(index) return categories, codes N, K = frame.shape # Will also convert negative level numbers and check if out of bounds. level_num = frame.columns._get_level_number(level) if isinstance(frame.columns, MultiIndex): return _stack_multi_columns(frame, level_num=level_num, dropna=dropna) elif isinstance(frame.index, MultiIndex): new_levels = list(frame.index.levels) new_codes = [lab.repeat(K) for lab in frame.index.codes] clev, clab = factorize(frame.columns) new_levels.append(clev) new_codes.append(np.tile(clab, N).ravel()) new_names = list(frame.index.names) new_names.append(frame.columns.name) new_index = MultiIndex( levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False ) else: levels, (ilab, clab) = zip(*map(factorize, (frame.index, frame.columns))) codes = ilab.repeat(K), np.tile(clab, N).ravel() new_index = MultiIndex( levels=levels, codes=codes, names=[frame.index.name, frame.columns.name], verify_integrity=False, ) if frame._is_homogeneous_type: # For homogeneous EAs, frame.values will coerce to object. So # we concatenate instead. dtypes = list(frame.dtypes.values) dtype = dtypes[0] if is_extension_array_dtype(dtype): arr = dtype.construct_array_type() new_values = arr._concat_same_type( [col._values for _, col in frame.items()] ) new_values = _reorder_for_extension_array_stack(new_values, N, K) else: # homogeneous, non-EA new_values = frame.values.ravel() else: # non-homogeneous new_values = frame.values.ravel() if dropna: mask = notna(new_values) new_values = new_values[mask] new_index = new_index[mask] return frame._constructor_sliced(new_values, index=new_index)
[ "def", "stack", "(", "frame", ",", "level", "=", "-", "1", ",", "dropna", "=", "True", ")", ":", "def", "factorize", "(", "index", ")", ":", "if", "index", ".", "is_unique", ":", "return", "index", ",", "np", ".", "arange", "(", "len", "(", "index", ")", ")", "codes", ",", "categories", "=", "factorize_from_iterable", "(", "index", ")", "return", "categories", ",", "codes", "N", ",", "K", "=", "frame", ".", "shape", "# Will also convert negative level numbers and check if out of bounds.", "level_num", "=", "frame", ".", "columns", ".", "_get_level_number", "(", "level", ")", "if", "isinstance", "(", "frame", ".", "columns", ",", "MultiIndex", ")", ":", "return", "_stack_multi_columns", "(", "frame", ",", "level_num", "=", "level_num", ",", "dropna", "=", "dropna", ")", "elif", "isinstance", "(", "frame", ".", "index", ",", "MultiIndex", ")", ":", "new_levels", "=", "list", "(", "frame", ".", "index", ".", "levels", ")", "new_codes", "=", "[", "lab", ".", "repeat", "(", "K", ")", "for", "lab", "in", "frame", ".", "index", ".", "codes", "]", "clev", ",", "clab", "=", "factorize", "(", "frame", ".", "columns", ")", "new_levels", ".", "append", "(", "clev", ")", "new_codes", ".", "append", "(", "np", ".", "tile", "(", "clab", ",", "N", ")", ".", "ravel", "(", ")", ")", "new_names", "=", "list", "(", "frame", ".", "index", ".", "names", ")", "new_names", ".", "append", "(", "frame", ".", "columns", ".", "name", ")", "new_index", "=", "MultiIndex", "(", "levels", "=", "new_levels", ",", "codes", "=", "new_codes", ",", "names", "=", "new_names", ",", "verify_integrity", "=", "False", ")", "else", ":", "levels", ",", "(", "ilab", ",", "clab", ")", "=", "zip", "(", "*", "map", "(", "factorize", ",", "(", "frame", ".", "index", ",", "frame", ".", "columns", ")", ")", ")", "codes", "=", "ilab", ".", "repeat", "(", "K", ")", ",", "np", ".", "tile", "(", "clab", ",", "N", ")", ".", "ravel", "(", ")", "new_index", "=", "MultiIndex", "(", "levels", "=", "levels", ",", "codes", "=", "codes", ",", "names", "=", "[", "frame", ".", "index", ".", "name", ",", "frame", ".", "columns", ".", "name", "]", ",", "verify_integrity", "=", "False", ",", ")", "if", "frame", ".", "_is_homogeneous_type", ":", "# For homogeneous EAs, frame.values will coerce to object. So", "# we concatenate instead.", "dtypes", "=", "list", "(", "frame", ".", "dtypes", ".", "values", ")", "dtype", "=", "dtypes", "[", "0", "]", "if", "is_extension_array_dtype", "(", "dtype", ")", ":", "arr", "=", "dtype", ".", "construct_array_type", "(", ")", "new_values", "=", "arr", ".", "_concat_same_type", "(", "[", "col", ".", "_values", "for", "_", ",", "col", "in", "frame", ".", "items", "(", ")", "]", ")", "new_values", "=", "_reorder_for_extension_array_stack", "(", "new_values", ",", "N", ",", "K", ")", "else", ":", "# homogeneous, non-EA", "new_values", "=", "frame", ".", "values", ".", "ravel", "(", ")", "else", ":", "# non-homogeneous", "new_values", "=", "frame", ".", "values", ".", "ravel", "(", ")", "if", "dropna", ":", "mask", "=", "notna", "(", "new_values", ")", "new_values", "=", "new_values", "[", "mask", "]", "new_index", "=", "new_index", "[", "mask", "]", "return", "frame", ".", "_constructor_sliced", "(", "new_values", ",", "index", "=", "new_index", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/reshape/reshape.py#L493-L564
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HtmlColourCell.__init__
(self, *args, **kwargs)
__init__(self, Colour clr, int flags=HTML_CLR_FOREGROUND) -> HtmlColourCell
__init__(self, Colour clr, int flags=HTML_CLR_FOREGROUND) -> HtmlColourCell
[ "__init__", "(", "self", "Colour", "clr", "int", "flags", "=", "HTML_CLR_FOREGROUND", ")", "-", ">", "HtmlColourCell" ]
def __init__(self, *args, **kwargs): """__init__(self, Colour clr, int flags=HTML_CLR_FOREGROUND) -> HtmlColourCell""" _html.HtmlColourCell_swiginit(self,_html.new_HtmlColourCell(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_html", ".", "HtmlColourCell_swiginit", "(", "self", ",", "_html", ".", "new_HtmlColourCell", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L877-L879
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PolDiffILLReduction.py
python
PolDiffILLReduction._read_experiment_properties
(self, ws)
Reads the user-provided dictionary that contains sample geometry (type, dimensions) and experimental conditions, such as the beam size and calculates derived parameters.
Reads the user-provided dictionary that contains sample geometry (type, dimensions) and experimental conditions, such as the beam size and calculates derived parameters.
[ "Reads", "the", "user", "-", "provided", "dictionary", "that", "contains", "sample", "geometry", "(", "type", "dimensions", ")", "and", "experimental", "conditions", "such", "as", "the", "beam", "size", "and", "calculates", "derived", "parameters", "." ]
def _read_experiment_properties(self, ws): """Reads the user-provided dictionary that contains sample geometry (type, dimensions) and experimental conditions, such as the beam size and calculates derived parameters.""" self._sampleAndEnvironmentProperties = self.getProperty('SampleAndEnvironmentProperties').value if 'InitialEnergy' not in self._sampleAndEnvironmentProperties: h = physical_constants['Planck constant'][0] # in m^2 kg / s neutron_mass = physical_constants['neutron mass'][0] # in kg wavelength = mtd[ws][0].getRun().getLogData('monochromator.wavelength').value * 1e-10 # in m joules_to_mev = 1e3 / physical_constants['electron volt'][0] self._sampleAndEnvironmentProperties['InitialEnergy'] = \ joules_to_mev * math.pow(h / wavelength, 2) / (2 * neutron_mass) if 'NMoles' not in self._sampleAndEnvironmentProperties and self.getProperty('AbsoluteNormalisation').value: sample_mass = self._sampleAndEnvironmentProperties['SampleMass'].value formula_unit_mass = self._sampleAndEnvironmentProperties['FormulaUnitMass'].value self._sampleAndEnvironmentProperties['NMoles'] = (sample_mass / formula_unit_mass)
[ "def", "_read_experiment_properties", "(", "self", ",", "ws", ")", ":", "self", ".", "_sampleAndEnvironmentProperties", "=", "self", ".", "getProperty", "(", "'SampleAndEnvironmentProperties'", ")", ".", "value", "if", "'InitialEnergy'", "not", "in", "self", ".", "_sampleAndEnvironmentProperties", ":", "h", "=", "physical_constants", "[", "'Planck constant'", "]", "[", "0", "]", "# in m^2 kg / s", "neutron_mass", "=", "physical_constants", "[", "'neutron mass'", "]", "[", "0", "]", "# in kg", "wavelength", "=", "mtd", "[", "ws", "]", "[", "0", "]", ".", "getRun", "(", ")", ".", "getLogData", "(", "'monochromator.wavelength'", ")", ".", "value", "*", "1e-10", "# in m", "joules_to_mev", "=", "1e3", "/", "physical_constants", "[", "'electron volt'", "]", "[", "0", "]", "self", ".", "_sampleAndEnvironmentProperties", "[", "'InitialEnergy'", "]", "=", "joules_to_mev", "*", "math", ".", "pow", "(", "h", "/", "wavelength", ",", "2", ")", "/", "(", "2", "*", "neutron_mass", ")", "if", "'NMoles'", "not", "in", "self", ".", "_sampleAndEnvironmentProperties", "and", "self", ".", "getProperty", "(", "'AbsoluteNormalisation'", ")", ".", "value", ":", "sample_mass", "=", "self", ".", "_sampleAndEnvironmentProperties", "[", "'SampleMass'", "]", ".", "value", "formula_unit_mass", "=", "self", ".", "_sampleAndEnvironmentProperties", "[", "'FormulaUnitMass'", "]", ".", "value", "self", ".", "_sampleAndEnvironmentProperties", "[", "'NMoles'", "]", "=", "(", "sample_mass", "/", "formula_unit_mass", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/PolDiffILLReduction.py#L1080-L1095
apple/swift-clang
d7403439fc6641751840b723e7165fb02f52db95
bindings/python/clang/cindex.py
python
Cursor.exception_specification_kind
(self)
return self._exception_specification_kind
Retrieve the exception specification kind, which is one of the values from the ExceptionSpecificationKind enumeration.
Retrieve the exception specification kind, which is one of the values from the ExceptionSpecificationKind enumeration.
[ "Retrieve", "the", "exception", "specification", "kind", "which", "is", "one", "of", "the", "values", "from", "the", "ExceptionSpecificationKind", "enumeration", "." ]
def exception_specification_kind(self): ''' Retrieve the exception specification kind, which is one of the values from the ExceptionSpecificationKind enumeration. ''' if not hasattr(self, '_exception_specification_kind'): exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self) self._exception_specification_kind = ExceptionSpecificationKind.from_id(exc_kind) return self._exception_specification_kind
[ "def", "exception_specification_kind", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_exception_specification_kind'", ")", ":", "exc_kind", "=", "conf", ".", "lib", ".", "clang_getCursorExceptionSpecificationType", "(", "self", ")", "self", ".", "_exception_specification_kind", "=", "ExceptionSpecificationKind", ".", "from_id", "(", "exc_kind", ")", "return", "self", ".", "_exception_specification_kind" ]
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L1676-L1685
nest/nest-simulator
f2623eb78518cdbd55e77e0ed486bf1111bcb62f
pynest/nest/server/hl_api_server.py
python
do_call
(call_name, args=[], kwargs={})
return combine(call_name, response)
Call a PYNEST function or execute a script within the server. If the server is run serially (i.e., without MPI), this function will do one of two things: If call_name is "exec", it will execute the script given in args via do_exec(). If call_name is the name of a PyNEST API function, it will call that function and pass args and kwargs to it. If the server is run with MPI, this function will first communicate the call type ("exec" or API call) and the args and kwargs to all worker processes. Only then will it execute the call in the same way as described above for the serial case. After the call, all worker responses are collected, combined and returned. Please note that this function must only be called on the master process (i.e., the task with rank 0) in a distributed scenario.
Call a PYNEST function or execute a script within the server.
[ "Call", "a", "PYNEST", "function", "or", "execute", "a", "script", "within", "the", "server", "." ]
def do_call(call_name, args=[], kwargs={}): """Call a PYNEST function or execute a script within the server. If the server is run serially (i.e., without MPI), this function will do one of two things: If call_name is "exec", it will execute the script given in args via do_exec(). If call_name is the name of a PyNEST API function, it will call that function and pass args and kwargs to it. If the server is run with MPI, this function will first communicate the call type ("exec" or API call) and the args and kwargs to all worker processes. Only then will it execute the call in the same way as described above for the serial case. After the call, all worker responses are collected, combined and returned. Please note that this function must only be called on the master process (i.e., the task with rank 0) in a distributed scenario. """ if mpi_comm is not None: assert mpi_comm.Get_rank() == 0 if mpi_comm is not None: log(call_name, 'sending call bcast') mpi_comm.bcast(call_name, root=0) data = (args, kwargs) log(call_name, f'sending data bcast, data={data}') mpi_comm.bcast(data, root=0) if call_name == "exec": master_response = do_exec(args, kwargs) else: call, args, kwargs = nestify(call_name, args, kwargs) log(call_name, f'local call, args={args}, kwargs={kwargs}') master_response = call(*args, **kwargs) response = [nest.serializable(master_response)] if mpi_comm is not None: log(call_name, 'waiting for response gather') response = mpi_comm.gather(response[0], root=0) log(call_name, f'received response gather, data={response}') return combine(call_name, response)
[ "def", "do_call", "(", "call_name", ",", "args", "=", "[", "]", ",", "kwargs", "=", "{", "}", ")", ":", "if", "mpi_comm", "is", "not", "None", ":", "assert", "mpi_comm", ".", "Get_rank", "(", ")", "==", "0", "if", "mpi_comm", "is", "not", "None", ":", "log", "(", "call_name", ",", "'sending call bcast'", ")", "mpi_comm", ".", "bcast", "(", "call_name", ",", "root", "=", "0", ")", "data", "=", "(", "args", ",", "kwargs", ")", "log", "(", "call_name", ",", "f'sending data bcast, data={data}'", ")", "mpi_comm", ".", "bcast", "(", "data", ",", "root", "=", "0", ")", "if", "call_name", "==", "\"exec\"", ":", "master_response", "=", "do_exec", "(", "args", ",", "kwargs", ")", "else", ":", "call", ",", "args", ",", "kwargs", "=", "nestify", "(", "call_name", ",", "args", ",", "kwargs", ")", "log", "(", "call_name", ",", "f'local call, args={args}, kwargs={kwargs}'", ")", "master_response", "=", "call", "(", "*", "args", ",", "*", "*", "kwargs", ")", "response", "=", "[", "nest", ".", "serializable", "(", "master_response", ")", "]", "if", "mpi_comm", "is", "not", "None", ":", "log", "(", "call_name", ",", "'waiting for response gather'", ")", "response", "=", "mpi_comm", ".", "gather", "(", "response", "[", "0", "]", ",", "root", "=", "0", ")", "log", "(", "call_name", ",", "f'received response gather, data={response}'", ")", "return", "combine", "(", "call_name", ",", "response", ")" ]
https://github.com/nest/nest-simulator/blob/f2623eb78518cdbd55e77e0ed486bf1111bcb62f/pynest/nest/server/hl_api_server.py#L115-L158
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/swift/utils/swift_build_support/swift_build_support/which.py
python
which
(cmd)
return out.rstrip()
Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None. Python 3.3+ provides this behavior via the shutil.which() function; see: https://docs.python.org/3.3/library/shutil.html#shutil.which We provide our own implementation because shutil.which() has not been backported to Python 2.7, which we support.
Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None.
[ "Return", "the", "path", "to", "an", "executable", "which", "would", "be", "run", "if", "the", "given", "cmd", "was", "called", ".", "If", "no", "cmd", "would", "be", "called", "return", "None", "." ]
def which(cmd): """ Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None. Python 3.3+ provides this behavior via the shutil.which() function; see: https://docs.python.org/3.3/library/shutil.html#shutil.which We provide our own implementation because shutil.which() has not been backported to Python 2.7, which we support. """ out = shell.capture(['which', cmd], dry_run=False, echo=False, optional=True) if out is None: return None return out.rstrip()
[ "def", "which", "(", "cmd", ")", ":", "out", "=", "shell", ".", "capture", "(", "[", "'which'", ",", "cmd", "]", ",", "dry_run", "=", "False", ",", "echo", "=", "False", ",", "optional", "=", "True", ")", "if", "out", "is", "None", ":", "return", "None", "return", "out", ".", "rstrip", "(", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/swift/utils/swift_build_support/swift_build_support/which.py#L26-L41
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py
python
declaration_t.attributes
(self)
return self._attributes
GCCXML attributes, set using __attribute__((gccxml("..."))) @type: str
GCCXML attributes, set using __attribute__((gccxml("...")))
[ "GCCXML", "attributes", "set", "using", "__attribute__", "((", "gccxml", "(", "...", ")))" ]
def attributes(self): """ GCCXML attributes, set using __attribute__((gccxml("..."))) @type: str """ return self._attributes
[ "def", "attributes", "(", "self", ")", ":", "return", "self", ".", "_attributes" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py#L277-L285
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/window/rolling.py
python
BaseWindow._apply
( self, func: Callable[..., Any], name: str | None = None, numba_cache_key: tuple[Callable, str] | None = None, **kwargs, )
Rolling statistical measure using supplied function. Designed to be used with passed-in Cython array-based functions. Parameters ---------- func : callable function to apply name : str, numba_cache_key : tuple caching key to be used to store a compiled numba func **kwargs additional arguments for rolling function and window function Returns ------- y : type of input
Rolling statistical measure using supplied function.
[ "Rolling", "statistical", "measure", "using", "supplied", "function", "." ]
def _apply( self, func: Callable[..., Any], name: str | None = None, numba_cache_key: tuple[Callable, str] | None = None, **kwargs, ): """ Rolling statistical measure using supplied function. Designed to be used with passed-in Cython array-based functions. Parameters ---------- func : callable function to apply name : str, numba_cache_key : tuple caching key to be used to store a compiled numba func **kwargs additional arguments for rolling function and window function Returns ------- y : type of input """ window_indexer = self._get_window_indexer() min_periods = ( self.min_periods if self.min_periods is not None else window_indexer.window_size ) def homogeneous_func(values: np.ndarray): # calculation function if values.size == 0: return values.copy() def calc(x): start, end = window_indexer.get_window_bounds( num_values=len(x), min_periods=min_periods, center=self.center, closed=self.closed, ) assert len(start) == len( end ), "these should be equal in length from get_window_bounds" return func(x, start, end, min_periods) with np.errstate(all="ignore"): if values.ndim > 1 and self.method == "single": result = np.apply_along_axis(calc, self.axis, values) else: result = calc(values) if numba_cache_key is not None: NUMBA_FUNC_CACHE[numba_cache_key] = func return result if self.method == "single": return self._apply_blockwise(homogeneous_func, name) else: return self._apply_tablewise(homogeneous_func, name)
[ "def", "_apply", "(", "self", ",", "func", ":", "Callable", "[", "...", ",", "Any", "]", ",", "name", ":", "str", "|", "None", "=", "None", ",", "numba_cache_key", ":", "tuple", "[", "Callable", ",", "str", "]", "|", "None", "=", "None", ",", "*", "*", "kwargs", ",", ")", ":", "window_indexer", "=", "self", ".", "_get_window_indexer", "(", ")", "min_periods", "=", "(", "self", ".", "min_periods", "if", "self", ".", "min_periods", "is", "not", "None", "else", "window_indexer", ".", "window_size", ")", "def", "homogeneous_func", "(", "values", ":", "np", ".", "ndarray", ")", ":", "# calculation function", "if", "values", ".", "size", "==", "0", ":", "return", "values", ".", "copy", "(", ")", "def", "calc", "(", "x", ")", ":", "start", ",", "end", "=", "window_indexer", ".", "get_window_bounds", "(", "num_values", "=", "len", "(", "x", ")", ",", "min_periods", "=", "min_periods", ",", "center", "=", "self", ".", "center", ",", "closed", "=", "self", ".", "closed", ",", ")", "assert", "len", "(", "start", ")", "==", "len", "(", "end", ")", ",", "\"these should be equal in length from get_window_bounds\"", "return", "func", "(", "x", ",", "start", ",", "end", ",", "min_periods", ")", "with", "np", ".", "errstate", "(", "all", "=", "\"ignore\"", ")", ":", "if", "values", ".", "ndim", ">", "1", "and", "self", ".", "method", "==", "\"single\"", ":", "result", "=", "np", ".", "apply_along_axis", "(", "calc", ",", "self", ".", "axis", ",", "values", ")", "else", ":", "result", "=", "calc", "(", "values", ")", "if", "numba_cache_key", "is", "not", "None", ":", "NUMBA_FUNC_CACHE", "[", "numba_cache_key", "]", "=", "func", "return", "result", "if", "self", ".", "method", "==", "\"single\"", ":", "return", "self", ".", "_apply_blockwise", "(", "homogeneous_func", ",", "name", ")", "else", ":", "return", "self", ".", "_apply_tablewise", "(", "homogeneous_func", ",", "name", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/window/rolling.py#L482-L547
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/Input/InputTree.py
python
InputTree.moveBlock
(self, path, new_index)
Moves the block to another position
Moves the block to another position
[ "Moves", "the", "block", "to", "another", "position" ]
def moveBlock(self, path, new_index): """ Moves the block to another position """ pinfo = self.path_map.get(path) if pinfo: pinfo.parent.moveChildBlock(pinfo.name, new_index)
[ "def", "moveBlock", "(", "self", ",", "path", ",", "new_index", ")", ":", "pinfo", "=", "self", ".", "path_map", ".", "get", "(", "path", ")", "if", "pinfo", ":", "pinfo", ".", "parent", ".", "moveChildBlock", "(", "pinfo", ".", "name", ",", "new_index", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputTree.py#L298-L304
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/extern/__init__.py
python
VendorImporter.load_module
(self, fullname)
Iterate over the search path to locate and load fullname.
Iterate over the search path to locate and load fullname.
[ "Iterate", "over", "the", "search", "path", "to", "locate", "and", "load", "fullname", "." ]
def load_module(self, fullname): """ Iterate over the search path to locate and load fullname. """ root, base, target = fullname.partition(self.root_name + '.') for prefix in self.search_path: try: extant = prefix + target __import__(extant) mod = sys.modules[extant] sys.modules[fullname] = mod return mod except ImportError: pass else: raise ImportError( "The '{target}' package is required; " "normally this is bundled with this package so if you get " "this warning, consult the packager of your " "distribution.".format(**locals()) )
[ "def", "load_module", "(", "self", ",", "fullname", ")", ":", "root", ",", "base", ",", "target", "=", "fullname", ".", "partition", "(", "self", ".", "root_name", "+", "'.'", ")", "for", "prefix", "in", "self", ".", "search_path", ":", "try", ":", "extant", "=", "prefix", "+", "target", "__import__", "(", "extant", ")", "mod", "=", "sys", ".", "modules", "[", "extant", "]", "sys", ".", "modules", "[", "fullname", "]", "=", "mod", "return", "mod", "except", "ImportError", ":", "pass", "else", ":", "raise", "ImportError", "(", "\"The '{target}' package is required; \"", "\"normally this is bundled with this package so if you get \"", "\"this warning, consult the packager of your \"", "\"distribution.\"", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/extern/__init__.py#L35-L55
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/selectionDataModel.py
python
Blocker.__enter__
(self)
Enter the 'blocked' state until the context is exited.
Enter the 'blocked' state until the context is exited.
[ "Enter", "the", "blocked", "state", "until", "the", "context", "is", "exited", "." ]
def __enter__(self): """Enter the 'blocked' state until the context is exited.""" self._count += 1
[ "def", "__enter__", "(", "self", ")", ":", "self", ".", "_count", "+=", "1" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L54-L57
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_vim.py
python
EditraCommander.DeleteSelection
(self)
Yank selection and delete it
Yank selection and delete it
[ "Yank", "selection", "and", "delete", "it" ]
def DeleteSelection(self): """Yank selection and delete it""" start, end = self._GetSelectionRange() self.stc.BeginUndoAction() self.YankSelection() self.stc.Clear() self._SetPos(start) self.stc.EndUndoAction()
[ "def", "DeleteSelection", "(", "self", ")", ":", "start", ",", "end", "=", "self", ".", "_GetSelectionRange", "(", ")", "self", ".", "stc", ".", "BeginUndoAction", "(", ")", "self", ".", "YankSelection", "(", ")", "self", ".", "stc", ".", "Clear", "(", ")", "self", ".", "_SetPos", "(", "start", ")", "self", ".", "stc", ".", "EndUndoAction", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_vim.py#L621-L628