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
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/commands.py
python
BuildExt.build_extension
(self, ext)
return _build_ext.build_ext.build_extension(self, ext)
Build C extension - with extended functionality The following features are added here: - ``ext.check_prerequisites`` is called before the extension is being built. See `Extension` for details. If the method does not exist, simply no check will be run. - The macros ``EXT_PACKAGE`` and ``EXT_MODULE`` will be filled (or unset) depending on the extensions name, but only if they are not already defined. :Parameters: `ext` : `Extension` The extension to build. If it's a pure ``distutils.core.Extension``, simply no prequisites check is applied. :Return: whatever ``distutils.command.build_ext.build_ext`` returns :Rtype: any
Build C extension - with extended functionality
[ "Build", "C", "extension", "-", "with", "extended", "functionality" ]
def build_extension(self, ext): """ Build C extension - with extended functionality The following features are added here: - ``ext.check_prerequisites`` is called before the extension is being built. See `Extension` for details. If the method does not exist, simply no check will be run. - The macros ``EXT_PACKAGE`` and ``EXT_MODULE`` will be filled (or unset) depending on the extensions name, but only if they are not already defined. :Parameters: `ext` : `Extension` The extension to build. If it's a pure ``distutils.core.Extension``, simply no prequisites check is applied. :Return: whatever ``distutils.command.build_ext.build_ext`` returns :Rtype: any """ # handle name macros macros = dict(ext.define_macros or ()) tup = ext.name.split('.') if len(tup) == 1: pkg, mod = None, tup[0] else: pkg, mod = '.'.join(tup[:-1]), tup[-1] if pkg is not None and 'EXT_PACKAGE' not in macros: ext.define_macros.append(('EXT_PACKAGE', pkg)) if 'EXT_MODULE' not in macros: ext.define_macros.append(('EXT_MODULE', mod)) if pkg is None: macros = dict(ext.undef_macros or ()) if 'EXT_PACKAGE' not in macros: ext.undef_macros.append('EXT_PACKAGE') # handle prereq checks try: checker = ext.check_prerequisites except AttributeError: pass else: if checker(self): log.info("Skipping %s extension" % ext.name) return return _build_ext.build_ext.build_extension(self, ext)
[ "def", "build_extension", "(", "self", ",", "ext", ")", ":", "# handle name macros", "macros", "=", "dict", "(", "ext", ".", "define_macros", "or", "(", ")", ")", "tup", "=", "ext", ".", "name", ".", "split", "(", "'.'", ")", "if", "len", "(", "tup", ")", "==", "1", ":", "pkg", ",", "mod", "=", "None", ",", "tup", "[", "0", "]", "else", ":", "pkg", ",", "mod", "=", "'.'", ".", "join", "(", "tup", "[", ":", "-", "1", "]", ")", ",", "tup", "[", "-", "1", "]", "if", "pkg", "is", "not", "None", "and", "'EXT_PACKAGE'", "not", "in", "macros", ":", "ext", ".", "define_macros", ".", "append", "(", "(", "'EXT_PACKAGE'", ",", "pkg", ")", ")", "if", "'EXT_MODULE'", "not", "in", "macros", ":", "ext", ".", "define_macros", ".", "append", "(", "(", "'EXT_MODULE'", ",", "mod", ")", ")", "if", "pkg", "is", "None", ":", "macros", "=", "dict", "(", "ext", ".", "undef_macros", "or", "(", ")", ")", "if", "'EXT_PACKAGE'", "not", "in", "macros", ":", "ext", ".", "undef_macros", ".", "append", "(", "'EXT_PACKAGE'", ")", "# handle prereq checks", "try", ":", "checker", "=", "ext", ".", "check_prerequisites", "except", "AttributeError", ":", "pass", "else", ":", "if", "checker", "(", "self", ")", ":", "log", ".", "info", "(", "\"Skipping %s extension\"", "%", "ext", ".", "name", ")", "return", "return", "_build_ext", ".", "build_ext", ".", "build_extension", "(", "self", ",", "ext", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/py_vulcanize/third_party/rjsmin/_setup/py3/commands.py#L198-L246
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py
python
NDFrame._add_series_or_dataframe_operations
(cls)
Add the series or dataframe only operations to the cls; evaluate the doc strings again.
Add the series or dataframe only operations to the cls; evaluate the doc strings again.
[ "Add", "the", "series", "or", "dataframe", "only", "operations", "to", "the", "cls", ";", "evaluate", "the", "doc", "strings", "again", "." ]
def _add_series_or_dataframe_operations(cls): """ Add the series or dataframe only operations to the cls; evaluate the doc strings again. """ from pandas.core.window import EWM, Expanding, Rolling, Window @Appender(Rolling.__doc__) def rolling( self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, ): axis = self._get_axis_number(axis) if win_type is not None: return Window( self, window=window, min_periods=min_periods, center=center, win_type=win_type, on=on, axis=axis, closed=closed, ) return Rolling( self, window=window, min_periods=min_periods, center=center, win_type=win_type, on=on, axis=axis, closed=closed, ) cls.rolling = rolling @Appender(Expanding.__doc__) def expanding(self, min_periods=1, center=False, axis=0): axis = self._get_axis_number(axis) return Expanding(self, min_periods=min_periods, center=center, axis=axis) cls.expanding = expanding @Appender(EWM.__doc__) def ewm( self, com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, ): axis = self._get_axis_number(axis) return EWM( self, com=com, span=span, halflife=halflife, alpha=alpha, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na, axis=axis, ) cls.ewm = ewm
[ "def", "_add_series_or_dataframe_operations", "(", "cls", ")", ":", "from", "pandas", ".", "core", ".", "window", "import", "EWM", ",", "Expanding", ",", "Rolling", ",", "Window", "@", "Appender", "(", "Rolling", ".", "__doc__", ")", "def", "rolling", "(", "self", ",", "window", ",", "min_periods", "=", "None", ",", "center", "=", "False", ",", "win_type", "=", "None", ",", "on", "=", "None", ",", "axis", "=", "0", ",", "closed", "=", "None", ",", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "if", "win_type", "is", "not", "None", ":", "return", "Window", "(", "self", ",", "window", "=", "window", ",", "min_periods", "=", "min_periods", ",", "center", "=", "center", ",", "win_type", "=", "win_type", ",", "on", "=", "on", ",", "axis", "=", "axis", ",", "closed", "=", "closed", ",", ")", "return", "Rolling", "(", "self", ",", "window", "=", "window", ",", "min_periods", "=", "min_periods", ",", "center", "=", "center", ",", "win_type", "=", "win_type", ",", "on", "=", "on", ",", "axis", "=", "axis", ",", "closed", "=", "closed", ",", ")", "cls", ".", "rolling", "=", "rolling", "@", "Appender", "(", "Expanding", ".", "__doc__", ")", "def", "expanding", "(", "self", ",", "min_periods", "=", "1", ",", "center", "=", "False", ",", "axis", "=", "0", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "return", "Expanding", "(", "self", ",", "min_periods", "=", "min_periods", ",", "center", "=", "center", ",", "axis", "=", "axis", ")", "cls", ".", "expanding", "=", "expanding", "@", "Appender", "(", "EWM", ".", "__doc__", ")", "def", "ewm", "(", "self", ",", "com", "=", "None", ",", "span", "=", "None", ",", "halflife", "=", "None", ",", "alpha", "=", "None", ",", "min_periods", "=", "0", ",", "adjust", "=", "True", ",", "ignore_na", "=", "False", ",", "axis", "=", "0", ",", ")", ":", "axis", "=", "self", ".", "_get_axis_number", "(", "axis", ")", "return", "EWM", "(", "self", ",", "com", "=", "com", ",", "span", "=", "span", ",", "halflife", "=", "halflife", ",", "alpha", "=", "alpha", ",", "min_periods", "=", "min_periods", ",", "adjust", "=", "adjust", ",", "ignore_na", "=", "ignore_na", ",", "axis", "=", "axis", ",", ")", "cls", ".", "ewm", "=", "ewm" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L10343-L10421
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/telnetlib.py
python
Telnet.process_rawq
(self)
Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence.
Transfer from raw queue to cooked queue.
[ "Transfer", "from", "raw", "queue", "to", "cooked", "queue", "." ]
def process_rawq(self): """Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence. """ buf = ['', ''] try: while self.rawq: c = self.rawq_getchar() if not self.iacseq: if c == theNULL: continue if c == "\021": continue if c != IAC: buf[self.sb] = buf[self.sb] + c continue else: self.iacseq += c elif len(self.iacseq) == 1: # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]' if c in (DO, DONT, WILL, WONT): self.iacseq += c continue self.iacseq = '' if c == IAC: buf[self.sb] = buf[self.sb] + c else: if c == SB: # SB ... SE start. self.sb = 1 self.sbdataq = '' elif c == SE: self.sb = 0 self.sbdataq = self.sbdataq + buf[1] buf[1] = '' if self.option_callback: # Callback is supposed to look into # the sbdataq self.option_callback(self.sock, c, NOOPT) else: # We can't offer automatic processing of # suboptions. Alas, we should not get any # unless we did a WILL/DO before. self.msg('IAC %d not recognized' % ord(c)) elif len(self.iacseq) == 2: cmd = self.iacseq[1] self.iacseq = '' opt = c if cmd in (DO, DONT): self.msg('IAC %s %d', cmd == DO and 'DO' or 'DONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(IAC + WONT + opt) elif cmd in (WILL, WONT): self.msg('IAC %s %d', cmd == WILL and 'WILL' or 'WONT', ord(opt)) if self.option_callback: self.option_callback(self.sock, cmd, opt) else: self.sock.sendall(IAC + DONT + opt) except EOFError: # raised by self.rawq_getchar() self.iacseq = '' # Reset on EOF self.sb = 0 pass self.cookedq = self.cookedq + buf[0] self.sbdataq = self.sbdataq + buf[1]
[ "def", "process_rawq", "(", "self", ")", ":", "buf", "=", "[", "''", ",", "''", "]", "try", ":", "while", "self", ".", "rawq", ":", "c", "=", "self", ".", "rawq_getchar", "(", ")", "if", "not", "self", ".", "iacseq", ":", "if", "c", "==", "theNULL", ":", "continue", "if", "c", "==", "\"\\021\"", ":", "continue", "if", "c", "!=", "IAC", ":", "buf", "[", "self", ".", "sb", "]", "=", "buf", "[", "self", ".", "sb", "]", "+", "c", "continue", "else", ":", "self", ".", "iacseq", "+=", "c", "elif", "len", "(", "self", ".", "iacseq", ")", "==", "1", ":", "# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'", "if", "c", "in", "(", "DO", ",", "DONT", ",", "WILL", ",", "WONT", ")", ":", "self", ".", "iacseq", "+=", "c", "continue", "self", ".", "iacseq", "=", "''", "if", "c", "==", "IAC", ":", "buf", "[", "self", ".", "sb", "]", "=", "buf", "[", "self", ".", "sb", "]", "+", "c", "else", ":", "if", "c", "==", "SB", ":", "# SB ... SE start.", "self", ".", "sb", "=", "1", "self", ".", "sbdataq", "=", "''", "elif", "c", "==", "SE", ":", "self", ".", "sb", "=", "0", "self", ".", "sbdataq", "=", "self", ".", "sbdataq", "+", "buf", "[", "1", "]", "buf", "[", "1", "]", "=", "''", "if", "self", ".", "option_callback", ":", "# Callback is supposed to look into", "# the sbdataq", "self", ".", "option_callback", "(", "self", ".", "sock", ",", "c", ",", "NOOPT", ")", "else", ":", "# We can't offer automatic processing of", "# suboptions. Alas, we should not get any", "# unless we did a WILL/DO before.", "self", ".", "msg", "(", "'IAC %d not recognized'", "%", "ord", "(", "c", ")", ")", "elif", "len", "(", "self", ".", "iacseq", ")", "==", "2", ":", "cmd", "=", "self", ".", "iacseq", "[", "1", "]", "self", ".", "iacseq", "=", "''", "opt", "=", "c", "if", "cmd", "in", "(", "DO", ",", "DONT", ")", ":", "self", ".", "msg", "(", "'IAC %s %d'", ",", "cmd", "==", "DO", "and", "'DO'", "or", "'DONT'", ",", "ord", "(", "opt", ")", ")", "if", "self", ".", "option_callback", ":", "self", ".", "option_callback", "(", "self", ".", "sock", ",", "cmd", ",", "opt", ")", "else", ":", "self", ".", "sock", ".", "sendall", "(", "IAC", "+", "WONT", "+", "opt", ")", "elif", "cmd", "in", "(", "WILL", ",", "WONT", ")", ":", "self", ".", "msg", "(", "'IAC %s %d'", ",", "cmd", "==", "WILL", "and", "'WILL'", "or", "'WONT'", ",", "ord", "(", "opt", ")", ")", "if", "self", ".", "option_callback", ":", "self", ".", "option_callback", "(", "self", ".", "sock", ",", "cmd", ",", "opt", ")", "else", ":", "self", ".", "sock", ".", "sendall", "(", "IAC", "+", "DONT", "+", "opt", ")", "except", "EOFError", ":", "# raised by self.rawq_getchar()", "self", ".", "iacseq", "=", "''", "# Reset on EOF", "self", ".", "sb", "=", "0", "pass", "self", ".", "cookedq", "=", "self", ".", "cookedq", "+", "buf", "[", "0", "]", "self", ".", "sbdataq", "=", "self", ".", "sbdataq", "+", "buf", "[", "1", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/telnetlib.py#L471-L541
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/specs/python/summaries.py
python
_truncate_structure
(x)
return False
A helper function that disables recursion in tf_structure. Some constructs (e.g., HorizontalLstm) are complex unrolled structures and don't need to be represented in the output of tf_structure or tf_print. This helper function defines which tree branches should be pruned. This is a very imperfect way of dealing with unrolled LSTM's (since it truncates useful information as well), but it's not worth doing something better until the new fused and unrolled ops are ready. Args: x: a Tensor or Op Returns: A bool indicating whether the subtree should be pruned.
A helper function that disables recursion in tf_structure.
[ "A", "helper", "function", "that", "disables", "recursion", "in", "tf_structure", "." ]
def _truncate_structure(x): """A helper function that disables recursion in tf_structure. Some constructs (e.g., HorizontalLstm) are complex unrolled structures and don't need to be represented in the output of tf_structure or tf_print. This helper function defines which tree branches should be pruned. This is a very imperfect way of dealing with unrolled LSTM's (since it truncates useful information as well), but it's not worth doing something better until the new fused and unrolled ops are ready. Args: x: a Tensor or Op Returns: A bool indicating whether the subtree should be pruned. """ if "/HorizontalLstm/" in x.name: return True return False
[ "def", "_truncate_structure", "(", "x", ")", ":", "if", "\"/HorizontalLstm/\"", "in", "x", ".", "name", ":", "return", "True", "return", "False" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/specs/python/summaries.py#L52-L70
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBWatchpoint.GetError
(self)
return _lldb.SBWatchpoint_GetError(self)
GetError(self) -> SBError
GetError(self) -> SBError
[ "GetError", "(", "self", ")", "-", ">", "SBError" ]
def GetError(self): """GetError(self) -> SBError""" return _lldb.SBWatchpoint_GetError(self)
[ "def", "GetError", "(", "self", ")", ":", "return", "_lldb", ".", "SBWatchpoint_GetError", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L12594-L12596
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py
python
Babyl.get_bytes
(self, key)
return headers + data
Return a string representation or raise a KeyError.
Return a string representation or raise a KeyError.
[ "Return", "a", "string", "representation", "or", "raise", "a", "KeyError", "." ]
def get_bytes(self, key): """Return a string representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) self._file.readline() # Skip b'1,' line specifying labels. original_headers = io.BytesIO() while True: line = self._file.readline() if line == b'*** EOOH ***' + linesep or not line: break original_headers.write(line.replace(linesep, b'\n')) while True: line = self._file.readline() if line == linesep or not line: break headers = original_headers.getvalue() n = stop - self._file.tell() assert n >= 0 data = self._file.read(n) data = data.replace(linesep, b'\n') return headers + data
[ "def", "get_bytes", "(", "self", ",", "key", ")", ":", "start", ",", "stop", "=", "self", ".", "_lookup", "(", "key", ")", "self", ".", "_file", ".", "seek", "(", "start", ")", "self", ".", "_file", ".", "readline", "(", ")", "# Skip b'1,' line specifying labels.", "original_headers", "=", "io", ".", "BytesIO", "(", ")", "while", "True", ":", "line", "=", "self", ".", "_file", ".", "readline", "(", ")", "if", "line", "==", "b'*** EOOH ***'", "+", "linesep", "or", "not", "line", ":", "break", "original_headers", ".", "write", "(", "line", ".", "replace", "(", "linesep", ",", "b'\\n'", ")", ")", "while", "True", ":", "line", "=", "self", ".", "_file", ".", "readline", "(", ")", "if", "line", "==", "linesep", "or", "not", "line", ":", "break", "headers", "=", "original_headers", ".", "getvalue", "(", ")", "n", "=", "stop", "-", "self", ".", "_file", ".", "tell", "(", ")", "assert", "n", ">=", "0", "data", "=", "self", ".", "_file", ".", "read", "(", "n", ")", "data", "=", "data", ".", "replace", "(", "linesep", ",", "b'\\n'", ")", "return", "headers", "+", "data" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/mailbox.py#L1295-L1315
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/cpplint.py
python
CheckEmptyBlockBody
(filename, clean_lines, linenum, error)
Look for empty loop/conditional body with only a single semicolon. 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.
Look for empty loop/conditional body with only a single semicolon.
[ "Look", "for", "empty", "loop", "/", "conditional", "body", "with", "only", "a", "single", "semicolon", "." ]
def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. 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. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. # # We also check "if" blocks here, since an empty conditional block # is likely an error. line = clean_lines.elided[linenum] matched = Match(r'\s*(for|while|if)\s*\(', line) if matched: # Find the end of the conditional expression. (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): if matched.group(1) == 'if': error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, 'Empty conditional bodies should use {}') else: error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue') # Check for if statements that have completely empty bodies (no comments) # and no else clauses. if end_pos >= 0 and matched.group(1) == 'if': # Find the position of the opening { for the if statement. # Return without logging an error if it has no brackets. opening_linenum = end_linenum opening_line_fragment = end_line[end_pos:] # Loop until EOF or find anything that's not whitespace or opening {. while not Search(r'^\s*\{', opening_line_fragment): if Search(r'^(?!\s*$)', opening_line_fragment): # Conditional has no brackets. return opening_linenum += 1 if opening_linenum == len(clean_lines.elided): # Couldn't find conditional's opening { or any code before EOF. return opening_line_fragment = clean_lines.elided[opening_linenum] # Set opening_line (opening_line_fragment may not be entire opening line). opening_line = clean_lines.elided[opening_linenum] # Find the position of the closing }. opening_pos = opening_line_fragment.find('{') if opening_linenum == end_linenum: # We need to make opening_pos relative to the start of the entire line. opening_pos += end_pos (closing_line, closing_linenum, closing_pos) = CloseExpression( clean_lines, opening_linenum, opening_pos) if closing_pos < 0: return # Now construct the body of the conditional. This consists of the portion # of the opening line after the {, all lines until the closing line, # and the portion of the closing line before the }. if (clean_lines.raw_lines[opening_linenum] != CleanseComments(clean_lines.raw_lines[opening_linenum])): # Opening line ends with a comment, so conditional isn't empty. return if closing_linenum > opening_linenum: # Opening line after the {. Ignore comments here since we checked above. bodylist = list(opening_line[opening_pos+1:]) # All lines until closing line, excluding closing line, with comments. bodylist.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum]) # Closing line before the }. Won't (and can't) have comments. bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1]) body = '\n'.join(bodylist) else: # If statement has brackets and fits on a single line. body = opening_line[opening_pos+1:closing_pos-1] # Check if the body is empty if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body): return # The body is empty. Now make sure there's not an else clause. current_linenum = closing_linenum current_line_fragment = closing_line[closing_pos:] # Loop until EOF or find anything that's not whitespace or else clause. while Search(r'^\s*$|^(?=\s*else)', current_line_fragment): if Search(r'^(?=\s*else)', current_line_fragment): # Found an else clause, so don't log an error. return current_linenum += 1 if current_linenum == len(clean_lines.elided): break current_line_fragment = clean_lines.elided[current_linenum] # The body is empty and there's no else clause until EOF or other code. error(filename, end_linenum, 'whitespace/empty_if_body', 4, ('If statement had no body and no else clause'))
[ "def", "CheckEmptyBlockBody", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Search for loop keywords at the beginning of the line. Because only", "# whitespaces are allowed before the keywords, this will also ignore most", "# do-while-loops, since those lines should start with closing brace.", "#", "# We also check \"if\" blocks here, since an empty conditional block", "# is likely an error.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "matched", "=", "Match", "(", "r'\\s*(for|while|if)\\s*\\('", ",", "line", ")", "if", "matched", ":", "# Find the end of the conditional expression.", "(", "end_line", ",", "end_linenum", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "line", ".", "find", "(", "'('", ")", ")", "# Output warning if what follows the condition expression is a semicolon.", "# No warning for all other cases, including whitespace or newline, since we", "# have a separate check for semicolons preceded by whitespace.", "if", "end_pos", ">=", "0", "and", "Match", "(", "r';'", ",", "end_line", "[", "end_pos", ":", "]", ")", ":", "if", "matched", ".", "group", "(", "1", ")", "==", "'if'", ":", "error", "(", "filename", ",", "end_linenum", ",", "'whitespace/empty_conditional_body'", ",", "5", ",", "'Empty conditional bodies should use {}'", ")", "else", ":", "error", "(", "filename", ",", "end_linenum", ",", "'whitespace/empty_loop_body'", ",", "5", ",", "'Empty loop bodies should use {} or continue'", ")", "# Check for if statements that have completely empty bodies (no comments)", "# and no else clauses.", "if", "end_pos", ">=", "0", "and", "matched", ".", "group", "(", "1", ")", "==", "'if'", ":", "# Find the position of the opening { for the if statement.", "# Return without logging an error if it has no brackets.", "opening_linenum", "=", "end_linenum", "opening_line_fragment", "=", "end_line", "[", "end_pos", ":", "]", "# Loop until EOF or find anything that's not whitespace or opening {.", "while", "not", "Search", "(", "r'^\\s*\\{'", ",", "opening_line_fragment", ")", ":", "if", "Search", "(", "r'^(?!\\s*$)'", ",", "opening_line_fragment", ")", ":", "# Conditional has no brackets.", "return", "opening_linenum", "+=", "1", "if", "opening_linenum", "==", "len", "(", "clean_lines", ".", "elided", ")", ":", "# Couldn't find conditional's opening { or any code before EOF.", "return", "opening_line_fragment", "=", "clean_lines", ".", "elided", "[", "opening_linenum", "]", "# Set opening_line (opening_line_fragment may not be entire opening line).", "opening_line", "=", "clean_lines", ".", "elided", "[", "opening_linenum", "]", "# Find the position of the closing }.", "opening_pos", "=", "opening_line_fragment", ".", "find", "(", "'{'", ")", "if", "opening_linenum", "==", "end_linenum", ":", "# We need to make opening_pos relative to the start of the entire line.", "opening_pos", "+=", "end_pos", "(", "closing_line", ",", "closing_linenum", ",", "closing_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "opening_linenum", ",", "opening_pos", ")", "if", "closing_pos", "<", "0", ":", "return", "# Now construct the body of the conditional. This consists of the portion", "# of the opening line after the {, all lines until the closing line,", "# and the portion of the closing line before the }.", "if", "(", "clean_lines", ".", "raw_lines", "[", "opening_linenum", "]", "!=", "CleanseComments", "(", "clean_lines", ".", "raw_lines", "[", "opening_linenum", "]", ")", ")", ":", "# Opening line ends with a comment, so conditional isn't empty.", "return", "if", "closing_linenum", ">", "opening_linenum", ":", "# Opening line after the {. Ignore comments here since we checked above.", "bodylist", "=", "list", "(", "opening_line", "[", "opening_pos", "+", "1", ":", "]", ")", "# All lines until closing line, excluding closing line, with comments.", "bodylist", ".", "extend", "(", "clean_lines", ".", "raw_lines", "[", "opening_linenum", "+", "1", ":", "closing_linenum", "]", ")", "# Closing line before the }. Won't (and can't) have comments.", "bodylist", ".", "append", "(", "clean_lines", ".", "elided", "[", "closing_linenum", "]", "[", ":", "closing_pos", "-", "1", "]", ")", "body", "=", "'\\n'", ".", "join", "(", "bodylist", ")", "else", ":", "# If statement has brackets and fits on a single line.", "body", "=", "opening_line", "[", "opening_pos", "+", "1", ":", "closing_pos", "-", "1", "]", "# Check if the body is empty", "if", "not", "_EMPTY_CONDITIONAL_BODY_PATTERN", ".", "search", "(", "body", ")", ":", "return", "# The body is empty. Now make sure there's not an else clause.", "current_linenum", "=", "closing_linenum", "current_line_fragment", "=", "closing_line", "[", "closing_pos", ":", "]", "# Loop until EOF or find anything that's not whitespace or else clause.", "while", "Search", "(", "r'^\\s*$|^(?=\\s*else)'", ",", "current_line_fragment", ")", ":", "if", "Search", "(", "r'^(?=\\s*else)'", ",", "current_line_fragment", ")", ":", "# Found an else clause, so don't log an error.", "return", "current_linenum", "+=", "1", "if", "current_linenum", "==", "len", "(", "clean_lines", ".", "elided", ")", ":", "break", "current_line_fragment", "=", "clean_lines", ".", "elided", "[", "current_linenum", "]", "# The body is empty and there's no else clause until EOF or other code.", "error", "(", "filename", ",", "end_linenum", ",", "'whitespace/empty_if_body'", ",", "4", ",", "(", "'If statement had no body and no else clause'", ")", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/cpplint.py#L4136-L4237
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/front/subgraph_matcher.py
python
SubgraphMatch.input_nodes
(self, port: int)
return self._input_nodes_map[port]
Returns list of tuples where the first element is a Node of the sub-graph and the second is the input port for that node. Each node of this list gets the same input tensor through the input port with number 'port' of the sub-graph. For example, if the returned list requested for port 'portSG' is the following: [(NodeA, portA), (nodeB, portB)] then the same tensor is passed to node 'NodeA' as input with number 'portA' and node 'nodeB' as input with number 'portB' for the sub-graph input with number 'portSG'. :param port: input port of the sub-graph. :return: list describing nodes of the sub-graph getting tensor through the specified port.
Returns list of tuples where the first element is a Node of the sub-graph and the second is the input port for that node. Each node of this list gets the same input tensor through the input port with number 'port' of the sub-graph.
[ "Returns", "list", "of", "tuples", "where", "the", "first", "element", "is", "a", "Node", "of", "the", "sub", "-", "graph", "and", "the", "second", "is", "the", "input", "port", "for", "that", "node", ".", "Each", "node", "of", "this", "list", "gets", "the", "same", "input", "tensor", "through", "the", "input", "port", "with", "number", "port", "of", "the", "sub", "-", "graph", "." ]
def input_nodes(self, port: int): """ Returns list of tuples where the first element is a Node of the sub-graph and the second is the input port for that node. Each node of this list gets the same input tensor through the input port with number 'port' of the sub-graph. For example, if the returned list requested for port 'portSG' is the following: [(NodeA, portA), (nodeB, portB)] then the same tensor is passed to node 'NodeA' as input with number 'portA' and node 'nodeB' as input with number 'portB' for the sub-graph input with number 'portSG'. :param port: input port of the sub-graph. :return: list describing nodes of the sub-graph getting tensor through the specified port. """ return self._input_nodes_map[port]
[ "def", "input_nodes", "(", "self", ",", "port", ":", "int", ")", ":", "return", "self", ".", "_input_nodes_map", "[", "port", "]" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/subgraph_matcher.py#L81-L93
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
external/marcopede-face-eval-f2870fd85d48/util.py
python
boxHOG
(px, py, dx, dy, col, lw)
bbox one the HOG weights
bbox one the HOG weights
[ "bbox", "one", "the", "HOG", "weights" ]
def boxHOG(px, py, dx, dy, col, lw): """ bbox one the HOG weights """ k = 1 d = 15 pylab.plot([px * d + 0 - k, px * d + 0 - k], [py * d + 0 - k, py * d + dy * d - k], col, lw=lw) pylab.plot([px * d + 0 - k, px * d + dx * d - k], [py * d + 0 - k, py * d + 0 - k], col, lw=lw) pylab.plot([px * d + dx * 15 - k, px * d + dx * d - k], [py * d + 0 - k, py * d + dy * d - k], col, lw=lw) pylab.plot([px * d + 0 - k, px * d + dx * d - k], [py * d + dy * d - k, py * d + dy * d - k], col, lw=lw) pylab.axis("image")
[ "def", "boxHOG", "(", "px", ",", "py", ",", "dx", ",", "dy", ",", "col", ",", "lw", ")", ":", "k", "=", "1", "d", "=", "15", "pylab", ".", "plot", "(", "[", "px", "*", "d", "+", "0", "-", "k", ",", "px", "*", "d", "+", "0", "-", "k", "]", ",", "[", "py", "*", "d", "+", "0", "-", "k", ",", "py", "*", "d", "+", "dy", "*", "d", "-", "k", "]", ",", "col", ",", "lw", "=", "lw", ")", "pylab", ".", "plot", "(", "[", "px", "*", "d", "+", "0", "-", "k", ",", "px", "*", "d", "+", "dx", "*", "d", "-", "k", "]", ",", "[", "py", "*", "d", "+", "0", "-", "k", ",", "py", "*", "d", "+", "0", "-", "k", "]", ",", "col", ",", "lw", "=", "lw", ")", "pylab", ".", "plot", "(", "[", "px", "*", "d", "+", "dx", "*", "15", "-", "k", ",", "px", "*", "d", "+", "dx", "*", "d", "-", "k", "]", ",", "[", "py", "*", "d", "+", "0", "-", "k", ",", "py", "*", "d", "+", "dy", "*", "d", "-", "k", "]", ",", "col", ",", "lw", "=", "lw", ")", "pylab", ".", "plot", "(", "[", "px", "*", "d", "+", "0", "-", "k", ",", "px", "*", "d", "+", "dx", "*", "d", "-", "k", "]", ",", "[", "py", "*", "d", "+", "dy", "*", "d", "-", "k", ",", "py", "*", "d", "+", "dy", "*", "d", "-", "k", "]", ",", "col", ",", "lw", "=", "lw", ")", "pylab", ".", "axis", "(", "\"image\"", ")" ]
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/external/marcopede-face-eval-f2870fd85d48/util.py#L270-L284
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/input.py
python
range_input_producer
(limit, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None)
Produces the integers from 0 to limit-1 in a queue. Note: if `num_epochs` is not `None`, this function creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables. Args: limit: An int32 scalar tensor. num_epochs: An integer (optional). If specified, `range_input_producer` produces each integer `num_epochs` times before generating an OutOfRange error. If not specified, `range_input_producer` can cycle through the integers an unlimited number of times. shuffle: Boolean. If true, the integers are randomly shuffled within each epoch. seed: An integer (optional). Seed used if shuffle == True. capacity: An integer. Sets the queue capacity. shared_name: (optional). If set, this queue will be shared under the given name across multiple sessions. name: A name for the operations (optional). Returns: A Queue with the output integers. A `QueueRunner` for the Queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. @compatibility(eager) Input pipelines based on Queues are not supported when eager execution is enabled. Please use the `tf.data` API to ingest data under eager execution. @end_compatibility
Produces the integers from 0 to limit-1 in a queue.
[ "Produces", "the", "integers", "from", "0", "to", "limit", "-", "1", "in", "a", "queue", "." ]
def range_input_producer(limit, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None): """Produces the integers from 0 to limit-1 in a queue. Note: if `num_epochs` is not `None`, this function creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables. Args: limit: An int32 scalar tensor. num_epochs: An integer (optional). If specified, `range_input_producer` produces each integer `num_epochs` times before generating an OutOfRange error. If not specified, `range_input_producer` can cycle through the integers an unlimited number of times. shuffle: Boolean. If true, the integers are randomly shuffled within each epoch. seed: An integer (optional). Seed used if shuffle == True. capacity: An integer. Sets the queue capacity. shared_name: (optional). If set, this queue will be shared under the given name across multiple sessions. name: A name for the operations (optional). Returns: A Queue with the output integers. A `QueueRunner` for the Queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. @compatibility(eager) Input pipelines based on Queues are not supported when eager execution is enabled. Please use the `tf.data` API to ingest data under eager execution. @end_compatibility """ with ops.name_scope(name, "input_producer", [limit]) as name: range_tensor = math_ops.range(limit) return input_producer( range_tensor, [], num_epochs, shuffle, seed, capacity, shared_name, "fraction_of_%d_full" % capacity, name)
[ "def", "range_input_producer", "(", "limit", ",", "num_epochs", "=", "None", ",", "shuffle", "=", "True", ",", "seed", "=", "None", ",", "capacity", "=", "32", ",", "shared_name", "=", "None", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"input_producer\"", ",", "[", "limit", "]", ")", "as", "name", ":", "range_tensor", "=", "math_ops", ".", "range", "(", "limit", ")", "return", "input_producer", "(", "range_tensor", ",", "[", "]", ",", "num_epochs", ",", "shuffle", ",", "seed", ",", "capacity", ",", "shared_name", ",", "\"fraction_of_%d_full\"", "%", "capacity", ",", "name", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/training/input.py#L285-L319
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibook.py
python
AuiNotebook.ReparentControl
(self, control, dest_tabs)
Reparents a control added inside a tab. :param Window `control`: almost any :class:`Window` -derived instance to be located inside a tab; :param `dest_tabs`: the destination :class:`AuiTabCtrl`.
Reparents a control added inside a tab.
[ "Reparents", "a", "control", "added", "inside", "a", "tab", "." ]
def ReparentControl(self, control, dest_tabs): """ Reparents a control added inside a tab. :param Window `control`: almost any :class:`Window` -derived instance to be located inside a tab; :param `dest_tabs`: the destination :class:`AuiTabCtrl`. """ control.Hide() control.Reparent(dest_tabs)
[ "def", "ReparentControl", "(", "self", ",", "control", ",", "dest_tabs", ")", ":", "control", ".", "Hide", "(", ")", "control", ".", "Reparent", "(", "dest_tabs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibook.py#L4366-L4376
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/operator/spin.py
python
sigmap
( hilbert: _AbstractHilbert, site: int, dtype: _DType = float )
return _LocalOperator(hilbert, mat, [site], dtype=dtype)
Builds the :math:`\\sigma^{+} = \\frac{1}{2}(\\sigma^x + i \\sigma^y)` operator acting on the `site`-th of the Hilbert space `hilbert`. If `hilbert` is a non-Spin space of local dimension M, it is considered as a (M-1)/2 - spin space. :param hilbert: The hilbert space :param site: the site on which this operator acts :return: a nk.operator.LocalOperator
Builds the :math:`\\sigma^{+} = \\frac{1}{2}(\\sigma^x + i \\sigma^y)` operator acting on the `site`-th of the Hilbert space `hilbert`.
[ "Builds", "the", ":", "math", ":", "\\\\", "sigma^", "{", "+", "}", "=", "\\\\", "frac", "{", "1", "}", "{", "2", "}", "(", "\\\\", "sigma^x", "+", "i", "\\\\", "sigma^y", ")", "operator", "acting", "on", "the", "site", "-", "th", "of", "the", "Hilbert", "space", "hilbert", "." ]
def sigmap( hilbert: _AbstractHilbert, site: int, dtype: _DType = float ) -> _LocalOperator: """ Builds the :math:`\\sigma^{+} = \\frac{1}{2}(\\sigma^x + i \\sigma^y)` operator acting on the `site`-th of the Hilbert space `hilbert`. If `hilbert` is a non-Spin space of local dimension M, it is considered as a (M-1)/2 - spin space. :param hilbert: The hilbert space :param site: the site on which this operator acts :return: a nk.operator.LocalOperator """ import numpy as np N = hilbert.size_at_index(site) S = (N - 1) / 2 S2 = (S + 1) * S D = np.array([np.sqrt(S2 - m * (m + 1)) for m in np.arange(S - 1, -(S + 1), -1)]) mat = np.diag(D, 1) return _LocalOperator(hilbert, mat, [site], dtype=dtype)
[ "def", "sigmap", "(", "hilbert", ":", "_AbstractHilbert", ",", "site", ":", "int", ",", "dtype", ":", "_DType", "=", "float", ")", "->", "_LocalOperator", ":", "import", "numpy", "as", "np", "N", "=", "hilbert", ".", "size_at_index", "(", "site", ")", "S", "=", "(", "N", "-", "1", ")", "/", "2", "S2", "=", "(", "S", "+", "1", ")", "*", "S", "D", "=", "np", ".", "array", "(", "[", "np", ".", "sqrt", "(", "S2", "-", "m", "*", "(", "m", "+", "1", ")", ")", "for", "m", "in", "np", ".", "arange", "(", "S", "-", "1", ",", "-", "(", "S", "+", "1", ")", ",", "-", "1", ")", "]", ")", "mat", "=", "np", ".", "diag", "(", "D", ",", "1", ")", "return", "_LocalOperator", "(", "hilbert", ",", "mat", ",", "[", "site", "]", ",", "dtype", "=", "dtype", ")" ]
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/operator/spin.py#L119-L141
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/inputs/atoms.py
python
InputAtoms.write
(self, name="", indent="")
Overloads Input write() function so that nothing is written if no atoms are present. This occurs if the beads object has been specified, so that the classical atoms object is not initialized. Returns: A string giving the appropriate xml tags for the checkpoint file.
Overloads Input write() function so that nothing is written if no atoms are present. This occurs if the beads object has been specified, so that the classical atoms object is not initialized.
[ "Overloads", "Input", "write", "()", "function", "so", "that", "nothing", "is", "written", "if", "no", "atoms", "are", "present", ".", "This", "occurs", "if", "the", "beads", "object", "has", "been", "specified", "so", "that", "the", "classical", "atoms", "object", "is", "not", "initialized", "." ]
def write(self, name="", indent=""): """Overloads Input write() function so that nothing is written if no atoms are present. This occurs if the beads object has been specified, so that the classical atoms object is not initialized. Returns: A string giving the appropriate xml tags for the checkpoint file. """ if self.natoms.fetch() > 0: return super(InputAtoms,self).write(name=name,indent=indent) else: return ""
[ "def", "write", "(", "self", ",", "name", "=", "\"\"", ",", "indent", "=", "\"\"", ")", ":", "if", "self", ".", "natoms", ".", "fetch", "(", ")", ">", "0", ":", "return", "super", "(", "InputAtoms", ",", "self", ")", ".", "write", "(", "name", "=", "name", ",", "indent", "=", "indent", ")", "else", ":", "return", "\"\"" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/atoms.py#L109-L121
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/numpy/multiarray.py
python
max
(a, axis=None, out=None, keepdims=False)
return _mx_nd_np.max(a, axis=axis, out=out, keepdims=keepdims)
Return the maximum of an array or maximum along an axis. Parameters ---------- a : ndarray Input data. axis : int, optional Axis along which to operate. By default, flattened input is used. out : ndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See `doc.ufuncs` (Section "Output arguments") for more details. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- max : ndarray Maximum of `a`. If `axis` is None, the result is an array of dimension 1. If `axis` is given, the result is an array of dimension ``a.ndim - 1``. See Also -------- min : The minimum value of an array along a given axis, ignoring any nan. maximum : Element-wise maximum of two arrays, ignoring any nan. argmax : Return the indices of the maximum values. Notes ----- NaN in the orginal `numpy` is denoted as nan and will be ignored. Don't use `max` for element-wise comparison of 2 arrays; when ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than ``max(a, axis=0)``. Examples -------- >>> a = np.arange(4).reshape((2,2)) >>> a array([[0., 1.], [2., 3.]]) >>> np.max(a) # Maximum of the flattened array array(3.) >>> np.max(a, axis=0) # Maxima along the first axis array([2., 3.]) >>> np.max(a, axis=1) # Maxima along the second axis array([1., 3.]) >>> b = np.arange(5, dtype=np.float32) >>> b[2] = np.nan >>> np.max(b) array(4.)
Return the maximum of an array or maximum along an axis.
[ "Return", "the", "maximum", "of", "an", "array", "or", "maximum", "along", "an", "axis", "." ]
def max(a, axis=None, out=None, keepdims=False): """ Return the maximum of an array or maximum along an axis. Parameters ---------- a : ndarray Input data. axis : int, optional Axis along which to operate. By default, flattened input is used. out : ndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See `doc.ufuncs` (Section "Output arguments") for more details. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- max : ndarray Maximum of `a`. If `axis` is None, the result is an array of dimension 1. If `axis` is given, the result is an array of dimension ``a.ndim - 1``. See Also -------- min : The minimum value of an array along a given axis, ignoring any nan. maximum : Element-wise maximum of two arrays, ignoring any nan. argmax : Return the indices of the maximum values. Notes ----- NaN in the orginal `numpy` is denoted as nan and will be ignored. Don't use `max` for element-wise comparison of 2 arrays; when ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than ``max(a, axis=0)``. Examples -------- >>> a = np.arange(4).reshape((2,2)) >>> a array([[0., 1.], [2., 3.]]) >>> np.max(a) # Maximum of the flattened array array(3.) >>> np.max(a, axis=0) # Maxima along the first axis array([2., 3.]) >>> np.max(a, axis=1) # Maxima along the second axis array([1., 3.]) >>> b = np.arange(5, dtype=np.float32) >>> b[2] = np.nan >>> np.max(b) array(4.) """ return _mx_nd_np.max(a, axis=axis, out=out, keepdims=keepdims)
[ "def", "max", "(", "a", ",", "axis", "=", "None", ",", "out", "=", "None", ",", "keepdims", "=", "False", ")", ":", "return", "_mx_nd_np", ".", "max", "(", "a", ",", "axis", "=", "axis", ",", "out", "=", "out", ",", "keepdims", "=", "keepdims", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L7824-L7885
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PrintPreview.SetPrintout
(*args, **kwargs)
return _windows_.PrintPreview_SetPrintout(*args, **kwargs)
SetPrintout(self, Printout printout)
SetPrintout(self, Printout printout)
[ "SetPrintout", "(", "self", "Printout", "printout", ")" ]
def SetPrintout(*args, **kwargs): """SetPrintout(self, Printout printout)""" return _windows_.PrintPreview_SetPrintout(*args, **kwargs)
[ "def", "SetPrintout", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintPreview_SetPrintout", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L5573-L5575
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py
python
IMAP4_stream.read
(self, size)
return self.readfile.read(size)
Read 'size' bytes from remote.
Read 'size' bytes from remote.
[ "Read", "size", "bytes", "from", "remote", "." ]
def read(self, size): """Read 'size' bytes from remote.""" return self.readfile.read(size)
[ "def", "read", "(", "self", ",", "size", ")", ":", "return", "self", ".", "readfile", ".", "read", "(", "size", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/imaplib.py#L1242-L1244
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pssunos.py
python
users
()
return retlist
Return currently connected users as a list of namedtuples.
Return currently connected users as a list of namedtuples.
[ "Return", "currently", "connected", "users", "as", "a", "list", "of", "namedtuples", "." ]
def users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = cext.users() localhost = (':0.0', ':0') for item in rawlist: user, tty, hostname, tstamp, user_process, pid = item # note: the underlying C function includes entries about # system boot, run level and others. We might want # to use them in the future. if not user_process: continue if hostname in localhost: hostname = 'localhost' nt = _common.suser(user, tty, hostname, tstamp, pid) retlist.append(nt) return retlist
[ "def", "users", "(", ")", ":", "retlist", "=", "[", "]", "rawlist", "=", "cext", ".", "users", "(", ")", "localhost", "=", "(", "':0.0'", ",", "':0'", ")", "for", "item", "in", "rawlist", ":", "user", ",", "tty", ",", "hostname", ",", "tstamp", ",", "user_process", ",", "pid", "=", "item", "# note: the underlying C function includes entries about", "# system boot, run level and others. We might want", "# to use them in the future.", "if", "not", "user_process", ":", "continue", "if", "hostname", "in", "localhost", ":", "hostname", "=", "'localhost'", "nt", "=", "_common", ".", "suser", "(", "user", ",", "tty", ",", "hostname", ",", "tstamp", ",", "pid", ")", "retlist", ".", "append", "(", "nt", ")", "return", "retlist" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/psutil/_pssunos.py#L308-L324
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMS_ACT_DATA.toTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def toTpm(self, buf): """ TpmMarshaller method """ self.handle.toTpm(buf) buf.writeInt(self.timeout) buf.writeInt(self.attributes)
[ "def", "toTpm", "(", "self", ",", "buf", ")", ":", "self", ".", "handle", ".", "toTpm", "(", "buf", ")", "buf", ".", "writeInt", "(", "self", ".", "timeout", ")", "buf", ".", "writeInt", "(", "self", ".", "attributes", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4417-L4421
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py
python
resolve
(node, source_info, graphs, definition_factory=Definition)
return node
Resolves reaching definitions for each symbol. Args: node: ast.AST source_info: transformer.SourceInfo graphs: Dict[ast.FunctionDef, cfg.Graph] definition_factory: Callable[[], Definition] Returns: ast.AST
Resolves reaching definitions for each symbol.
[ "Resolves", "reaching", "definitions", "for", "each", "symbol", "." ]
def resolve(node, source_info, graphs, definition_factory=Definition): """Resolves reaching definitions for each symbol. Args: node: ast.AST source_info: transformer.SourceInfo graphs: Dict[ast.FunctionDef, cfg.Graph] definition_factory: Callable[[], Definition] Returns: ast.AST """ visitor = TreeAnnotator(source_info, graphs, definition_factory) node = visitor.visit(node) return node
[ "def", "resolve", "(", "node", ",", "source_info", ",", "graphs", ",", "definition_factory", "=", "Definition", ")", ":", "visitor", "=", "TreeAnnotator", "(", "source_info", ",", "graphs", ",", "definition_factory", ")", "node", "=", "visitor", ".", "visit", "(", "node", ")", "return", "node" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py#L275-L288
google/mozc
7329757e1ad30e327c1ae823a8302c79482d6b9c
src/win32/installer/postbuilds_win.py
python
PrintErrorAndExit
(error_message)
Prints the error message and exists.
Prints the error message and exists.
[ "Prints", "the", "error", "message", "and", "exists", "." ]
def PrintErrorAndExit(error_message): """Prints the error message and exists.""" print(error_message) sys.exit(1)
[ "def", "PrintErrorAndExit", "(", "error_message", ")", ":", "print", "(", "error_message", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/google/mozc/blob/7329757e1ad30e327c1ae823a8302c79482d6b9c/src/win32/installer/postbuilds_win.py#L128-L131
acbull/Unbiased_LambdaMart
7c39abe5caa18ca07df2d23c2db392916d92956c
Unbias_LightGBM/python-package/lightgbm/plotting.py
python
plot_metric
(booster, metric=None, dataset_names=None, ax=None, xlim=None, ylim=None, title='Metric during training', xlabel='Iterations', ylabel='auto', figsize=None, grid=True)
return ax
Plot one metric during training. Parameters ---------- booster : dict or LGBMModel Dictionary returned from ``lightgbm.train()`` or LGBMModel instance. metric : string or None, optional (default=None) The metric name to plot. Only one metric supported because different metrics have various scales. If None, first metric picked from dictionary (according to hashcode). dataset_names : list of strings or None, optional (default=None) List of the dataset names which are used to calculate metric to plot. If None, all datasets are used. ax : matplotlib.axes.Axes or None, optional (default=None) Target axes instance. If None, new figure and axes will be created. xlim : tuple of 2 elements or None, optional (default=None) Tuple passed to ``ax.xlim()``. ylim : tuple of 2 elements or None, optional (default=None) Tuple passed to ``ax.ylim()``. title : string or None, optional (default="Metric during training") Axes title. If None, title is disabled. xlabel : string or None, optional (default="Iterations") X-axis title label. If None, title is disabled. ylabel : string or None, optional (default="auto") Y-axis title label. If 'auto', metric name is used. If None, title is disabled. figsize : tuple of 2 elements or None, optional (default=None) Figure size. grid : bool, optional (default=True) Whether to add a grid for axes. Returns ------- ax : matplotlib.axes.Axes The plot with metric's history over the training.
Plot one metric during training.
[ "Plot", "one", "metric", "during", "training", "." ]
def plot_metric(booster, metric=None, dataset_names=None, ax=None, xlim=None, ylim=None, title='Metric during training', xlabel='Iterations', ylabel='auto', figsize=None, grid=True): """Plot one metric during training. Parameters ---------- booster : dict or LGBMModel Dictionary returned from ``lightgbm.train()`` or LGBMModel instance. metric : string or None, optional (default=None) The metric name to plot. Only one metric supported because different metrics have various scales. If None, first metric picked from dictionary (according to hashcode). dataset_names : list of strings or None, optional (default=None) List of the dataset names which are used to calculate metric to plot. If None, all datasets are used. ax : matplotlib.axes.Axes or None, optional (default=None) Target axes instance. If None, new figure and axes will be created. xlim : tuple of 2 elements or None, optional (default=None) Tuple passed to ``ax.xlim()``. ylim : tuple of 2 elements or None, optional (default=None) Tuple passed to ``ax.ylim()``. title : string or None, optional (default="Metric during training") Axes title. If None, title is disabled. xlabel : string or None, optional (default="Iterations") X-axis title label. If None, title is disabled. ylabel : string or None, optional (default="auto") Y-axis title label. If 'auto', metric name is used. If None, title is disabled. figsize : tuple of 2 elements or None, optional (default=None) Figure size. grid : bool, optional (default=True) Whether to add a grid for axes. Returns ------- ax : matplotlib.axes.Axes The plot with metric's history over the training. """ try: import matplotlib.pyplot as plt except ImportError: raise ImportError('You must install matplotlib to plot metric.') if isinstance(booster, LGBMModel): eval_results = deepcopy(booster.evals_result_) elif isinstance(booster, dict): eval_results = deepcopy(booster) else: raise TypeError('booster must be dict or LGBMModel.') num_data = len(eval_results) if not num_data: raise ValueError('eval results cannot be empty.') if ax is None: if figsize is not None: check_not_tuple_of_2_elements(figsize, 'figsize') _, ax = plt.subplots(1, 1, figsize=figsize) if dataset_names is None: dataset_names = iter(eval_results.keys()) elif not isinstance(dataset_names, (list, tuple, set)) or not dataset_names: raise ValueError('dataset_names should be iterable and cannot be empty') else: dataset_names = iter(dataset_names) name = next(dataset_names) # take one as sample metrics_for_one = eval_results[name] num_metric = len(metrics_for_one) if metric is None: if num_metric > 1: msg = """more than one metric available, picking one to plot.""" warnings.warn(msg, stacklevel=2) metric, results = metrics_for_one.popitem() else: if metric not in metrics_for_one: raise KeyError('No given metric in eval results.') results = metrics_for_one[metric] num_iteration, max_result, min_result = len(results), max(results), min(results) x_ = range(num_iteration) ax.plot(x_, results, label=name) for name in dataset_names: metrics_for_one = eval_results[name] results = metrics_for_one[metric] max_result, min_result = max(max(results), max_result), min(min(results), min_result) ax.plot(x_, results, label=name) ax.legend(loc='best') if xlim is not None: check_not_tuple_of_2_elements(xlim, 'xlim') else: xlim = (0, num_iteration) ax.set_xlim(xlim) if ylim is not None: check_not_tuple_of_2_elements(ylim, 'ylim') else: range_result = max_result - min_result ylim = (min_result - range_result * 0.2, max_result + range_result * 0.2) ax.set_ylim(ylim) if ylabel == 'auto': ylabel = metric if title is not None: ax.set_title(title) if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) ax.grid(grid) return ax
[ "def", "plot_metric", "(", "booster", ",", "metric", "=", "None", ",", "dataset_names", "=", "None", ",", "ax", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "title", "=", "'Metric during training'", ",", "xlabel", "=", "'Iterations'", ",", "ylabel", "=", "'auto'", ",", "figsize", "=", "None", ",", "grid", "=", "True", ")", ":", "try", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "except", "ImportError", ":", "raise", "ImportError", "(", "'You must install matplotlib to plot metric.'", ")", "if", "isinstance", "(", "booster", ",", "LGBMModel", ")", ":", "eval_results", "=", "deepcopy", "(", "booster", ".", "evals_result_", ")", "elif", "isinstance", "(", "booster", ",", "dict", ")", ":", "eval_results", "=", "deepcopy", "(", "booster", ")", "else", ":", "raise", "TypeError", "(", "'booster must be dict or LGBMModel.'", ")", "num_data", "=", "len", "(", "eval_results", ")", "if", "not", "num_data", ":", "raise", "ValueError", "(", "'eval results cannot be empty.'", ")", "if", "ax", "is", "None", ":", "if", "figsize", "is", "not", "None", ":", "check_not_tuple_of_2_elements", "(", "figsize", ",", "'figsize'", ")", "_", ",", "ax", "=", "plt", ".", "subplots", "(", "1", ",", "1", ",", "figsize", "=", "figsize", ")", "if", "dataset_names", "is", "None", ":", "dataset_names", "=", "iter", "(", "eval_results", ".", "keys", "(", ")", ")", "elif", "not", "isinstance", "(", "dataset_names", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", "or", "not", "dataset_names", ":", "raise", "ValueError", "(", "'dataset_names should be iterable and cannot be empty'", ")", "else", ":", "dataset_names", "=", "iter", "(", "dataset_names", ")", "name", "=", "next", "(", "dataset_names", ")", "# take one as sample", "metrics_for_one", "=", "eval_results", "[", "name", "]", "num_metric", "=", "len", "(", "metrics_for_one", ")", "if", "metric", "is", "None", ":", "if", "num_metric", ">", "1", ":", "msg", "=", "\"\"\"more than one metric available, picking one to plot.\"\"\"", "warnings", ".", "warn", "(", "msg", ",", "stacklevel", "=", "2", ")", "metric", ",", "results", "=", "metrics_for_one", ".", "popitem", "(", ")", "else", ":", "if", "metric", "not", "in", "metrics_for_one", ":", "raise", "KeyError", "(", "'No given metric in eval results.'", ")", "results", "=", "metrics_for_one", "[", "metric", "]", "num_iteration", ",", "max_result", ",", "min_result", "=", "len", "(", "results", ")", ",", "max", "(", "results", ")", ",", "min", "(", "results", ")", "x_", "=", "range", "(", "num_iteration", ")", "ax", ".", "plot", "(", "x_", ",", "results", ",", "label", "=", "name", ")", "for", "name", "in", "dataset_names", ":", "metrics_for_one", "=", "eval_results", "[", "name", "]", "results", "=", "metrics_for_one", "[", "metric", "]", "max_result", ",", "min_result", "=", "max", "(", "max", "(", "results", ")", ",", "max_result", ")", ",", "min", "(", "min", "(", "results", ")", ",", "min_result", ")", "ax", ".", "plot", "(", "x_", ",", "results", ",", "label", "=", "name", ")", "ax", ".", "legend", "(", "loc", "=", "'best'", ")", "if", "xlim", "is", "not", "None", ":", "check_not_tuple_of_2_elements", "(", "xlim", ",", "'xlim'", ")", "else", ":", "xlim", "=", "(", "0", ",", "num_iteration", ")", "ax", ".", "set_xlim", "(", "xlim", ")", "if", "ylim", "is", "not", "None", ":", "check_not_tuple_of_2_elements", "(", "ylim", ",", "'ylim'", ")", "else", ":", "range_result", "=", "max_result", "-", "min_result", "ylim", "=", "(", "min_result", "-", "range_result", "*", "0.2", ",", "max_result", "+", "range_result", "*", "0.2", ")", "ax", ".", "set_ylim", "(", "ylim", ")", "if", "ylabel", "==", "'auto'", ":", "ylabel", "=", "metric", "if", "title", "is", "not", "None", ":", "ax", ".", "set_title", "(", "title", ")", "if", "xlabel", "is", "not", "None", ":", "ax", ".", "set_xlabel", "(", "xlabel", ")", "if", "ylabel", "is", "not", "None", ":", "ax", ".", "set_ylabel", "(", "ylabel", ")", "ax", ".", "grid", "(", "grid", ")", "return", "ax" ]
https://github.com/acbull/Unbiased_LambdaMart/blob/7c39abe5caa18ca07df2d23c2db392916d92956c/Unbias_LightGBM/python-package/lightgbm/plotting.py#L131-L252
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/google/protobuf/internal/python_message.py
python
_GetFieldByName
(message_descriptor, field_name)
Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name.
Returns a field descriptor by field name.
[ "Returns", "a", "field", "descriptor", "by", "field", "name", "." ]
def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. """ try: return message_descriptor.fields_by_name[field_name] except KeyError: raise ValueError('Protocol message has no "%s" field.' % field_name)
[ "def", "_GetFieldByName", "(", "message_descriptor", ",", "field_name", ")", ":", "try", ":", "return", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Protocol message has no \"%s\" field.'", "%", "field_name", ")" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/internal/python_message.py#L351-L363
kevinlin311tw/cvpr16-deepbit
c60fb3233d7d534cfcee9d3ed47d77af437ee32a
python/caffe/draw.py
python
choose_color_by_layertype
(layertype)
return color
Define colors for nodes based on the layer type.
Define colors for nodes based on the layer type.
[ "Define", "colors", "for", "nodes", "based", "on", "the", "layer", "type", "." ]
def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type. """ color = '#6495ED' # Default if layertype == 'Convolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color
[ "def", "choose_color_by_layertype", "(", "layertype", ")", ":", "color", "=", "'#6495ED'", "# Default", "if", "layertype", "==", "'Convolution'", ":", "color", "=", "'#FF5050'", "elif", "layertype", "==", "'Pooling'", ":", "color", "=", "'#FF9900'", "elif", "layertype", "==", "'InnerProduct'", ":", "color", "=", "'#CC33FF'", "return", "color" ]
https://github.com/kevinlin311tw/cvpr16-deepbit/blob/c60fb3233d7d534cfcee9d3ed47d77af437ee32a/python/caffe/draw.py#L108-L118
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/build_ext.py
python
build_ext.links_to_dynamic
(self, ext)
return any(pkg + libname in libnames for libname in ext.libraries)
Return true if 'ext' links to a dynamic lib in the same package
Return true if 'ext' links to a dynamic lib in the same package
[ "Return", "true", "if", "ext", "links", "to", "a", "dynamic", "lib", "in", "the", "same", "package" ]
def links_to_dynamic(self, ext): """Return true if 'ext' links to a dynamic lib in the same package""" # XXX this should check to ensure the lib is actually being built # XXX as dynamic, and not just using a locally-found version or a # XXX static-compiled version libnames = dict.fromkeys([lib._full_name for lib in self.shlibs]) pkg = '.'.join(ext._full_name.split('.')[:-1] + ['']) return any(pkg + libname in libnames for libname in ext.libraries)
[ "def", "links_to_dynamic", "(", "self", ",", "ext", ")", ":", "# XXX this should check to ensure the lib is actually being built", "# XXX as dynamic, and not just using a locally-found version or a", "# XXX static-compiled version", "libnames", "=", "dict", ".", "fromkeys", "(", "[", "lib", ".", "_full_name", "for", "lib", "in", "self", ".", "shlibs", "]", ")", "pkg", "=", "'.'", ".", "join", "(", "ext", ".", "_full_name", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", "+", "[", "''", "]", ")", "return", "any", "(", "pkg", "+", "libname", "in", "libnames", "for", "libname", "in", "ext", ".", "libraries", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/build_ext.py#L215-L222
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py
python
ServerConnection.ping
(self, target, target2="")
Send a PING command.
Send a PING command.
[ "Send", "a", "PING", "command", "." ]
def ping(self, target, target2=""): """Send a PING command.""" self.send_raw("PING %s%s" % (target, target2 and (" " + target2)))
[ "def", "ping", "(", "self", ",", "target", ",", "target2", "=", "\"\"", ")", ":", "self", ".", "send_raw", "(", "\"PING %s%s\"", "%", "(", "target", ",", "target2", "and", "(", "\" \"", "+", "target2", ")", ")", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/irc/irclib.py#L755-L757
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedCompositeFieldContainer.remove
(self, elem)
Removes an item from the list. Similar to list.remove().
Removes an item from the list. Similar to list.remove().
[ "Removes", "an", "item", "from", "the", "list", ".", "Similar", "to", "list", ".", "remove", "()", "." ]
def remove(self, elem): """Removes an item from the list. Similar to list.remove().""" self._values.remove(elem) self._message_listener.Modified()
[ "def", "remove", "(", "self", ",", "elem", ")", ":", "self", ".", "_values", ".", "remove", "(", "elem", ")", "self", ".", "_message_listener", ".", "Modified", "(", ")" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/containers.py#L243-L246
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/GeoMechanicsApplication/python_scripts/geomechanics_solver.py
python
GeoMechanicalSolver.Initialize
(self)
Perform initialization after adding nodal variables and dofs to the main model part.
Perform initialization after adding nodal variables and dofs to the main model part.
[ "Perform", "initialization", "after", "adding", "nodal", "variables", "and", "dofs", "to", "the", "main", "model", "part", "." ]
def Initialize(self): """Perform initialization after adding nodal variables and dofs to the main model part. """ pass
[ "def", "Initialize", "(", "self", ")", ":", "pass" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/GeoMechanicsApplication/python_scripts/geomechanics_solver.py#L106-L108
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/tf_utils.py
python
shape_type_conversion
(fn)
return wrapper
Decorator that handles tuple/TensorShape conversion. Used in `compute_output_shape` and `build`. Arguments: fn: function to wrap. Returns: Wrapped function.
Decorator that handles tuple/TensorShape conversion.
[ "Decorator", "that", "handles", "tuple", "/", "TensorShape", "conversion", "." ]
def shape_type_conversion(fn): """Decorator that handles tuple/TensorShape conversion. Used in `compute_output_shape` and `build`. Arguments: fn: function to wrap. Returns: Wrapped function. """ def wrapper(instance, input_shape): # Pass shapes as tuples to `fn` # This preserves compatibility with external Keras. if input_shape is not None: input_shape = convert_shapes(input_shape, to_tuples=True) output_shape = fn(instance, input_shape) # Return shapes from `fn` as TensorShapes. if output_shape is not None: output_shape = convert_shapes(output_shape, to_tuples=False) return output_shape return wrapper
[ "def", "shape_type_conversion", "(", "fn", ")", ":", "def", "wrapper", "(", "instance", ",", "input_shape", ")", ":", "# Pass shapes as tuples to `fn`", "# This preserves compatibility with external Keras.", "if", "input_shape", "is", "not", "None", ":", "input_shape", "=", "convert_shapes", "(", "input_shape", ",", "to_tuples", "=", "True", ")", "output_shape", "=", "fn", "(", "instance", ",", "input_shape", ")", "# Return shapes from `fn` as TensorShapes.", "if", "output_shape", "is", "not", "None", ":", "output_shape", "=", "convert_shapes", "(", "output_shape", ",", "to_tuples", "=", "False", ")", "return", "output_shape", "return", "wrapper" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/tf_utils.py#L289-L312
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMT_ASYM_SCHEME.fromTpm
(buf)
return buf.createObj(TPMT_ASYM_SCHEME)
Returns new TPMT_ASYM_SCHEME object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new TPMT_ASYM_SCHEME object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "TPMT_ASYM_SCHEME", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new TPMT_ASYM_SCHEME object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(TPMT_ASYM_SCHEME)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "TPMT_ASYM_SCHEME", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L7026-L7030
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/graph_editor/select.py
python
select_ts
(*args, **kwargs)
return ts
Helper to select tensors. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) tf.Tensor. tf.Operation instances are silently ignored. **kwargs: 'graph': tf.Graph in which to perform the regex query.This is required when using regex. 'positive_filter': an elem if selected only if positive_filter(elem) is True. This is optional. 'restrict_ts_regex': a regular expression is ignored if it doesn't start with the substring "(?#ts)". Returns: list of tf.Tensor Raises: TypeError: if the optional keyword argument graph is not a tf.Graph or if an argument in args is not an (array of) tf.Tensor or an (array of) tf.Operation (silently ignored) or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected or if a regular expression is used without passing a graph as a keyword argument.
Helper to select tensors.
[ "Helper", "to", "select", "tensors", "." ]
def select_ts(*args, **kwargs): """Helper to select tensors. Args: *args: list of 1) regular expressions (compiled or not) or 2) (array of) tf.Tensor. tf.Operation instances are silently ignored. **kwargs: 'graph': tf.Graph in which to perform the regex query.This is required when using regex. 'positive_filter': an elem if selected only if positive_filter(elem) is True. This is optional. 'restrict_ts_regex': a regular expression is ignored if it doesn't start with the substring "(?#ts)". Returns: list of tf.Tensor Raises: TypeError: if the optional keyword argument graph is not a tf.Graph or if an argument in args is not an (array of) tf.Tensor or an (array of) tf.Operation (silently ignored) or a string or a regular expression. ValueError: if one of the keyword arguments is unexpected or if a regular expression is used without passing a graph as a keyword argument. """ # get keywords arguments graph = None positive_filter = None restrict_ts_regex = False for k, v in iteritems(kwargs): if k == "graph": graph = v if graph is not None and not isinstance(graph, tf_ops.Graph): raise TypeError("Expected a tf.Graph, got {}".format(type(graph))) elif k == "positive_filter": positive_filter = v elif k == "restrict_ts_regex": restrict_ts_regex = v elif k == "restrict_ops_regex": pass else: raise ValueError("Wrong keywords argument: {}.".format(k)) ts = [] for arg in args: if can_be_regex(arg): if graph is None: raise ValueError("Use the keyword argument 'graph' to use regex.") regex = make_regex(arg) if regex.pattern.startswith("(?#ops)"): continue if restrict_ts_regex and not regex.pattern.startswith("(?#ts)"): continue ts_ = filter_ts_from_regex(graph, regex) for t_ in ts_: if t_ not in ts: if positive_filter is None or positive_filter(t_): ts.append(t_) else: ts_aux = util.make_list_of_t(arg, ignore_ops=True) if positive_filter is not None: ts_aux = [t for t in ts_aux if positive_filter(t)] ts_aux = [t for t in ts_aux if t not in ts] ts += ts_aux return ts
[ "def", "select_ts", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# get keywords arguments", "graph", "=", "None", "positive_filter", "=", "None", "restrict_ts_regex", "=", "False", "for", "k", ",", "v", "in", "iteritems", "(", "kwargs", ")", ":", "if", "k", "==", "\"graph\"", ":", "graph", "=", "v", "if", "graph", "is", "not", "None", "and", "not", "isinstance", "(", "graph", ",", "tf_ops", ".", "Graph", ")", ":", "raise", "TypeError", "(", "\"Expected a tf.Graph, got {}\"", ".", "format", "(", "type", "(", "graph", ")", ")", ")", "elif", "k", "==", "\"positive_filter\"", ":", "positive_filter", "=", "v", "elif", "k", "==", "\"restrict_ts_regex\"", ":", "restrict_ts_regex", "=", "v", "elif", "k", "==", "\"restrict_ops_regex\"", ":", "pass", "else", ":", "raise", "ValueError", "(", "\"Wrong keywords argument: {}.\"", ".", "format", "(", "k", ")", ")", "ts", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "can_be_regex", "(", "arg", ")", ":", "if", "graph", "is", "None", ":", "raise", "ValueError", "(", "\"Use the keyword argument 'graph' to use regex.\"", ")", "regex", "=", "make_regex", "(", "arg", ")", "if", "regex", ".", "pattern", ".", "startswith", "(", "\"(?#ops)\"", ")", ":", "continue", "if", "restrict_ts_regex", "and", "not", "regex", ".", "pattern", ".", "startswith", "(", "\"(?#ts)\"", ")", ":", "continue", "ts_", "=", "filter_ts_from_regex", "(", "graph", ",", "regex", ")", "for", "t_", "in", "ts_", ":", "if", "t_", "not", "in", "ts", ":", "if", "positive_filter", "is", "None", "or", "positive_filter", "(", "t_", ")", ":", "ts", ".", "append", "(", "t_", ")", "else", ":", "ts_aux", "=", "util", ".", "make_list_of_t", "(", "arg", ",", "ignore_ops", "=", "True", ")", "if", "positive_filter", "is", "not", "None", ":", "ts_aux", "=", "[", "t", "for", "t", "in", "ts_aux", "if", "positive_filter", "(", "t", ")", "]", "ts_aux", "=", "[", "t", "for", "t", "in", "ts_aux", "if", "t", "not", "in", "ts", "]", "ts", "+=", "ts_aux", "return", "ts" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/graph_editor/select.py#L638-L701
vnpy/vnpy
f50f2535ed39dd33272e0985ed40c7078e4c19f6
vnpy/chart/widget.py
python
ChartWidget._on_key_up
(self)
Zoom in the chart.
Zoom in the chart.
[ "Zoom", "in", "the", "chart", "." ]
def _on_key_up(self) -> None: """ Zoom in the chart. """ self._bar_count /= 1.2 self._bar_count = max(int(self._bar_count), self.MIN_BAR_COUNT) self._update_x_range() self._cursor.update_info()
[ "def", "_on_key_up", "(", "self", ")", "->", "None", ":", "self", ".", "_bar_count", "/=", "1.2", "self", ".", "_bar_count", "=", "max", "(", "int", "(", "self", ".", "_bar_count", ")", ",", "self", ".", "MIN_BAR_COUNT", ")", "self", ".", "_update_x_range", "(", ")", "self", ".", "_cursor", ".", "update_info", "(", ")" ]
https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/chart/widget.py#L287-L295
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
media/tools/bug_hunter/bug_hunter.py
python
BugHunterUtils.SendEmail
(message, sender_email_address, receivers_email_address, subject)
return False
Send email using localhost's mail server. Args: message: Email message to be sent. sender_email_address: Sender's email address. receivers_email_address: Receiver's email address. subject: Email subject. Returns: True if successful; False, otherwise.
Send email using localhost's mail server.
[ "Send", "email", "using", "localhost", "s", "mail", "server", "." ]
def SendEmail(message, sender_email_address, receivers_email_address, subject): """Send email using localhost's mail server. Args: message: Email message to be sent. sender_email_address: Sender's email address. receivers_email_address: Receiver's email address. subject: Email subject. Returns: True if successful; False, otherwise. """ try: html = '<html><head></head><body>%s</body></html>' % message msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender_email_address msg['To'] = receivers_email_address msg.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8')) smtp_obj = smtplib.SMTP('localhost') smtp_obj.sendmail(sender_email_address, receivers_email_address, msg.as_string()) logging.info('Successfully sent email.') smtp_obj.quit() return True except smtplib.SMTPException: logging.exception('Authentication failed, unable to send email.') except (socket.gaierror, socket.error, socket.herror): logging.exception('Unable to send email.') return False
[ "def", "SendEmail", "(", "message", ",", "sender_email_address", ",", "receivers_email_address", ",", "subject", ")", ":", "try", ":", "html", "=", "'<html><head></head><body>%s</body></html>'", "%", "message", "msg", "=", "MIMEMultipart", "(", "'alternative'", ")", "msg", "[", "'Subject'", "]", "=", "subject", "msg", "[", "'From'", "]", "=", "sender_email_address", "msg", "[", "'To'", "]", "=", "receivers_email_address", "msg", ".", "attach", "(", "MIMEText", "(", "html", ".", "encode", "(", "'utf-8'", ")", ",", "'html'", ",", "_charset", "=", "'utf-8'", ")", ")", "smtp_obj", "=", "smtplib", ".", "SMTP", "(", "'localhost'", ")", "smtp_obj", ".", "sendmail", "(", "sender_email_address", ",", "receivers_email_address", ",", "msg", ".", "as_string", "(", ")", ")", "logging", ".", "info", "(", "'Successfully sent email.'", ")", "smtp_obj", ".", "quit", "(", ")", "return", "True", "except", "smtplib", ".", "SMTPException", ":", "logging", ".", "exception", "(", "'Authentication failed, unable to send email.'", ")", "except", "(", "socket", ".", "gaierror", ",", "socket", ".", "error", ",", "socket", ".", "herror", ")", ":", "logging", ".", "exception", "(", "'Unable to send email.'", ")", "return", "False" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/media/tools/bug_hunter/bug_hunter.py#L336-L366
qboticslabs/mastering_ros
d83e78f30acc45b0f18522c1d5fae3a7f52974b9
chapter_9_codes/chefbot/chefbot/chefbot_bringup/scripts/bkup_working/GoalsSequencer.py
python
SimpleGoalsFileParser._ParseFrameId
(self, trimmedLine)
return nameValueParts[1].strip()
Takes as input text like this: frame_id: /map
Takes as input text like this: frame_id: /map
[ "Takes", "as", "input", "text", "like", "this", ":", "frame_id", ":", "/", "map" ]
def _ParseFrameId(self, trimmedLine): ''' Takes as input text like this: frame_id: /map ''' nameValueParts = trimmedLine.split(':') if nameValueParts[0].strip() != 'frame_id': raise NameError('Expected variable name frame_id but found ' + nameValueParts[0].strip()) return nameValueParts[1].strip()
[ "def", "_ParseFrameId", "(", "self", ",", "trimmedLine", ")", ":", "nameValueParts", "=", "trimmedLine", ".", "split", "(", "':'", ")", "if", "nameValueParts", "[", "0", "]", ".", "strip", "(", ")", "!=", "'frame_id'", ":", "raise", "NameError", "(", "'Expected variable name frame_id but found '", "+", "nameValueParts", "[", "0", "]", ".", "strip", "(", ")", ")", "return", "nameValueParts", "[", "1", "]", ".", "strip", "(", ")" ]
https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_9_codes/chefbot/chefbot/chefbot_bringup/scripts/bkup_working/GoalsSequencer.py#L303-L312
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
IKObjective.link
(self)
return _robotsim.IKObjective_link(self)
link(IKObjective self) -> int The index of the robot link that is constrained.
link(IKObjective self) -> int
[ "link", "(", "IKObjective", "self", ")", "-", ">", "int" ]
def link(self): """ link(IKObjective self) -> int The index of the robot link that is constrained. """ return _robotsim.IKObjective_link(self)
[ "def", "link", "(", "self", ")", ":", "return", "_robotsim", ".", "IKObjective_link", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L6184-L6193
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
TreeCtrl.GetBoundingRect
(*args, **kwargs)
return _controls_.TreeCtrl_GetBoundingRect(*args, **kwargs)
GetBoundingRect(self, TreeItemId item, bool textOnly=False) -> PyObject
GetBoundingRect(self, TreeItemId item, bool textOnly=False) -> PyObject
[ "GetBoundingRect", "(", "self", "TreeItemId", "item", "bool", "textOnly", "=", "False", ")", "-", ">", "PyObject" ]
def GetBoundingRect(*args, **kwargs): """GetBoundingRect(self, TreeItemId item, bool textOnly=False) -> PyObject""" return _controls_.TreeCtrl_GetBoundingRect(*args, **kwargs)
[ "def", "GetBoundingRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_GetBoundingRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5550-L5552
greenheartgames/greenworks
3ea4ab490b56676de3f0a237c74bcfdb17323e60
deps/cpplint/cpplint.py
python
ParseArguments
(args)
return filenames
Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint.
Parses the command line arguments.
[ "Parses", "the", "command", "line", "arguments", "." ]
def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=', 'linelength=', 'extensions=', 'headers=']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' counting_style = '' for (opt, val) in opts: if opt == '--help': PrintUsage(None) elif opt == '--output': if val not in ('emacs', 'vs7', 'eclipse'): PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') output_format = val elif opt == '--verbose': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val elif opt == '--linelength': global _line_length try: _line_length = int(val) except ValueError: PrintUsage('Line length must be digits.') elif opt == '--extensions': global _valid_extensions try: _valid_extensions = set(val.split(',')) except ValueError: PrintUsage('Extensions must be comma seperated list.') elif opt == '--headers': ProcessHppHeadersOption(val) if not filenames: PrintUsage('No files were specified.') _SetOutputFormat(output_format) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames
[ "def", "ParseArguments", "(", "args", ")", ":", "try", ":", "(", "opts", ",", "filenames", ")", "=", "getopt", ".", "getopt", "(", "args", ",", "''", ",", "[", "'help'", ",", "'output='", ",", "'verbose='", ",", "'counting='", ",", "'filter='", ",", "'root='", ",", "'linelength='", ",", "'extensions='", ",", "'headers='", "]", ")", "except", "getopt", ".", "GetoptError", ":", "PrintUsage", "(", "'Invalid arguments.'", ")", "verbosity", "=", "_VerboseLevel", "(", ")", "output_format", "=", "_OutputFormat", "(", ")", "filters", "=", "''", "counting_style", "=", "''", "for", "(", "opt", ",", "val", ")", "in", "opts", ":", "if", "opt", "==", "'--help'", ":", "PrintUsage", "(", "None", ")", "elif", "opt", "==", "'--output'", ":", "if", "val", "not", "in", "(", "'emacs'", ",", "'vs7'", ",", "'eclipse'", ")", ":", "PrintUsage", "(", "'The only allowed output formats are emacs, vs7 and eclipse.'", ")", "output_format", "=", "val", "elif", "opt", "==", "'--verbose'", ":", "verbosity", "=", "int", "(", "val", ")", "elif", "opt", "==", "'--filter'", ":", "filters", "=", "val", "if", "not", "filters", ":", "PrintCategories", "(", ")", "elif", "opt", "==", "'--counting'", ":", "if", "val", "not", "in", "(", "'total'", ",", "'toplevel'", ",", "'detailed'", ")", ":", "PrintUsage", "(", "'Valid counting options are total, toplevel, and detailed'", ")", "counting_style", "=", "val", "elif", "opt", "==", "'--root'", ":", "global", "_root", "_root", "=", "val", "elif", "opt", "==", "'--linelength'", ":", "global", "_line_length", "try", ":", "_line_length", "=", "int", "(", "val", ")", "except", "ValueError", ":", "PrintUsage", "(", "'Line length must be digits.'", ")", "elif", "opt", "==", "'--extensions'", ":", "global", "_valid_extensions", "try", ":", "_valid_extensions", "=", "set", "(", "val", ".", "split", "(", "','", ")", ")", "except", "ValueError", ":", "PrintUsage", "(", "'Extensions must be comma seperated list.'", ")", "elif", "opt", "==", "'--headers'", ":", "ProcessHppHeadersOption", "(", "val", ")", "if", "not", "filenames", ":", "PrintUsage", "(", "'No files were specified.'", ")", "_SetOutputFormat", "(", "output_format", ")", "_SetVerboseLevel", "(", "verbosity", ")", "_SetFilters", "(", "filters", ")", "_SetCountingStyle", "(", "counting_style", ")", "return", "filenames" ]
https://github.com/greenheartgames/greenworks/blob/3ea4ab490b56676de3f0a237c74bcfdb17323e60/deps/cpplint/cpplint.py#L6062-L6132
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py
python
TypeKind.spelling
(self)
return conf.lib.clang_getTypeKindSpelling(self.value)
Retrieve the spelling of this TypeKind.
Retrieve the spelling of this TypeKind.
[ "Retrieve", "the", "spelling", "of", "this", "TypeKind", "." ]
def spelling(self): """Retrieve the spelling of this TypeKind.""" return conf.lib.clang_getTypeKindSpelling(self.value)
[ "def", "spelling", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTypeKindSpelling", "(", "self", ".", "value", ")" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/bindings/python/clang/cindex.py#L2023-L2025
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/symbol.py
python
Symbol.infer_type_partial
(self, *args, **kwargs)
return self._infer_type_impl(True, *args, **kwargs)
Infers the type partially. This functions works the same way as `infer_type`, except that this function can return partial results. In the following example, information about fc2 is not available. So, `infer_shape` will return a tuple of `None` values but `infer_shape_partial` will return partial values. Example ------- >>> data = mx.sym.Variable('data') >>> prev = mx.sym.Variable('prev') >>> casted_prev = mx.sym.cast(prev, dtype='float32') >>> out = mx.sym.Activation(data=mx.sym.elemwise_add(data, casted_prev), act_type='relu') >>> out.list_arguments() ['data', 'prev'] >>> out.infer_type(data='float32') (None, None, None) >>> out.infer_type_partial(data='float32') ([numpy.float32, None], [numpy.float32], []) >>> # infers type if you give information about prev >>> out.infer_type(data='float32', prev='float16') ([numpy.float32, numpy.float16], [numpy.float32], []) Parameters ---------- *args : Type of known arguments in a positional way. Unknown type can be marked as None. **kwargs : Keyword arguments of known types. Returns ------- arg_types : list of numpy.dtype or None List of argument types. The order is same as the order of list_arguments(). out_types : list of numpy.dtype or None List of output types. The order is same as the order of list_outputs(). aux_types : list of numpy.dtype or None List of auxiliary state types. The order is same as the order of list_auxiliary_states().
Infers the type partially.
[ "Infers", "the", "type", "partially", "." ]
def infer_type_partial(self, *args, **kwargs): """Infers the type partially. This functions works the same way as `infer_type`, except that this function can return partial results. In the following example, information about fc2 is not available. So, `infer_shape` will return a tuple of `None` values but `infer_shape_partial` will return partial values. Example ------- >>> data = mx.sym.Variable('data') >>> prev = mx.sym.Variable('prev') >>> casted_prev = mx.sym.cast(prev, dtype='float32') >>> out = mx.sym.Activation(data=mx.sym.elemwise_add(data, casted_prev), act_type='relu') >>> out.list_arguments() ['data', 'prev'] >>> out.infer_type(data='float32') (None, None, None) >>> out.infer_type_partial(data='float32') ([numpy.float32, None], [numpy.float32], []) >>> # infers type if you give information about prev >>> out.infer_type(data='float32', prev='float16') ([numpy.float32, numpy.float16], [numpy.float32], []) Parameters ---------- *args : Type of known arguments in a positional way. Unknown type can be marked as None. **kwargs : Keyword arguments of known types. Returns ------- arg_types : list of numpy.dtype or None List of argument types. The order is same as the order of list_arguments(). out_types : list of numpy.dtype or None List of output types. The order is same as the order of list_outputs(). aux_types : list of numpy.dtype or None List of auxiliary state types. The order is same as the order of list_auxiliary_states(). """ return self._infer_type_impl(True, *args, **kwargs)
[ "def", "infer_type_partial", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_infer_type_impl", "(", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/symbol.py#L967-L1013
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/commands/rsync.py
python
_RootListingExceptionHandler
(cls, e)
Simple exception handler for exceptions during listing URLs to sync.
Simple exception handler for exceptions during listing URLs to sync.
[ "Simple", "exception", "handler", "for", "exceptions", "during", "listing", "URLs", "to", "sync", "." ]
def _RootListingExceptionHandler(cls, e): """Simple exception handler for exceptions during listing URLs to sync.""" cls.logger.error(str(e))
[ "def", "_RootListingExceptionHandler", "(", "cls", ",", "e", ")", ":", "cls", ".", "logger", ".", "error", "(", "str", "(", "e", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/commands/rsync.py#L912-L914
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/diagonal-traverse-ii.py
python
Solution2.findDiagonalOrder
(self, nums)
return [num for row in result for num in reversed(row)]
:type nums: List[List[int]] :rtype: List[int]
:type nums: List[List[int]] :rtype: List[int]
[ ":", "type", "nums", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "int", "]" ]
def findDiagonalOrder(self, nums): """ :type nums: List[List[int]] :rtype: List[int] """ result = [] for r, row in enumerate(nums): for c, num in enumerate(row): if len(result) <= r+c: result.append([]) result[r+c].append(num) return [num for row in result for num in reversed(row)]
[ "def", "findDiagonalOrder", "(", "self", ",", "nums", ")", ":", "result", "=", "[", "]", "for", "r", ",", "row", "in", "enumerate", "(", "nums", ")", ":", "for", "c", ",", "num", "in", "enumerate", "(", "row", ")", ":", "if", "len", "(", "result", ")", "<=", "r", "+", "c", ":", "result", ".", "append", "(", "[", "]", ")", "result", "[", "r", "+", "c", "]", ".", "append", "(", "num", ")", "return", "[", "num", "for", "row", "in", "result", "for", "num", "in", "reversed", "(", "row", ")", "]" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/diagonal-traverse-ii.py#L30-L41
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/ops.py
python
name_scope
(name)
return get_default_graph().name_scope(name)
Wrapper for `Graph.name_scope()` using the default graph. See [`Graph.name_scope()`](../../api_docs/python/framework.md#Graph.name_scope) for more details. Args: name: A name for the scope. Returns: A context manager that installs `name` as a new name scope in the default graph.
Wrapper for `Graph.name_scope()` using the default graph.
[ "Wrapper", "for", "Graph", ".", "name_scope", "()", "using", "the", "default", "graph", "." ]
def name_scope(name): """Wrapper for `Graph.name_scope()` using the default graph. See [`Graph.name_scope()`](../../api_docs/python/framework.md#Graph.name_scope) for more details. Args: name: A name for the scope. Returns: A context manager that installs `name` as a new name scope in the default graph. """ return get_default_graph().name_scope(name)
[ "def", "name_scope", "(", "name", ")", ":", "return", "get_default_graph", "(", ")", ".", "name_scope", "(", "name", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L3467-L3481
microsoft/BlingFire
7634ad43b521ee6a596266d82c3f0c46cd43e222
ldbsrc/bert_base_tok/tokenization.py
python
BasicTokenizer.__init__
(self, do_lower_case=True)
Constructs a BasicTokenizer. Args: do_lower_case: Whether to lower case the input.
Constructs a BasicTokenizer.
[ "Constructs", "a", "BasicTokenizer", "." ]
def __init__(self, do_lower_case=True): """Constructs a BasicTokenizer. Args: do_lower_case: Whether to lower case the input. """ self.do_lower_case = do_lower_case
[ "def", "__init__", "(", "self", ",", "do_lower_case", "=", "True", ")", ":", "self", ".", "do_lower_case", "=", "do_lower_case" ]
https://github.com/microsoft/BlingFire/blob/7634ad43b521ee6a596266d82c3f0c46cd43e222/ldbsrc/bert_base_tok/tokenization.py#L188-L194
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/utils.py
python
LRUCache.itervalue
(self)
return iter(self.values())
Iterate over all values.
Iterate over all values.
[ "Iterate", "over", "all", "values", "." ]
def itervalue(self): """Iterate over all values.""" return iter(self.values())
[ "def", "itervalue", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "values", "(", ")", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/utils.py#L457-L459
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/compiler.py
python
CUDAKernelBase._serialize_config
(self)
return self.griddim, self.blockdim, self.sharedmem
Helper for serializing the grid, block and shared memory configuration. CUDA stream config is not serialized.
Helper for serializing the grid, block and shared memory configuration. CUDA stream config is not serialized.
[ "Helper", "for", "serializing", "the", "grid", "block", "and", "shared", "memory", "configuration", ".", "CUDA", "stream", "config", "is", "not", "serialized", "." ]
def _serialize_config(self): """ Helper for serializing the grid, block and shared memory configuration. CUDA stream config is not serialized. """ return self.griddim, self.blockdim, self.sharedmem
[ "def", "_serialize_config", "(", "self", ")", ":", "return", "self", ".", "griddim", ",", "self", ".", "blockdim", ",", "self", ".", "sharedmem" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/compiler.py#L362-L367
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/maximum-number-of-events-that-can-be-attended.py
python
Solution.maxEvents
(self, events)
return result
:type events: List[List[int]] :rtype: int
:type events: List[List[int]] :rtype: int
[ ":", "type", "events", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "int" ]
def maxEvents(self, events): """ :type events: List[List[int]] :rtype: int """ events.sort(reverse=True) min_heap = [] result = 0 for d in xrange(1, max(events, key=lambda x:x[1])[1]+1): while events and events[-1][0] == d: heapq.heappush(min_heap, events.pop()[1]) while min_heap and min_heap[0] == d-1: heapq.heappop(min_heap) if not min_heap: continue heapq.heappop(min_heap) result += 1 return result
[ "def", "maxEvents", "(", "self", ",", "events", ")", ":", "events", ".", "sort", "(", "reverse", "=", "True", ")", "min_heap", "=", "[", "]", "result", "=", "0", "for", "d", "in", "xrange", "(", "1", ",", "max", "(", "events", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "[", "1", "]", "+", "1", ")", ":", "while", "events", "and", "events", "[", "-", "1", "]", "[", "0", "]", "==", "d", ":", "heapq", ".", "heappush", "(", "min_heap", ",", "events", ".", "pop", "(", ")", "[", "1", "]", ")", "while", "min_heap", "and", "min_heap", "[", "0", "]", "==", "d", "-", "1", ":", "heapq", ".", "heappop", "(", "min_heap", ")", "if", "not", "min_heap", ":", "continue", "heapq", ".", "heappop", "(", "min_heap", ")", "result", "+=", "1", "return", "result" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-number-of-events-that-can-be-attended.py#L8-L25
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/completerlib.py
python
quick_completer
(cmd, completions)
r""" Easily create a trivial completer for a command. Takes either a list of completions, or all completions in string (that will be split on whitespace). Example:: [d:\ipython]|1> import ipy_completers [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) [d:\ipython]|3> foo b<TAB> bar baz [d:\ipython]|3> foo ba
r""" Easily create a trivial completer for a command.
[ "r", "Easily", "create", "a", "trivial", "completer", "for", "a", "command", "." ]
def quick_completer(cmd, completions): r""" Easily create a trivial completer for a command. Takes either a list of completions, or all completions in string (that will be split on whitespace). Example:: [d:\ipython]|1> import ipy_completers [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) [d:\ipython]|3> foo b<TAB> bar baz [d:\ipython]|3> foo ba """ if isinstance(completions, str): completions = completions.split() def do_complete(self, event): return completions get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
[ "def", "quick_completer", "(", "cmd", ",", "completions", ")", ":", "if", "isinstance", "(", "completions", ",", "str", ")", ":", "completions", "=", "completions", ".", "split", "(", ")", "def", "do_complete", "(", "self", ",", "event", ")", ":", "return", "completions", "get_ipython", "(", ")", ".", "set_hook", "(", "'complete_command'", ",", "do_complete", ",", "str_key", "=", "cmd", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/completerlib.py#L235-L256
numworks/epsilon
8952d2f8b1de1c3f064eec8ffcea804c5594ba4c
build/device/usb/legacy.py
python
DeviceHandle.interruptRead
(self, endpoint, size, timeout = 100)
return self.dev.read(endpoint, size, timeout)
r"""Performs a interrupt read request to the endpoint specified. Arguments: endpoint: endpoint number. size: number of bytes to read. timeout: operation timeout in milliseconds. (default: 100) Returns a tuple with the data read.
r"""Performs a interrupt read request to the endpoint specified.
[ "r", "Performs", "a", "interrupt", "read", "request", "to", "the", "endpoint", "specified", "." ]
def interruptRead(self, endpoint, size, timeout = 100): r"""Performs a interrupt read request to the endpoint specified. Arguments: endpoint: endpoint number. size: number of bytes to read. timeout: operation timeout in milliseconds. (default: 100) Returns a tuple with the data read. """ return self.dev.read(endpoint, size, timeout)
[ "def", "interruptRead", "(", "self", ",", "endpoint", ",", "size", ",", "timeout", "=", "100", ")", ":", "return", "self", ".", "dev", ".", "read", "(", "endpoint", ",", "size", ",", "timeout", ")" ]
https://github.com/numworks/epsilon/blob/8952d2f8b1de1c3f064eec8ffcea804c5594ba4c/build/device/usb/legacy.py#L181-L190
ispc/ispc
0a7ee59b6ec50e54d545eb2a31056e54c4891d51
common.py
python
TestTable.__init__
(self)
This dictionary contains {rev: [test1, test2, ...], ...}, where 'rev' is a string (revision name) and 'test#' is a Test() object instance
This dictionary contains {rev: [test1, test2, ...], ...}, where 'rev' is a string (revision name) and 'test#' is a Test() object instance
[ "This", "dictionary", "contains", "{", "rev", ":", "[", "test1", "test2", "...", "]", "...", "}", "where", "rev", "is", "a", "string", "(", "revision", "name", ")", "and", "test#", "is", "a", "Test", "()", "object", "instance" ]
def __init__(self): """ This dictionary contains {rev: [test1, test2, ...], ...}, where 'rev' is a string (revision name) and 'test#' is a Test() object instance """ self.table = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "table", "=", "{", "}" ]
https://github.com/ispc/ispc/blob/0a7ee59b6ec50e54d545eb2a31056e54c4891d51/common.py#L315-L318
scylladb/seastar
0cdd2329beb1cc4c0af8828598c26114397ffa9c
scripts/perftune.py
python
PerfTunerBase.irqs_cpu_mask
(self)
return self.__irq_cpu_mask
Return the mask of CPUs used for IRQs distribution.
Return the mask of CPUs used for IRQs distribution.
[ "Return", "the", "mask", "of", "CPUs", "used", "for", "IRQs", "distribution", "." ]
def irqs_cpu_mask(self): """ Return the mask of CPUs used for IRQs distribution. """ # see the __set_mode_and_masks() description if self.__irq_cpu_mask is None: self.__set_mode_and_masks() return self.__irq_cpu_mask
[ "def", "irqs_cpu_mask", "(", "self", ")", ":", "# see the __set_mode_and_masks() description", "if", "self", ".", "__irq_cpu_mask", "is", "None", ":", "self", ".", "__set_mode_and_masks", "(", ")", "return", "self", ".", "__irq_cpu_mask" ]
https://github.com/scylladb/seastar/blob/0cdd2329beb1cc4c0af8828598c26114397ffa9c/scripts/perftune.py#L395-L403
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ast.py
python
fix_missing_locations
(node)
return node
When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*.
When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*.
[ "When", "you", "compile", "a", "node", "tree", "with", "compile", "()", "the", "compiler", "expects", "lineno", "and", "col_offset", "attributes", "for", "every", "node", "that", "supports", "them", ".", "This", "is", "rather", "tedious", "to", "fill", "in", "for", "generated", "nodes", "so", "this", "helper", "adds", "these", "attributes", "recursively", "where", "not", "already", "set", "by", "setting", "them", "to", "the", "values", "of", "the", "parent", "node", ".", "It", "works", "recursively", "starting", "at", "*", "node", "*", "." ]
def fix_missing_locations(node): """ When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*. """ def _fix(node, lineno, col_offset): if 'lineno' in node._attributes: if not hasattr(node, 'lineno'): node.lineno = lineno else: lineno = node.lineno if 'col_offset' in node._attributes: if not hasattr(node, 'col_offset'): node.col_offset = col_offset else: col_offset = node.col_offset for child in iter_child_nodes(node): _fix(child, lineno, col_offset) _fix(node, 1, 0) return node
[ "def", "fix_missing_locations", "(", "node", ")", ":", "def", "_fix", "(", "node", ",", "lineno", ",", "col_offset", ")", ":", "if", "'lineno'", "in", "node", ".", "_attributes", ":", "if", "not", "hasattr", "(", "node", ",", "'lineno'", ")", ":", "node", ".", "lineno", "=", "lineno", "else", ":", "lineno", "=", "node", ".", "lineno", "if", "'col_offset'", "in", "node", ".", "_attributes", ":", "if", "not", "hasattr", "(", "node", ",", "'col_offset'", ")", ":", "node", ".", "col_offset", "=", "col_offset", "else", ":", "col_offset", "=", "node", ".", "col_offset", "for", "child", "in", "iter_child_nodes", "(", "node", ")", ":", "_fix", "(", "child", ",", "lineno", ",", "col_offset", ")", "_fix", "(", "node", ",", "1", ",", "0", ")", "return", "node" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ast.py#L125-L147
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/auto_bisect/builder.py
python
BuildWithVisualStudio
(targets, build_type='Release')
return not return_code
Runs a command to build the given targets with Visual Studio.
Runs a command to build the given targets with Visual Studio.
[ "Runs", "a", "command", "to", "build", "the", "given", "targets", "with", "Visual", "Studio", "." ]
def BuildWithVisualStudio(targets, build_type='Release'): """Runs a command to build the given targets with Visual Studio.""" path_to_devenv = os.path.abspath( os.path.join(os.environ['VS100COMNTOOLS'], '..', 'IDE', 'devenv.com')) path_to_sln = os.path.join(os.getcwd(), 'chrome', 'chrome.sln') cmd = [path_to_devenv, '/build', build_type, path_to_sln] for t in targets: cmd.extend(['/Project', t]) return_code = bisect_utils.RunProcess(cmd) return not return_code
[ "def", "BuildWithVisualStudio", "(", "targets", ",", "build_type", "=", "'Release'", ")", ":", "path_to_devenv", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'VS100COMNTOOLS'", "]", ",", "'..'", ",", "'IDE'", ",", "'devenv.com'", ")", ")", "path_to_sln", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "'chrome'", ",", "'chrome.sln'", ")", "cmd", "=", "[", "path_to_devenv", ",", "'/build'", ",", "build_type", ",", "path_to_sln", "]", "for", "t", "in", "targets", ":", "cmd", ".", "extend", "(", "[", "'/Project'", ",", "t", "]", ")", "return_code", "=", "bisect_utils", ".", "RunProcess", "(", "cmd", ")", "return", "not", "return_code" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/auto_bisect/builder.py#L282-L291
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/errors.py
python
PermissionDeniedError.__init__
(self, node_def, op, message)
Creates a `PermissionDeniedError`.
Creates a `PermissionDeniedError`.
[ "Creates", "a", "PermissionDeniedError", "." ]
def __init__(self, node_def, op, message): """Creates a `PermissionDeniedError`.""" super(PermissionDeniedError, self).__init__(node_def, op, message, PERMISSION_DENIED)
[ "def", "__init__", "(", "self", ",", "node_def", ",", "op", ",", "message", ")", ":", "super", "(", "PermissionDeniedError", ",", "self", ")", ".", "__init__", "(", "node_def", ",", "op", ",", "message", ",", "PERMISSION_DENIED", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/errors.py#L265-L268
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py
python
dictOf
( key, value )
return Dict(OneOrMore(Group(key + value)))
Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the :class:`Dict`, :class:`ZeroOrMore`, and :class:`Group` tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the :class:`Dict` results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the :class:`Dict`, :class:`ZeroOrMore`, and :class:`Group` tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the :class:`Dict` results can include named token fields.
[ "Helper", "to", "easily", "and", "clearly", "define", "a", "dictionary", "by", "specifying", "the", "respective", "patterns", "for", "the", "key", "and", "value", ".", "Takes", "care", "of", "defining", "the", ":", "class", ":", "Dict", ":", "class", ":", "ZeroOrMore", "and", ":", "class", ":", "Group", "tokens", "in", "the", "proper", "order", ".", "The", "key", "pattern", "can", "include", "delimiting", "markers", "or", "punctuation", "as", "long", "as", "they", "are", "suppressed", "thereby", "leaving", "the", "significant", "key", "text", ".", "The", "value", "pattern", "can", "include", "named", "results", "so", "that", "the", ":", "class", ":", "Dict", "results", "can", "include", "named", "token", "fields", "." ]
def dictOf( key, value ): """Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the :class:`Dict`, :class:`ZeroOrMore`, and :class:`Group` tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the :class:`Dict` results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} """ return Dict(OneOrMore(Group(key + value)))
[ "def", "dictOf", "(", "key", ",", "value", ")", ":", "return", "Dict", "(", "OneOrMore", "(", "Group", "(", "key", "+", "value", ")", ")", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/pyparsing.py#L5107-L5144
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/data_parallel_model.py
python
_GroupByDevice
(model, devices, params, non_data_params)
return grouped
Groups blobs by device, returning a map of [blobname] = {0: BlobRef, 1: ..}. Returns ordered dictionary, ensuring the original order.
Groups blobs by device, returning a map of [blobname] = {0: BlobRef, 1: ..}. Returns ordered dictionary, ensuring the original order.
[ "Groups", "blobs", "by", "device", "returning", "a", "map", "of", "[", "blobname", "]", "=", "{", "0", ":", "BlobRef", "1", ":", "..", "}", ".", "Returns", "ordered", "dictionary", "ensuring", "the", "original", "order", "." ]
def _GroupByDevice(model, devices, params, non_data_params): ''' Groups blobs by device, returning a map of [blobname] = {0: BlobRef, 1: ..}. Returns ordered dictionary, ensuring the original order. ''' grouped = OrderedDict() # Only consider params that were created to be "data parallel" params = params[len(non_data_params):] for _i, p in enumerate(params): assert isinstance(p, core.BlobReference) or \ isinstance(p, core.GradientSlice), \ "Param {} is not BlobReference or GradientSlice".format(p) name = stripBlobName(p) gpuid = None if isinstance(p, core.BlobReference): gpuid = int(p.GetNameScope().split("_")[1].split("/")[0]) assert "{}_{}/".format(model._device_prefix, gpuid) in p.GetNameScope(),\ "Param {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid) else: gpuid = int(p.indices.GetNameScope().split("_")[1].split("/")[0]) assert "{}_{}/".format(model._device_prefix, gpuid) in p.indices.GetNameScope(),\ "Indices {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid) assert "{}_{}/".format(model._device_prefix, gpuid) in p.values.GetNameScope(),\ "Values {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid) if name not in grouped: grouped[name] = {} grouped[name][gpuid] = p return grouped
[ "def", "_GroupByDevice", "(", "model", ",", "devices", ",", "params", ",", "non_data_params", ")", ":", "grouped", "=", "OrderedDict", "(", ")", "# Only consider params that were created to be \"data parallel\"", "params", "=", "params", "[", "len", "(", "non_data_params", ")", ":", "]", "for", "_i", ",", "p", "in", "enumerate", "(", "params", ")", ":", "assert", "isinstance", "(", "p", ",", "core", ".", "BlobReference", ")", "or", "isinstance", "(", "p", ",", "core", ".", "GradientSlice", ")", ",", "\"Param {} is not BlobReference or GradientSlice\"", ".", "format", "(", "p", ")", "name", "=", "stripBlobName", "(", "p", ")", "gpuid", "=", "None", "if", "isinstance", "(", "p", ",", "core", ".", "BlobReference", ")", ":", "gpuid", "=", "int", "(", "p", ".", "GetNameScope", "(", ")", ".", "split", "(", "\"_\"", ")", "[", "1", "]", ".", "split", "(", "\"/\"", ")", "[", "0", "]", ")", "assert", "\"{}_{}/\"", ".", "format", "(", "model", ".", "_device_prefix", ",", "gpuid", ")", "in", "p", ".", "GetNameScope", "(", ")", ",", "\"Param {} expected to have namescope '{}_{}'\"", ".", "format", "(", "str", "(", "p", ")", ",", "model", ".", "_device_prefix", ",", "gpuid", ")", "else", ":", "gpuid", "=", "int", "(", "p", ".", "indices", ".", "GetNameScope", "(", ")", ".", "split", "(", "\"_\"", ")", "[", "1", "]", ".", "split", "(", "\"/\"", ")", "[", "0", "]", ")", "assert", "\"{}_{}/\"", ".", "format", "(", "model", ".", "_device_prefix", ",", "gpuid", ")", "in", "p", ".", "indices", ".", "GetNameScope", "(", ")", ",", "\"Indices {} expected to have namescope '{}_{}'\"", ".", "format", "(", "str", "(", "p", ")", ",", "model", ".", "_device_prefix", ",", "gpuid", ")", "assert", "\"{}_{}/\"", ".", "format", "(", "model", ".", "_device_prefix", ",", "gpuid", ")", "in", "p", ".", "values", ".", "GetNameScope", "(", ")", ",", "\"Values {} expected to have namescope '{}_{}'\"", ".", "format", "(", "str", "(", "p", ")", ",", "model", ".", "_device_prefix", ",", "gpuid", ")", "if", "name", "not", "in", "grouped", ":", "grouped", "[", "name", "]", "=", "{", "}", "grouped", "[", "name", "]", "[", "gpuid", "]", "=", "p", "return", "grouped" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/data_parallel_model.py#L1644-L1676
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
js/xpconnect/src/qsgen.py
python
isSpecificInterfaceType
(t, name)
return t.kind in ('interface', 'forward') and t.name == name
True if `t` is an interface type with the given name, or a forward declaration or typedef aliasing it. `name` must not be the name of a typedef but the actual name of the interface.
True if `t` is an interface type with the given name, or a forward declaration or typedef aliasing it.
[ "True", "if", "t", "is", "an", "interface", "type", "with", "the", "given", "name", "or", "a", "forward", "declaration", "or", "typedef", "aliasing", "it", "." ]
def isSpecificInterfaceType(t, name): """ True if `t` is an interface type with the given name, or a forward declaration or typedef aliasing it. `name` must not be the name of a typedef but the actual name of the interface. """ t = unaliasType(t) return t.kind in ('interface', 'forward') and t.name == name
[ "def", "isSpecificInterfaceType", "(", "t", ",", "name", ")", ":", "t", "=", "unaliasType", "(", "t", ")", "return", "t", ".", "kind", "in", "(", "'interface'", ",", "'forward'", ")", "and", "t", ".", "name", "==", "name" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/js/xpconnect/src/qsgen.py#L111-L119
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/util.py
python
EventMixin.get_subscribers
(self, event)
return iter(self._subscribers.get(event, ()))
Return an iterator for the subscribers for an event. :param event: The event to return subscribers for.
[]
def get_subscribers(self, event): """ Return an iterator for the subscribers for an event. :param event: The event to return subscribers for. """ return iter(self._subscribers.get(event, ()))
[ "def", "get_subscribers", "(", "self", ",", "event", ")", ":", "return", "iter", "(", "self", ".", "_subscribers", ".", "get", "(", "event", ",", "(", ")", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/util.py#L2047-L2057
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ConfigParser.py
python
RawConfigParser.sections
(self)
return self._sections.keys()
Return a list of section names, excluding [DEFAULT]
Return a list of section names, excluding [DEFAULT]
[ "Return", "a", "list", "of", "section", "names", "excluding", "[", "DEFAULT", "]" ]
def sections(self): """Return a list of section names, excluding [DEFAULT]""" # self._sections will never have [DEFAULT] in it return self._sections.keys()
[ "def", "sections", "(", "self", ")", ":", "# self._sections will never have [DEFAULT] in it", "return", "self", ".", "_sections", ".", "keys", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ConfigParser.py#L248-L251
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Modules/Scripted/EditorLib/MakeModelEffect.py
python
MakeModelEffectOptions.updateParameterNode
(self, caller, event)
note: this method needs to be implemented exactly as defined in the leaf classes in EditOptions.py in each leaf subclass so that "self" in the observer is of the correct type
note: this method needs to be implemented exactly as defined in the leaf classes in EditOptions.py in each leaf subclass so that "self" in the observer is of the correct type
[ "note", ":", "this", "method", "needs", "to", "be", "implemented", "exactly", "as", "defined", "in", "the", "leaf", "classes", "in", "EditOptions", ".", "py", "in", "each", "leaf", "subclass", "so", "that", "self", "in", "the", "observer", "is", "of", "the", "correct", "type" ]
def updateParameterNode(self, caller, event): """ note: this method needs to be implemented exactly as defined in the leaf classes in EditOptions.py in each leaf subclass so that "self" in the observer is of the correct type """ node = EditUtil.getParameterNode() if node != self.parameterNode: if self.parameterNode: node.RemoveObserver(self.parameterNodeTag) self.parameterNode = node self.parameterNodeTag = node.AddObserver(vtk.vtkCommand.ModifiedEvent, self.updateGUIFromMRML)
[ "def", "updateParameterNode", "(", "self", ",", "caller", ",", "event", ")", ":", "node", "=", "EditUtil", ".", "getParameterNode", "(", ")", "if", "node", "!=", "self", ".", "parameterNode", ":", "if", "self", ".", "parameterNode", ":", "node", ".", "RemoveObserver", "(", "self", ".", "parameterNodeTag", ")", "self", ".", "parameterNode", "=", "node", "self", ".", "parameterNodeTag", "=", "node", ".", "AddObserver", "(", "vtk", ".", "vtkCommand", ".", "ModifiedEvent", ",", "self", ".", "updateGUIFromMRML", ")" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/EditorLib/MakeModelEffect.py#L97-L108
raymondlu/super-animation-samples
04234269112ff0dc32447f27a761dbbb00b8ba17
samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
TranslationUnit.get_extent
(self, filename, locations)
return SourceRange.from_locations(start_location, end_location)
Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15)))
Obtain a SourceRange from this translation unit.
[ "Obtain", "a", "SourceRange", "from", "this", "translation", "unit", "." ]
def get_extent(self, filename, locations): """Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15))) """ f = self.get_file(filename) if len(locations) < 2: raise Exception('Must pass object with at least 2 elements') start_location, end_location = locations if hasattr(start_location, '__len__'): start_location = SourceLocation.from_position(self, f, start_location[0], start_location[1]) elif isinstance(start_location, int): start_location = SourceLocation.from_offset(self, f, start_location) if hasattr(end_location, '__len__'): end_location = SourceLocation.from_position(self, f, end_location[0], end_location[1]) elif isinstance(end_location, int): end_location = SourceLocation.from_offset(self, f, end_location) assert isinstance(start_location, SourceLocation) assert isinstance(end_location, SourceLocation) return SourceRange.from_locations(start_location, end_location)
[ "def", "get_extent", "(", "self", ",", "filename", ",", "locations", ")", ":", "f", "=", "self", ".", "get_file", "(", "filename", ")", "if", "len", "(", "locations", ")", "<", "2", ":", "raise", "Exception", "(", "'Must pass object with at least 2 elements'", ")", "start_location", ",", "end_location", "=", "locations", "if", "hasattr", "(", "start_location", ",", "'__len__'", ")", ":", "start_location", "=", "SourceLocation", ".", "from_position", "(", "self", ",", "f", ",", "start_location", "[", "0", "]", ",", "start_location", "[", "1", "]", ")", "elif", "isinstance", "(", "start_location", ",", "int", ")", ":", "start_location", "=", "SourceLocation", ".", "from_offset", "(", "self", ",", "f", ",", "start_location", ")", "if", "hasattr", "(", "end_location", ",", "'__len__'", ")", ":", "end_location", "=", "SourceLocation", ".", "from_position", "(", "self", ",", "f", ",", "end_location", "[", "0", "]", ",", "end_location", "[", "1", "]", ")", "elif", "isinstance", "(", "end_location", ",", "int", ")", ":", "end_location", "=", "SourceLocation", ".", "from_offset", "(", "self", ",", "f", ",", "end_location", ")", "assert", "isinstance", "(", "start_location", ",", "SourceLocation", ")", "assert", "isinstance", "(", "end_location", ",", "SourceLocation", ")", "return", "SourceRange", ".", "from_locations", "(", "start_location", ",", "end_location", ")" ]
https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L2139-L2177
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/check_scalar_to_nodes_process.py
python
CheckScalarToNodesProcess.__init__
(self, Model, settings )
The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings.
The default constructor of the class
[ "The", "default", "constructor", "of", "the", "class" ]
def __init__(self, Model, settings ): """ The default constructor of the class Keyword arguments: self -- It signifies an instance of a class. Model -- the container of the different model parts. settings -- Kratos parameters containing solver settings. """ default_settings = KratosMultiphysics.Parameters(""" { "help" : "This process checks analytically from a function the solution (scalar) in a set of nodes belonging a certain submodelpart", "mesh_id" : 0, "model_part_name" : "please_specify_model_part_name", "variable_name" : "SPECIFY_VARIABLE_NAME", "interval" : [0.0, 1e30], "value" : 0.0, "tolerance_rank" : 3, "reference_conf" : false, "local_axes" : {} } """ ) # We transfer the parameters to the base class base_settings = KratosMultiphysics.Parameters("""{}""") if settings.Has("model_part_name"): base_settings.AddValue("model_part_name", settings["model_part_name"]) if settings.Has("variable_name"): base_settings.AddValue("variable_name", settings["variable_name"]) if settings.Has("interval"): base_settings.AddValue("interval", settings["interval"]) if settings.Has("value"): base_settings.AddValue("value", settings["value"]) if settings.Has("tolerance_rank"): base_settings.AddValue("tolerance_rank", settings["tolerance_rank"]) # Construct the base process super(CheckScalarToNodesProcess, self).__init__(Model, base_settings) # Copy from input self.settings = settings # Here i do a trick, since i want to allow "value" to be a string or a double value if(self.settings.Has("value")): if(self.settings["value"].IsString()): default_settings["value"].SetString("0.0") # Validate and assign self.settings.ValidateAndAssignDefaults(default_settings) # Admissible values for local axes, are "empty" or #"local_axes" :{ # "origin" : [0.0, 0.0, 0.0] # "axes" : [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0] ] # } self.non_trivial_local_system = False if(self.settings["local_axes"].Has("origin")): # not empty self.non_trivial_local_system = True self.R = KratosMultiphysics.Matrix(3,3) self.R[0,0] = self.settings["local_axes"]["axes"][0][0].GetDouble() self.R[0,1] = self.settings["local_axes"]["axes"][0][1].GetDouble() self.R[0,2] = self.settings["local_axes"]["axes"][0][2].GetDouble() self.R[1,0] = self.settings["local_axes"]["axes"][1][0].GetDouble() self.R[1,1] = self.settings["local_axes"]["axes"][1][1].GetDouble() self.R[1,2] = self.settings["local_axes"]["axes"][1][2].GetDouble() self.R[2,0] = self.settings["local_axes"]["axes"][2][0].GetDouble() self.R[2,1] = self.settings["local_axes"]["axes"][2][1].GetDouble() self.R[2,2] = self.settings["local_axes"]["axes"][2][2].GetDouble() self.x0 = KratosMultiphysics.Vector(3) self.x0[0] = self.settings["local_axes"]["origin"][0].GetDouble() self.x0[1] = self.settings["local_axes"]["origin"][1].GetDouble() self.x0[2] = self.settings["local_axes"]["origin"][2].GetDouble() # Getting the mesh self.mesh = self.model_part.GetMesh(self.settings["mesh_id"].GetInt()) # Getting reference configuration self.reference_configuration = self.settings["reference_conf"].GetBool()
[ "def", "__init__", "(", "self", ",", "Model", ",", "settings", ")", ":", "default_settings", "=", "KratosMultiphysics", ".", "Parameters", "(", "\"\"\"\n {\n \"help\" : \"This process checks analytically from a function the solution (scalar) in a set of nodes belonging a certain submodelpart\",\n \"mesh_id\" : 0,\n \"model_part_name\" : \"please_specify_model_part_name\",\n \"variable_name\" : \"SPECIFY_VARIABLE_NAME\",\n \"interval\" : [0.0, 1e30],\n \"value\" : 0.0,\n \"tolerance_rank\" : 3,\n \"reference_conf\" : false,\n \"local_axes\" : {}\n }\n \"\"\"", ")", "# We transfer the parameters to the base class", "base_settings", "=", "KratosMultiphysics", ".", "Parameters", "(", "\"\"\"{}\"\"\"", ")", "if", "settings", ".", "Has", "(", "\"model_part_name\"", ")", ":", "base_settings", ".", "AddValue", "(", "\"model_part_name\"", ",", "settings", "[", "\"model_part_name\"", "]", ")", "if", "settings", ".", "Has", "(", "\"variable_name\"", ")", ":", "base_settings", ".", "AddValue", "(", "\"variable_name\"", ",", "settings", "[", "\"variable_name\"", "]", ")", "if", "settings", ".", "Has", "(", "\"interval\"", ")", ":", "base_settings", ".", "AddValue", "(", "\"interval\"", ",", "settings", "[", "\"interval\"", "]", ")", "if", "settings", ".", "Has", "(", "\"value\"", ")", ":", "base_settings", ".", "AddValue", "(", "\"value\"", ",", "settings", "[", "\"value\"", "]", ")", "if", "settings", ".", "Has", "(", "\"tolerance_rank\"", ")", ":", "base_settings", ".", "AddValue", "(", "\"tolerance_rank\"", ",", "settings", "[", "\"tolerance_rank\"", "]", ")", "# Construct the base process", "super", "(", "CheckScalarToNodesProcess", ",", "self", ")", ".", "__init__", "(", "Model", ",", "base_settings", ")", "# Copy from input", "self", ".", "settings", "=", "settings", "# Here i do a trick, since i want to allow \"value\" to be a string or a double value", "if", "(", "self", ".", "settings", ".", "Has", "(", "\"value\"", ")", ")", ":", "if", "(", "self", ".", "settings", "[", "\"value\"", "]", ".", "IsString", "(", ")", ")", ":", "default_settings", "[", "\"value\"", "]", ".", "SetString", "(", "\"0.0\"", ")", "# Validate and assign", "self", ".", "settings", ".", "ValidateAndAssignDefaults", "(", "default_settings", ")", "# Admissible values for local axes, are \"empty\" or", "#\"local_axes\" :{", "# \"origin\" : [0.0, 0.0, 0.0]", "# \"axes\" : [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0] ]", "# }", "self", ".", "non_trivial_local_system", "=", "False", "if", "(", "self", ".", "settings", "[", "\"local_axes\"", "]", ".", "Has", "(", "\"origin\"", ")", ")", ":", "# not empty", "self", ".", "non_trivial_local_system", "=", "True", "self", ".", "R", "=", "KratosMultiphysics", ".", "Matrix", "(", "3", ",", "3", ")", "self", ".", "R", "[", "0", ",", "0", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "0", "]", "[", "0", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "0", ",", "1", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "0", "]", "[", "1", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "0", ",", "2", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "0", "]", "[", "2", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "1", ",", "0", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "1", "]", "[", "0", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "1", ",", "1", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "1", "]", "[", "1", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "1", ",", "2", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "1", "]", "[", "2", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "2", ",", "0", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "2", "]", "[", "0", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "2", ",", "1", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "2", "]", "[", "1", "]", ".", "GetDouble", "(", ")", "self", ".", "R", "[", "2", ",", "2", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"axes\"", "]", "[", "2", "]", "[", "2", "]", ".", "GetDouble", "(", ")", "self", ".", "x0", "=", "KratosMultiphysics", ".", "Vector", "(", "3", ")", "self", ".", "x0", "[", "0", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"origin\"", "]", "[", "0", "]", ".", "GetDouble", "(", ")", "self", ".", "x0", "[", "1", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"origin\"", "]", "[", "1", "]", ".", "GetDouble", "(", ")", "self", ".", "x0", "[", "2", "]", "=", "self", ".", "settings", "[", "\"local_axes\"", "]", "[", "\"origin\"", "]", "[", "2", "]", ".", "GetDouble", "(", ")", "# Getting the mesh", "self", ".", "mesh", "=", "self", ".", "model_part", ".", "GetMesh", "(", "self", ".", "settings", "[", "\"mesh_id\"", "]", ".", "GetInt", "(", ")", ")", "# Getting reference configuration", "self", ".", "reference_configuration", "=", "self", ".", "settings", "[", "\"reference_conf\"", "]", ".", "GetBool", "(", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/check_scalar_to_nodes_process.py#L23-L102
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connection.py
python
HTTPConnection.host
(self)
return self._dns_host.rstrip(".")
Getter method to remove any trailing dots that indicate the hostname is an FQDN. In general, SSL certificates don't include the trailing dot indicating a fully-qualified domain name, and thus, they don't validate properly when checked against a domain name that includes the dot. In addition, some servers may not expect to receive the trailing dot when provided. However, the hostname with trailing dot is critical to DNS resolution; doing a lookup with the trailing dot will properly only resolve the appropriate FQDN, whereas a lookup without a trailing dot will search the system's search domain list. Thus, it's important to keep the original host around for use only in those cases where it's appropriate (i.e., when doing DNS lookup to establish the actual TCP connection across which we're going to send HTTP requests).
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
[ "Getter", "method", "to", "remove", "any", "trailing", "dots", "that", "indicate", "the", "hostname", "is", "an", "FQDN", "." ]
def host(self): """ Getter method to remove any trailing dots that indicate the hostname is an FQDN. In general, SSL certificates don't include the trailing dot indicating a fully-qualified domain name, and thus, they don't validate properly when checked against a domain name that includes the dot. In addition, some servers may not expect to receive the trailing dot when provided. However, the hostname with trailing dot is critical to DNS resolution; doing a lookup with the trailing dot will properly only resolve the appropriate FQDN, whereas a lookup without a trailing dot will search the system's search domain list. Thus, it's important to keep the original host around for use only in those cases where it's appropriate (i.e., when doing DNS lookup to establish the actual TCP connection across which we're going to send HTTP requests). """ return self._dns_host.rstrip(".")
[ "def", "host", "(", "self", ")", ":", "return", "self", ".", "_dns_host", ".", "rstrip", "(", "\".\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connection.py#L115-L131
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
Region.UnionBitmap
(*args, **kwargs)
return _gdi_.Region_UnionBitmap(*args, **kwargs)
UnionBitmap(self, Bitmap bmp) -> bool
UnionBitmap(self, Bitmap bmp) -> bool
[ "UnionBitmap", "(", "self", "Bitmap", "bmp", ")", "-", ">", "bool" ]
def UnionBitmap(*args, **kwargs): """UnionBitmap(self, Bitmap bmp) -> bool""" return _gdi_.Region_UnionBitmap(*args, **kwargs)
[ "def", "UnionBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Region_UnionBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L1635-L1637
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/script_ops.py
python
FuncRegistry.remove
(self, token)
Removes the registered function corresponding to `token`.
Removes the registered function corresponding to `token`.
[ "Removes", "the", "registered", "function", "corresponding", "to", "token", "." ]
def remove(self, token): """Removes the registered function corresponding to `token`.""" self._funcs.pop(token, None)
[ "def", "remove", "(", "self", ",", "token", ")", ":", "self", ".", "_funcs", ".", "pop", "(", "token", ",", "None", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/script_ops.py#L173-L175
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/misc.py
python
NoneType.unify
(self, typingctx, other)
return Optional(other)
Turn anything to a Optional type;
Turn anything to a Optional type;
[ "Turn", "anything", "to", "a", "Optional", "type", ";" ]
def unify(self, typingctx, other): """ Turn anything to a Optional type; """ if isinstance(other, (Optional, NoneType)): return other return Optional(other)
[ "def", "unify", "(", "self", ",", "typingctx", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "(", "Optional", ",", "NoneType", ")", ")", ":", "return", "other", "return", "Optional", "(", "other", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/misc.py#L260-L266
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/base/MooseWidget.py
python
MooseWidget.stateKey
(self)
return 'default'
Return a unique "key" for saving widget state, see ExodusPlugin.
Return a unique "key" for saving widget state, see ExodusPlugin.
[ "Return", "a", "unique", "key", "for", "saving", "widget", "state", "see", "ExodusPlugin", "." ]
def stateKey(self): """ Return a unique "key" for saving widget state, see ExodusPlugin. """ return 'default'
[ "def", "stateKey", "(", "self", ")", ":", "return", "'default'" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/base/MooseWidget.py#L71-L75
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/resample.py
python
DatetimeIndexResampler._downsample
(self, how, **kwargs)
return self._wrap_result(result)
Downsample the cython defined function. Parameters ---------- how : string / cython mapped function **kwargs : kw args passed to how function
Downsample the cython defined function.
[ "Downsample", "the", "cython", "defined", "function", "." ]
def _downsample(self, how, **kwargs): """ Downsample the cython defined function. Parameters ---------- how : string / cython mapped function **kwargs : kw args passed to how function """ how = com.get_cython_func(how) or how ax = self.ax obj = self._selected_obj if not len(ax): # reset to the new freq obj = obj.copy() obj.index = obj.index._with_freq(self.freq) assert obj.index.freq == self.freq, (obj.index.freq, self.freq) return obj # do we have a regular frequency # error: Item "None" of "Optional[Any]" has no attribute "binlabels" if ( (ax.freq is not None or ax.inferred_freq is not None) and len(self.grouper.binlabels) > len(ax) and how is None ): # let's do an asfreq return self.asfreq() # we are downsampling # we want to call the actual grouper method here result = obj.groupby(self.grouper, axis=self.axis).aggregate(how, **kwargs) result = self._apply_loffset(result) return self._wrap_result(result)
[ "def", "_downsample", "(", "self", ",", "how", ",", "*", "*", "kwargs", ")", ":", "how", "=", "com", ".", "get_cython_func", "(", "how", ")", "or", "how", "ax", "=", "self", ".", "ax", "obj", "=", "self", ".", "_selected_obj", "if", "not", "len", "(", "ax", ")", ":", "# reset to the new freq", "obj", "=", "obj", ".", "copy", "(", ")", "obj", ".", "index", "=", "obj", ".", "index", ".", "_with_freq", "(", "self", ".", "freq", ")", "assert", "obj", ".", "index", ".", "freq", "==", "self", ".", "freq", ",", "(", "obj", ".", "index", ".", "freq", ",", "self", ".", "freq", ")", "return", "obj", "# do we have a regular frequency", "# error: Item \"None\" of \"Optional[Any]\" has no attribute \"binlabels\"", "if", "(", "(", "ax", ".", "freq", "is", "not", "None", "or", "ax", ".", "inferred_freq", "is", "not", "None", ")", "and", "len", "(", "self", ".", "grouper", ".", "binlabels", ")", ">", "len", "(", "ax", ")", "and", "how", "is", "None", ")", ":", "# let's do an asfreq", "return", "self", ".", "asfreq", "(", ")", "# we are downsampling", "# we want to call the actual grouper method here", "result", "=", "obj", ".", "groupby", "(", "self", ".", "grouper", ",", "axis", "=", "self", ".", "axis", ")", ".", "aggregate", "(", "how", ",", "*", "*", "kwargs", ")", "result", "=", "self", ".", "_apply_loffset", "(", "result", ")", "return", "self", ".", "_wrap_result", "(", "result", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/resample.py#L1115-L1152
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py
python
_RealValuedVarLenColumn._normalized_input_tensor
(self, input_tensor)
Returns the input tensor after custom normalization is applied.
Returns the input tensor after custom normalization is applied.
[ "Returns", "the", "input", "tensor", "after", "custom", "normalization", "is", "applied", "." ]
def _normalized_input_tensor(self, input_tensor): """Returns the input tensor after custom normalization is applied.""" if self.normalizer is None: return input_tensor if self.is_sparse: return sparse_tensor_py.SparseTensor(input_tensor.indices, self.normalizer(input_tensor.values), input_tensor.dense_shape) else: return self.normalizer(input_tensor)
[ "def", "_normalized_input_tensor", "(", "self", ",", "input_tensor", ")", ":", "if", "self", ".", "normalizer", "is", "None", ":", "return", "input_tensor", "if", "self", ".", "is_sparse", ":", "return", "sparse_tensor_py", ".", "SparseTensor", "(", "input_tensor", ".", "indices", ",", "self", ".", "normalizer", "(", "input_tensor", ".", "values", ")", ",", "input_tensor", ".", "dense_shape", ")", "else", ":", "return", "self", ".", "normalizer", "(", "input_tensor", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py#L1725-L1734
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/tabart.py
python
AuiDefaultTabArt.DrawFocusRectangle
(self, dc, page, wnd, draw_text, text_offset, bitmap_offset, drawn_tab_yoff, drawn_tab_height, textx, texty)
Draws the focus rectangle on a tab. :param `dc`: a :class:`DC` device context; :param `page`: the page associated with the tab; :param `wnd`: a :class:`Window` instance object; :param string `draw_text`: the text that has been drawn on the tab; :param integer `text_offset`: the text offset on the tab; :param integer `bitmap_offset`: the bitmap offset on the tab; :param integer `drawn_tab_yoff`: the y offset of the tab text; :param integer `drawn_tab_height`: the height of the tab; :param integer `textx`: the x text extent; :param integer `texty`: the y text extent.
Draws the focus rectangle on a tab.
[ "Draws", "the", "focus", "rectangle", "on", "a", "tab", "." ]
def DrawFocusRectangle(self, dc, page, wnd, draw_text, text_offset, bitmap_offset, drawn_tab_yoff, drawn_tab_height, textx, texty): """ Draws the focus rectangle on a tab. :param `dc`: a :class:`DC` device context; :param `page`: the page associated with the tab; :param `wnd`: a :class:`Window` instance object; :param string `draw_text`: the text that has been drawn on the tab; :param integer `text_offset`: the text offset on the tab; :param integer `bitmap_offset`: the bitmap offset on the tab; :param integer `drawn_tab_yoff`: the y offset of the tab text; :param integer `drawn_tab_height`: the height of the tab; :param integer `textx`: the x text extent; :param integer `texty`: the y text extent. """ if self.GetAGWFlags() & AUI_NB_NO_TAB_FOCUS: return if page.active and wx.Window.FindFocus() == wnd: focusRectText = wx.Rect(text_offset, (drawn_tab_yoff + (drawn_tab_height)/2 - (texty/2)), textx, texty) if page.bitmap.IsOk(): focusRectBitmap = wx.Rect(bitmap_offset, drawn_tab_yoff + (drawn_tab_height/2) - (page.bitmap.GetHeight()/2), page.bitmap.GetWidth(), page.bitmap.GetHeight()) if page.bitmap.IsOk() and draw_text == "": focusRect = wx.Rect(*focusRectBitmap) elif not page.bitmap.IsOk() and draw_text != "": focusRect = wx.Rect(*focusRectText) elif page.bitmap.IsOk() and draw_text != "": focusRect = focusRectText.Union(focusRectBitmap) focusRect.Inflate(2, 2) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(self._focusPen) dc.DrawRoundedRectangleRect(focusRect, 2)
[ "def", "DrawFocusRectangle", "(", "self", ",", "dc", ",", "page", ",", "wnd", ",", "draw_text", ",", "text_offset", ",", "bitmap_offset", ",", "drawn_tab_yoff", ",", "drawn_tab_height", ",", "textx", ",", "texty", ")", ":", "if", "self", ".", "GetAGWFlags", "(", ")", "&", "AUI_NB_NO_TAB_FOCUS", ":", "return", "if", "page", ".", "active", "and", "wx", ".", "Window", ".", "FindFocus", "(", ")", "==", "wnd", ":", "focusRectText", "=", "wx", ".", "Rect", "(", "text_offset", ",", "(", "drawn_tab_yoff", "+", "(", "drawn_tab_height", ")", "/", "2", "-", "(", "texty", "/", "2", ")", ")", ",", "textx", ",", "texty", ")", "if", "page", ".", "bitmap", ".", "IsOk", "(", ")", ":", "focusRectBitmap", "=", "wx", ".", "Rect", "(", "bitmap_offset", ",", "drawn_tab_yoff", "+", "(", "drawn_tab_height", "/", "2", ")", "-", "(", "page", ".", "bitmap", ".", "GetHeight", "(", ")", "/", "2", ")", ",", "page", ".", "bitmap", ".", "GetWidth", "(", ")", ",", "page", ".", "bitmap", ".", "GetHeight", "(", ")", ")", "if", "page", ".", "bitmap", ".", "IsOk", "(", ")", "and", "draw_text", "==", "\"\"", ":", "focusRect", "=", "wx", ".", "Rect", "(", "*", "focusRectBitmap", ")", "elif", "not", "page", ".", "bitmap", ".", "IsOk", "(", ")", "and", "draw_text", "!=", "\"\"", ":", "focusRect", "=", "wx", ".", "Rect", "(", "*", "focusRectText", ")", "elif", "page", ".", "bitmap", ".", "IsOk", "(", ")", "and", "draw_text", "!=", "\"\"", ":", "focusRect", "=", "focusRectText", ".", "Union", "(", "focusRectBitmap", ")", "focusRect", ".", "Inflate", "(", "2", ",", "2", ")", "dc", ".", "SetBrush", "(", "wx", ".", "TRANSPARENT_BRUSH", ")", "dc", ".", "SetPen", "(", "self", ".", "_focusPen", ")", "dc", ".", "DrawRoundedRectangleRect", "(", "focusRect", ",", "2", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/tabart.py#L787-L826
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/dockerfiles/assembler.py
python
upload_in_background
(hub_repository, dock, image, tag)
Upload a docker image (to be used by multiprocessing).
Upload a docker image (to be used by multiprocessing).
[ "Upload", "a", "docker", "image", "(", "to", "be", "used", "by", "multiprocessing", ")", "." ]
def upload_in_background(hub_repository, dock, image, tag): """Upload a docker image (to be used by multiprocessing).""" image.tag(hub_repository, tag=tag) print(dock.images.push(hub_repository, tag=tag))
[ "def", "upload_in_background", "(", "hub_repository", ",", "dock", ",", "image", ",", "tag", ")", ":", "image", ".", "tag", "(", "hub_repository", ",", "tag", "=", "tag", ")", "print", "(", "dock", ".", "images", ".", "push", "(", "hub_repository", ",", "tag", "=", "tag", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/tools/dockerfiles/assembler.py#L432-L435
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/coordinates.py
python
Point.worldCoordinates
(self)
return se3.apply(self._frame.worldCoordinates(),self._localCoordinates)
Returns the coordinates of this point in the world Frame
Returns the coordinates of this point in the world Frame
[ "Returns", "the", "coordinates", "of", "this", "point", "in", "the", "world", "Frame" ]
def worldCoordinates(self): """Returns the coordinates of this point in the world Frame""" if self._frame ==None: return self._localCoordinates[:] return se3.apply(self._frame.worldCoordinates(),self._localCoordinates)
[ "def", "worldCoordinates", "(", "self", ")", ":", "if", "self", ".", "_frame", "==", "None", ":", "return", "self", ".", "_localCoordinates", "[", ":", "]", "return", "se3", ".", "apply", "(", "self", ".", "_frame", ".", "worldCoordinates", "(", ")", ",", "self", ".", "_localCoordinates", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/coordinates.py#L140-L144
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
scripts/cpp_lint.py
python
PrintUsage
(message)
Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message.
Prints a brief usage string and exits, optionally with an error message.
[ "Prints", "a", "brief", "usage", "string", "and", "exits", "optionally", "with", "an", "error", "message", "." ]
def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1)
[ "def", "PrintUsage", "(", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "_USAGE", ")", "if", "message", ":", "sys", ".", "exit", "(", "'\\nFATAL ERROR: '", "+", "message", ")", "else", ":", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L4761-L4771
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/ciconfig/evergreen.py
python
Variant.run_on
(self)
return run_on if run_on is not None else []
The build variant run_on parameter as a list of distro names.
The build variant run_on parameter as a list of distro names.
[ "The", "build", "variant", "run_on", "parameter", "as", "a", "list", "of", "distro", "names", "." ]
def run_on(self): """The build variant run_on parameter as a list of distro names.""" run_on = self.raw.get("run_on") return run_on if run_on is not None else []
[ "def", "run_on", "(", "self", ")", ":", "run_on", "=", "self", ".", "raw", ".", "get", "(", "\"run_on\"", ")", "return", "run_on", "if", "run_on", "is", "not", "None", "else", "[", "]" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/ciconfig/evergreen.py#L138-L141
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/struct_types.py
python
StructTypeInfoBase.get_deserializer_static_method
(self)
Get the public static deserializer method for a struct.
Get the public static deserializer method for a struct.
[ "Get", "the", "public", "static", "deserializer", "method", "for", "a", "struct", "." ]
def get_deserializer_static_method(self): # type: () -> MethodInfo """Get the public static deserializer method for a struct.""" pass
[ "def", "get_deserializer_static_method", "(", "self", ")", ":", "# type: () -> MethodInfo", "pass" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/struct_types.py#L181-L184
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/boxing.py
python
box_enum
(typ, val, c)
return c.pyapi.call_function_objargs(cls_obj, (valobj,))
Fetch an enum member given its native value.
Fetch an enum member given its native value.
[ "Fetch", "an", "enum", "member", "given", "its", "native", "value", "." ]
def box_enum(typ, val, c): """ Fetch an enum member given its native value. """ valobj = c.box(typ.dtype, val) # Call the enum class with the value object cls_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.instance_class)) return c.pyapi.call_function_objargs(cls_obj, (valobj,))
[ "def", "box_enum", "(", "typ", ",", "val", ",", "c", ")", ":", "valobj", "=", "c", ".", "box", "(", "typ", ".", "dtype", ",", "val", ")", "# Call the enum class with the value object", "cls_obj", "=", "c", ".", "pyapi", ".", "unserialize", "(", "c", ".", "pyapi", ".", "serialize_object", "(", "typ", ".", "instance_class", ")", ")", "return", "c", ".", "pyapi", ".", "call_function_objargs", "(", "cls_obj", ",", "(", "valobj", ",", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/targets/boxing.py#L162-L169
tensorflow/io
92b44e180674a8af0e12e405530f7343e3e693e4
tensorflow_io/python/ops/image_ops.py
python
encode_gif
(image, name=None)
return core_ops.io_encode_gif(image, name=name)
Encode a uint8 tensor to gif image. Args: image: A Tensor. 3-D uint8 with shape [N, H, W, C]. name: A name for the operation (optional). Returns: A `Tensor` of type `string`.
Encode a uint8 tensor to gif image.
[ "Encode", "a", "uint8", "tensor", "to", "gif", "image", "." ]
def encode_gif(image, name=None): """ Encode a uint8 tensor to gif image. Args: image: A Tensor. 3-D uint8 with shape [N, H, W, C]. name: A name for the operation (optional). Returns: A `Tensor` of type `string`. """ return core_ops.io_encode_gif(image, name=name)
[ "def", "encode_gif", "(", "image", ",", "name", "=", "None", ")", ":", "return", "core_ops", ".", "io_encode_gif", "(", "image", ",", "name", "=", "name", ")" ]
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/ops/image_ops.py#L48-L59
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/jinja2/compiler.py
python
Frame.soft
(self)
return rv
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. This is only used to implement if-statements.
Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer.
[ "Return", "a", "soft", "frame", ".", "A", "soft", "frame", "may", "not", "be", "modified", "as", "standalone", "thing", "as", "it", "shares", "the", "resources", "with", "the", "frame", "it", "was", "created", "of", "but", "it", "s", "not", "a", "rootlevel", "frame", "any", "longer", "." ]
def soft(self): """Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. This is only used to implement if-statements. """ rv = self.copy() rv.rootlevel = False return rv
[ "def", "soft", "(", "self", ")", ":", "rv", "=", "self", ".", "copy", "(", ")", "rv", ".", "rootlevel", "=", "False", "return", "rv" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/jinja2/compiler.py#L178-L187
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/EasyDialogs.py
python
AskFolder
( message=None, # From here on the order is not documented version=None, defaultLocation=None, dialogOptionFlags=None, location=None, clientName=None, windowTitle=None, actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, eventProc=_dummy_Nav_eventproc, filterProc=None, wanted=None, multiple=None)
Display a dialog asking the user for select a folder. wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) the other arguments can be looked up in Apple's Navigation Services documentation
Display a dialog asking the user for select a folder.
[ "Display", "a", "dialog", "asking", "the", "user", "for", "select", "a", "folder", "." ]
def AskFolder( message=None, # From here on the order is not documented version=None, defaultLocation=None, dialogOptionFlags=None, location=None, clientName=None, windowTitle=None, actionButtonLabel=None, cancelButtonLabel=None, preferenceKey=None, popupExtension=None, eventProc=_dummy_Nav_eventproc, filterProc=None, wanted=None, multiple=None): """Display a dialog asking the user for select a folder. wanted is the return type wanted: FSSpec, FSRef, unicode or string (default) the other arguments can be looked up in Apple's Navigation Services documentation""" default_flags = 0x17 args, tpwanted = _process_Nav_args(default_flags, version=version, defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags, location=location,clientName=clientName,windowTitle=windowTitle, actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel, message=message,preferenceKey=preferenceKey, popupExtension=popupExtension,eventProc=eventProc,filterProc=filterProc, wanted=wanted,multiple=multiple) _interact() try: rr = Nav.NavChooseFolder(args) good = 1 except Nav.error, arg: if arg[0] != -128: # userCancelledErr raise Nav.error, arg return None if not rr.validRecord or not rr.selection: return None if issubclass(tpwanted, Carbon.File.FSRef): return tpwanted(rr.selection_fsr[0]) if issubclass(tpwanted, Carbon.File.FSSpec): return tpwanted(rr.selection[0]) if issubclass(tpwanted, str): return tpwanted(rr.selection_fsr[0].as_pathname()) if issubclass(tpwanted, unicode): return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8') raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
[ "def", "AskFolder", "(", "message", "=", "None", ",", "# From here on the order is not documented", "version", "=", "None", ",", "defaultLocation", "=", "None", ",", "dialogOptionFlags", "=", "None", ",", "location", "=", "None", ",", "clientName", "=", "None", ",", "windowTitle", "=", "None", ",", "actionButtonLabel", "=", "None", ",", "cancelButtonLabel", "=", "None", ",", "preferenceKey", "=", "None", ",", "popupExtension", "=", "None", ",", "eventProc", "=", "_dummy_Nav_eventproc", ",", "filterProc", "=", "None", ",", "wanted", "=", "None", ",", "multiple", "=", "None", ")", ":", "default_flags", "=", "0x17", "args", ",", "tpwanted", "=", "_process_Nav_args", "(", "default_flags", ",", "version", "=", "version", ",", "defaultLocation", "=", "defaultLocation", ",", "dialogOptionFlags", "=", "dialogOptionFlags", ",", "location", "=", "location", ",", "clientName", "=", "clientName", ",", "windowTitle", "=", "windowTitle", ",", "actionButtonLabel", "=", "actionButtonLabel", ",", "cancelButtonLabel", "=", "cancelButtonLabel", ",", "message", "=", "message", ",", "preferenceKey", "=", "preferenceKey", ",", "popupExtension", "=", "popupExtension", ",", "eventProc", "=", "eventProc", ",", "filterProc", "=", "filterProc", ",", "wanted", "=", "wanted", ",", "multiple", "=", "multiple", ")", "_interact", "(", ")", "try", ":", "rr", "=", "Nav", ".", "NavChooseFolder", "(", "args", ")", "good", "=", "1", "except", "Nav", ".", "error", ",", "arg", ":", "if", "arg", "[", "0", "]", "!=", "-", "128", ":", "# userCancelledErr", "raise", "Nav", ".", "error", ",", "arg", "return", "None", "if", "not", "rr", ".", "validRecord", "or", "not", "rr", ".", "selection", ":", "return", "None", "if", "issubclass", "(", "tpwanted", ",", "Carbon", ".", "File", ".", "FSRef", ")", ":", "return", "tpwanted", "(", "rr", ".", "selection_fsr", "[", "0", "]", ")", "if", "issubclass", "(", "tpwanted", ",", "Carbon", ".", "File", ".", "FSSpec", ")", ":", "return", "tpwanted", "(", "rr", ".", "selection", "[", "0", "]", ")", "if", "issubclass", "(", "tpwanted", ",", "str", ")", ":", "return", "tpwanted", "(", "rr", ".", "selection_fsr", "[", "0", "]", ".", "as_pathname", "(", ")", ")", "if", "issubclass", "(", "tpwanted", ",", "unicode", ")", ":", "return", "tpwanted", "(", "rr", ".", "selection_fsr", "[", "0", "]", ".", "as_pathname", "(", ")", ",", "'utf8'", ")", "raise", "TypeError", ",", "\"Unknown value for argument 'wanted': %s\"", "%", "repr", "(", "tpwanted", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/EasyDialogs.py#L736-L784
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/decoder.py
python
dynamic_decode
(decoder, output_time_major=False, impute_finished=False, maximum_iterations=None, parallel_iterations=32, swap_memory=False, scope=None, **kwargs)
return final_outputs, final_state, final_sequence_lengths
Perform dynamic decoding with `decoder`. Calls initialize() once and step() repeatedly on the Decoder object. Args: decoder: A `Decoder` instance. output_time_major: Python boolean. Default: `False` (batch major). If `True`, outputs are returned as time major tensors (this mode is faster). Otherwise, outputs are returned as batch major tensors (this adds extra time to the computation). impute_finished: Python boolean. If `True`, then states for batch entries which are marked as finished get copied through and the corresponding outputs get zeroed out. This causes some slowdown at each time step, but ensures that the final state and outputs have the correct values and that backprop ignores time steps that were marked as finished. maximum_iterations: `int32` scalar, maximum allowed number of decoding steps. Default is `None` (decode until the decoder is fully done). parallel_iterations: Argument passed to `tf.while_loop`. swap_memory: Argument passed to `tf.while_loop`. scope: Optional variable scope to use. **kwargs: dict, other keyword arguments for dynamic_decode. It might contain arguments for `BaseDecoder` to initialize, which takes all tensor inputs during call(). Returns: `(final_outputs, final_state, final_sequence_lengths)`. Raises: TypeError: if `decoder` is not an instance of `Decoder`. ValueError: if `maximum_iterations` is provided but is not a scalar.
Perform dynamic decoding with `decoder`.
[ "Perform", "dynamic", "decoding", "with", "decoder", "." ]
def dynamic_decode(decoder, output_time_major=False, impute_finished=False, maximum_iterations=None, parallel_iterations=32, swap_memory=False, scope=None, **kwargs): """Perform dynamic decoding with `decoder`. Calls initialize() once and step() repeatedly on the Decoder object. Args: decoder: A `Decoder` instance. output_time_major: Python boolean. Default: `False` (batch major). If `True`, outputs are returned as time major tensors (this mode is faster). Otherwise, outputs are returned as batch major tensors (this adds extra time to the computation). impute_finished: Python boolean. If `True`, then states for batch entries which are marked as finished get copied through and the corresponding outputs get zeroed out. This causes some slowdown at each time step, but ensures that the final state and outputs have the correct values and that backprop ignores time steps that were marked as finished. maximum_iterations: `int32` scalar, maximum allowed number of decoding steps. Default is `None` (decode until the decoder is fully done). parallel_iterations: Argument passed to `tf.while_loop`. swap_memory: Argument passed to `tf.while_loop`. scope: Optional variable scope to use. **kwargs: dict, other keyword arguments for dynamic_decode. It might contain arguments for `BaseDecoder` to initialize, which takes all tensor inputs during call(). Returns: `(final_outputs, final_state, final_sequence_lengths)`. Raises: TypeError: if `decoder` is not an instance of `Decoder`. ValueError: if `maximum_iterations` is provided but is not a scalar. """ if not isinstance(decoder, (Decoder, BaseDecoder)): raise TypeError("Expected decoder to be type Decoder, but saw: %s" % type(decoder)) with variable_scope.variable_scope(scope, "decoder") as varscope: # Determine context types. ctxt = ops.get_default_graph()._get_control_flow_context() # pylint: disable=protected-access is_xla = control_flow_util.GetContainingXLAContext(ctxt) is not None in_while_loop = ( control_flow_util.GetContainingWhileContext(ctxt) is not None) # Properly cache variable values inside the while_loop. # Don't set a caching device when running in a loop, since it is possible # that train steps could be wrapped in a tf.while_loop. In that scenario # caching prevents forward computations in loop iterations from re-reading # the updated weights. if not context.executing_eagerly() and not in_while_loop: if varscope.caching_device is None: varscope.set_caching_device(lambda op: op.device) if maximum_iterations is not None: maximum_iterations = ops.convert_to_tensor( maximum_iterations, dtype=dtypes.int32, name="maximum_iterations") if maximum_iterations.get_shape().ndims != 0: raise ValueError("maximum_iterations must be a scalar") if isinstance(decoder, Decoder): initial_finished, initial_inputs, initial_state = decoder.initialize() else: # For BaseDecoder that takes tensor inputs during call. decoder_init_input = kwargs.pop("decoder_init_input", None) decoder_init_kwargs = kwargs.pop("decoder_init_kwargs", {}) initial_finished, initial_inputs, initial_state = decoder.initialize( decoder_init_input, **decoder_init_kwargs) zero_outputs = _create_zero_outputs(decoder.output_size, decoder.output_dtype, decoder.batch_size) if is_xla and maximum_iterations is None: raise ValueError("maximum_iterations is required for XLA compilation.") if maximum_iterations is not None: initial_finished = math_ops.logical_or( initial_finished, 0 >= maximum_iterations) initial_sequence_lengths = array_ops.zeros_like( initial_finished, dtype=dtypes.int32) initial_time = constant_op.constant(0, dtype=dtypes.int32) def _shape(batch_size, from_shape): if (not isinstance(from_shape, tensor_shape.TensorShape) or from_shape.ndims == 0): return None else: batch_size = tensor_util.constant_value( ops.convert_to_tensor( batch_size, name="batch_size")) return tensor_shape.TensorShape([batch_size]).concatenate(from_shape) dynamic_size = maximum_iterations is None or not is_xla def _create_ta(s, d): return tensor_array_ops.TensorArray( dtype=d, size=0 if dynamic_size else maximum_iterations, dynamic_size=dynamic_size, element_shape=_shape(decoder.batch_size, s)) initial_outputs_ta = nest.map_structure(_create_ta, decoder.output_size, decoder.output_dtype) def condition(unused_time, unused_outputs_ta, unused_state, unused_inputs, finished, unused_sequence_lengths): return math_ops.logical_not(math_ops.reduce_all(finished)) def body(time, outputs_ta, state, inputs, finished, sequence_lengths): """Internal while_loop body. Args: time: scalar int32 tensor. outputs_ta: structure of TensorArray. state: (structure of) state tensors and TensorArrays. inputs: (structure of) input tensors. finished: bool tensor (keeping track of what's finished). sequence_lengths: int32 tensor (keeping track of time of finish). Returns: `(time + 1, outputs_ta, next_state, next_inputs, next_finished, next_sequence_lengths)`. ``` """ (next_outputs, decoder_state, next_inputs, decoder_finished) = decoder.step(time, inputs, state) if decoder.tracks_own_finished: next_finished = decoder_finished else: next_finished = math_ops.logical_or(decoder_finished, finished) next_sequence_lengths = array_ops.where( math_ops.logical_not(finished), array_ops.fill(array_ops.shape(sequence_lengths), time + 1), sequence_lengths) nest.assert_same_structure(state, decoder_state) nest.assert_same_structure(outputs_ta, next_outputs) nest.assert_same_structure(inputs, next_inputs) # Zero out output values past finish if impute_finished: emit = nest.map_structure( lambda out, zero: array_ops.where(finished, zero, out), next_outputs, zero_outputs) else: emit = next_outputs # Copy through states past finish def _maybe_copy_state(new, cur): # TensorArrays and scalar states get passed through. if isinstance(cur, tensor_array_ops.TensorArray): pass_through = True else: new.set_shape(cur.shape) pass_through = (new.shape.ndims == 0) return new if pass_through else array_ops.where(finished, cur, new) if impute_finished: next_state = nest.map_structure( _maybe_copy_state, decoder_state, state) else: next_state = decoder_state outputs_ta = nest.map_structure(lambda ta, out: ta.write(time, out), outputs_ta, emit) return (time + 1, outputs_ta, next_state, next_inputs, next_finished, next_sequence_lengths) res = control_flow_ops.while_loop( condition, body, loop_vars=( initial_time, initial_outputs_ta, initial_state, initial_inputs, initial_finished, initial_sequence_lengths, ), parallel_iterations=parallel_iterations, maximum_iterations=maximum_iterations, swap_memory=swap_memory) final_outputs_ta = res[1] final_state = res[2] final_sequence_lengths = res[5] final_outputs = nest.map_structure(lambda ta: ta.stack(), final_outputs_ta) try: final_outputs, final_state = decoder.finalize( final_outputs, final_state, final_sequence_lengths) except NotImplementedError: pass if not output_time_major: final_outputs = nest.map_structure(_transpose_batch_time, final_outputs) return final_outputs, final_state, final_sequence_lengths
[ "def", "dynamic_decode", "(", "decoder", ",", "output_time_major", "=", "False", ",", "impute_finished", "=", "False", ",", "maximum_iterations", "=", "None", ",", "parallel_iterations", "=", "32", ",", "swap_memory", "=", "False", ",", "scope", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "decoder", ",", "(", "Decoder", ",", "BaseDecoder", ")", ")", ":", "raise", "TypeError", "(", "\"Expected decoder to be type Decoder, but saw: %s\"", "%", "type", "(", "decoder", ")", ")", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "\"decoder\"", ")", "as", "varscope", ":", "# Determine context types.", "ctxt", "=", "ops", ".", "get_default_graph", "(", ")", ".", "_get_control_flow_context", "(", ")", "# pylint: disable=protected-access", "is_xla", "=", "control_flow_util", ".", "GetContainingXLAContext", "(", "ctxt", ")", "is", "not", "None", "in_while_loop", "=", "(", "control_flow_util", ".", "GetContainingWhileContext", "(", "ctxt", ")", "is", "not", "None", ")", "# Properly cache variable values inside the while_loop.", "# Don't set a caching device when running in a loop, since it is possible", "# that train steps could be wrapped in a tf.while_loop. In that scenario", "# caching prevents forward computations in loop iterations from re-reading", "# the updated weights.", "if", "not", "context", ".", "executing_eagerly", "(", ")", "and", "not", "in_while_loop", ":", "if", "varscope", ".", "caching_device", "is", "None", ":", "varscope", ".", "set_caching_device", "(", "lambda", "op", ":", "op", ".", "device", ")", "if", "maximum_iterations", "is", "not", "None", ":", "maximum_iterations", "=", "ops", ".", "convert_to_tensor", "(", "maximum_iterations", ",", "dtype", "=", "dtypes", ".", "int32", ",", "name", "=", "\"maximum_iterations\"", ")", "if", "maximum_iterations", ".", "get_shape", "(", ")", ".", "ndims", "!=", "0", ":", "raise", "ValueError", "(", "\"maximum_iterations must be a scalar\"", ")", "if", "isinstance", "(", "decoder", ",", "Decoder", ")", ":", "initial_finished", ",", "initial_inputs", ",", "initial_state", "=", "decoder", ".", "initialize", "(", ")", "else", ":", "# For BaseDecoder that takes tensor inputs during call.", "decoder_init_input", "=", "kwargs", ".", "pop", "(", "\"decoder_init_input\"", ",", "None", ")", "decoder_init_kwargs", "=", "kwargs", ".", "pop", "(", "\"decoder_init_kwargs\"", ",", "{", "}", ")", "initial_finished", ",", "initial_inputs", ",", "initial_state", "=", "decoder", ".", "initialize", "(", "decoder_init_input", ",", "*", "*", "decoder_init_kwargs", ")", "zero_outputs", "=", "_create_zero_outputs", "(", "decoder", ".", "output_size", ",", "decoder", ".", "output_dtype", ",", "decoder", ".", "batch_size", ")", "if", "is_xla", "and", "maximum_iterations", "is", "None", ":", "raise", "ValueError", "(", "\"maximum_iterations is required for XLA compilation.\"", ")", "if", "maximum_iterations", "is", "not", "None", ":", "initial_finished", "=", "math_ops", ".", "logical_or", "(", "initial_finished", ",", "0", ">=", "maximum_iterations", ")", "initial_sequence_lengths", "=", "array_ops", ".", "zeros_like", "(", "initial_finished", ",", "dtype", "=", "dtypes", ".", "int32", ")", "initial_time", "=", "constant_op", ".", "constant", "(", "0", ",", "dtype", "=", "dtypes", ".", "int32", ")", "def", "_shape", "(", "batch_size", ",", "from_shape", ")", ":", "if", "(", "not", "isinstance", "(", "from_shape", ",", "tensor_shape", ".", "TensorShape", ")", "or", "from_shape", ".", "ndims", "==", "0", ")", ":", "return", "None", "else", ":", "batch_size", "=", "tensor_util", ".", "constant_value", "(", "ops", ".", "convert_to_tensor", "(", "batch_size", ",", "name", "=", "\"batch_size\"", ")", ")", "return", "tensor_shape", ".", "TensorShape", "(", "[", "batch_size", "]", ")", ".", "concatenate", "(", "from_shape", ")", "dynamic_size", "=", "maximum_iterations", "is", "None", "or", "not", "is_xla", "def", "_create_ta", "(", "s", ",", "d", ")", ":", "return", "tensor_array_ops", ".", "TensorArray", "(", "dtype", "=", "d", ",", "size", "=", "0", "if", "dynamic_size", "else", "maximum_iterations", ",", "dynamic_size", "=", "dynamic_size", ",", "element_shape", "=", "_shape", "(", "decoder", ".", "batch_size", ",", "s", ")", ")", "initial_outputs_ta", "=", "nest", ".", "map_structure", "(", "_create_ta", ",", "decoder", ".", "output_size", ",", "decoder", ".", "output_dtype", ")", "def", "condition", "(", "unused_time", ",", "unused_outputs_ta", ",", "unused_state", ",", "unused_inputs", ",", "finished", ",", "unused_sequence_lengths", ")", ":", "return", "math_ops", ".", "logical_not", "(", "math_ops", ".", "reduce_all", "(", "finished", ")", ")", "def", "body", "(", "time", ",", "outputs_ta", ",", "state", ",", "inputs", ",", "finished", ",", "sequence_lengths", ")", ":", "\"\"\"Internal while_loop body.\n\n Args:\n time: scalar int32 tensor.\n outputs_ta: structure of TensorArray.\n state: (structure of) state tensors and TensorArrays.\n inputs: (structure of) input tensors.\n finished: bool tensor (keeping track of what's finished).\n sequence_lengths: int32 tensor (keeping track of time of finish).\n\n Returns:\n `(time + 1, outputs_ta, next_state, next_inputs, next_finished,\n next_sequence_lengths)`.\n ```\n \"\"\"", "(", "next_outputs", ",", "decoder_state", ",", "next_inputs", ",", "decoder_finished", ")", "=", "decoder", ".", "step", "(", "time", ",", "inputs", ",", "state", ")", "if", "decoder", ".", "tracks_own_finished", ":", "next_finished", "=", "decoder_finished", "else", ":", "next_finished", "=", "math_ops", ".", "logical_or", "(", "decoder_finished", ",", "finished", ")", "next_sequence_lengths", "=", "array_ops", ".", "where", "(", "math_ops", ".", "logical_not", "(", "finished", ")", ",", "array_ops", ".", "fill", "(", "array_ops", ".", "shape", "(", "sequence_lengths", ")", ",", "time", "+", "1", ")", ",", "sequence_lengths", ")", "nest", ".", "assert_same_structure", "(", "state", ",", "decoder_state", ")", "nest", ".", "assert_same_structure", "(", "outputs_ta", ",", "next_outputs", ")", "nest", ".", "assert_same_structure", "(", "inputs", ",", "next_inputs", ")", "# Zero out output values past finish", "if", "impute_finished", ":", "emit", "=", "nest", ".", "map_structure", "(", "lambda", "out", ",", "zero", ":", "array_ops", ".", "where", "(", "finished", ",", "zero", ",", "out", ")", ",", "next_outputs", ",", "zero_outputs", ")", "else", ":", "emit", "=", "next_outputs", "# Copy through states past finish", "def", "_maybe_copy_state", "(", "new", ",", "cur", ")", ":", "# TensorArrays and scalar states get passed through.", "if", "isinstance", "(", "cur", ",", "tensor_array_ops", ".", "TensorArray", ")", ":", "pass_through", "=", "True", "else", ":", "new", ".", "set_shape", "(", "cur", ".", "shape", ")", "pass_through", "=", "(", "new", ".", "shape", ".", "ndims", "==", "0", ")", "return", "new", "if", "pass_through", "else", "array_ops", ".", "where", "(", "finished", ",", "cur", ",", "new", ")", "if", "impute_finished", ":", "next_state", "=", "nest", ".", "map_structure", "(", "_maybe_copy_state", ",", "decoder_state", ",", "state", ")", "else", ":", "next_state", "=", "decoder_state", "outputs_ta", "=", "nest", ".", "map_structure", "(", "lambda", "ta", ",", "out", ":", "ta", ".", "write", "(", "time", ",", "out", ")", ",", "outputs_ta", ",", "emit", ")", "return", "(", "time", "+", "1", ",", "outputs_ta", ",", "next_state", ",", "next_inputs", ",", "next_finished", ",", "next_sequence_lengths", ")", "res", "=", "control_flow_ops", ".", "while_loop", "(", "condition", ",", "body", ",", "loop_vars", "=", "(", "initial_time", ",", "initial_outputs_ta", ",", "initial_state", ",", "initial_inputs", ",", "initial_finished", ",", "initial_sequence_lengths", ",", ")", ",", "parallel_iterations", "=", "parallel_iterations", ",", "maximum_iterations", "=", "maximum_iterations", ",", "swap_memory", "=", "swap_memory", ")", "final_outputs_ta", "=", "res", "[", "1", "]", "final_state", "=", "res", "[", "2", "]", "final_sequence_lengths", "=", "res", "[", "5", "]", "final_outputs", "=", "nest", ".", "map_structure", "(", "lambda", "ta", ":", "ta", ".", "stack", "(", ")", ",", "final_outputs_ta", ")", "try", ":", "final_outputs", ",", "final_state", "=", "decoder", ".", "finalize", "(", "final_outputs", ",", "final_state", ",", "final_sequence_lengths", ")", "except", "NotImplementedError", ":", "pass", "if", "not", "output_time_major", ":", "final_outputs", "=", "nest", ".", "map_structure", "(", "_transpose_batch_time", ",", "final_outputs", ")", "return", "final_outputs", ",", "final_state", ",", "final_sequence_lengths" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/seq2seq/python/ops/decoder.py#L282-L486
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBDebugger.Clear
(self)
return _lldb.SBDebugger_Clear(self)
Clear(self)
Clear(self)
[ "Clear", "(", "self", ")" ]
def Clear(self): """Clear(self)""" return _lldb.SBDebugger_Clear(self)
[ "def", "Clear", "(", "self", ")", ":", "return", "_lldb", ".", "SBDebugger_Clear", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L3214-L3216
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/util.py
python
rfc822_escape
(header)
return sep.join(lines)
Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline.
Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline.
[ "Return", "a", "version", "of", "the", "string", "escaped", "for", "inclusion", "in", "an", "RFC", "-", "822", "header", "by", "ensuring", "there", "are", "8", "spaces", "space", "after", "each", "newline", "." ]
def rfc822_escape (header): """Return a version of the string escaped for inclusion in an RFC-822 header, by ensuring there are 8 spaces space after each newline. """ lines = header.split('\n') sep = '\n' + 8 * ' ' return sep.join(lines)
[ "def", "rfc822_escape", "(", "header", ")", ":", "lines", "=", "header", ".", "split", "(", "'\\n'", ")", "sep", "=", "'\\n'", "+", "8", "*", "' '", "return", "sep", ".", "join", "(", "lines", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/util.py#L542-L548
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py
python
MultiIndex.equals
(self, other)
return True
Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) See Also -------- equal_levels
Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same)
[ "Determines", "if", "two", "MultiIndex", "objects", "have", "the", "same", "labeling", "information", "(", "the", "levels", "themselves", "do", "not", "necessarily", "have", "to", "be", "the", "same", ")" ]
def equals(self, other) -> bool: """ Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) See Also -------- equal_levels """ if self.is_(other): return True if not isinstance(other, Index): return False if not isinstance(other, MultiIndex): # d-level MultiIndex can equal d-tuple Index if not is_object_dtype(other.dtype): if self.nlevels != other.nlevels: return False other_vals = com.values_from_object(ensure_index(other)) return array_equivalent(self._ndarray_values, other_vals) if self.nlevels != other.nlevels: return False if len(self) != len(other): return False for i in range(self.nlevels): self_codes = self.codes[i] self_codes = self_codes[self_codes != -1] self_values = algos.take_nd( np.asarray(self.levels[i]._values), self_codes, allow_fill=False ) other_codes = other.codes[i] other_codes = other_codes[other_codes != -1] other_values = algos.take_nd( np.asarray(other.levels[i]._values), other_codes, allow_fill=False ) # since we use NaT both datetime64 and timedelta64 # we can have a situation where a level is typed say # timedelta64 in self (IOW it has other values than NaT) # but types datetime64 in other (where its all NaT) # but these are equivalent if len(self_values) == 0 and len(other_values) == 0: continue if not array_equivalent(self_values, other_values): return False return True
[ "def", "equals", "(", "self", ",", "other", ")", "->", "bool", ":", "if", "self", ".", "is_", "(", "other", ")", ":", "return", "True", "if", "not", "isinstance", "(", "other", ",", "Index", ")", ":", "return", "False", "if", "not", "isinstance", "(", "other", ",", "MultiIndex", ")", ":", "# d-level MultiIndex can equal d-tuple Index", "if", "not", "is_object_dtype", "(", "other", ".", "dtype", ")", ":", "if", "self", ".", "nlevels", "!=", "other", ".", "nlevels", ":", "return", "False", "other_vals", "=", "com", ".", "values_from_object", "(", "ensure_index", "(", "other", ")", ")", "return", "array_equivalent", "(", "self", ".", "_ndarray_values", ",", "other_vals", ")", "if", "self", ".", "nlevels", "!=", "other", ".", "nlevels", ":", "return", "False", "if", "len", "(", "self", ")", "!=", "len", "(", "other", ")", ":", "return", "False", "for", "i", "in", "range", "(", "self", ".", "nlevels", ")", ":", "self_codes", "=", "self", ".", "codes", "[", "i", "]", "self_codes", "=", "self_codes", "[", "self_codes", "!=", "-", "1", "]", "self_values", "=", "algos", ".", "take_nd", "(", "np", ".", "asarray", "(", "self", ".", "levels", "[", "i", "]", ".", "_values", ")", ",", "self_codes", ",", "allow_fill", "=", "False", ")", "other_codes", "=", "other", ".", "codes", "[", "i", "]", "other_codes", "=", "other_codes", "[", "other_codes", "!=", "-", "1", "]", "other_values", "=", "algos", ".", "take_nd", "(", "np", ".", "asarray", "(", "other", ".", "levels", "[", "i", "]", ".", "_values", ")", ",", "other_codes", ",", "allow_fill", "=", "False", ")", "# since we use NaT both datetime64 and timedelta64", "# we can have a situation where a level is typed say", "# timedelta64 in self (IOW it has other values than NaT)", "# but types datetime64 in other (where its all NaT)", "# but these are equivalent", "if", "len", "(", "self_values", ")", "==", "0", "and", "len", "(", "other_values", ")", "==", "0", ":", "continue", "if", "not", "array_equivalent", "(", "self_values", ",", "other_values", ")", ":", "return", "False", "return", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py#L3101-L3155
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/msvs.py
python
_generateGUID
(slnfile, name, namespace=external_makefile_guid)
return '{' + str(solution).upper() + '}'
Generates a GUID for the sln file to use. The uuid5 function is used to combine an existing namespace uuid - the one VS uses for C projects (external_makedile_guid) - and a combination of the solution file name (slnfile) and the project name (name). We just need uniqueness/repeatability. Returns (str) "displayable" GUID, already wrapped in braces
Generates a GUID for the sln file to use.
[ "Generates", "a", "GUID", "for", "the", "sln", "file", "to", "use", "." ]
def _generateGUID(slnfile, name, namespace=external_makefile_guid): """Generates a GUID for the sln file to use. The uuid5 function is used to combine an existing namespace uuid - the one VS uses for C projects (external_makedile_guid) - and a combination of the solution file name (slnfile) and the project name (name). We just need uniqueness/repeatability. Returns (str) "displayable" GUID, already wrapped in braces """ # Normalize the slnfile path to a Windows path (\ separators) so # the generated file has a consistent GUID even if we generate # it on a non-Windows platform. slnfile = ntpath.normpath(str(slnfile)) solution = uuid.uuid5(uuid.UUID(namespace), "%s-%s" %(slnfile, name)) return '{' + str(solution).upper() + '}'
[ "def", "_generateGUID", "(", "slnfile", ",", "name", ",", "namespace", "=", "external_makefile_guid", ")", ":", "# Normalize the slnfile path to a Windows path (\\ separators) so", "# the generated file has a consistent GUID even if we generate", "# it on a non-Windows platform.", "slnfile", "=", "ntpath", ".", "normpath", "(", "str", "(", "slnfile", ")", ")", "solution", "=", "uuid", ".", "uuid5", "(", "uuid", ".", "UUID", "(", "namespace", ")", ",", "\"%s-%s\"", "%", "(", "slnfile", ",", "name", ")", ")", "return", "'{'", "+", "str", "(", "solution", ")", ".", "upper", "(", ")", "+", "'}'" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/msvs.py#L109-L125
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/baselines/enjoy_kuka_diverse_object_grasping.py
python
ContinuousDownwardBiasPolicy.sample_action
(self, obs, explore_prob)
return [dx, dy, dz, da, 0]
Implements height hack and grasping threshold hack.
Implements height hack and grasping threshold hack.
[ "Implements", "height", "hack", "and", "grasping", "threshold", "hack", "." ]
def sample_action(self, obs, explore_prob): """Implements height hack and grasping threshold hack. """ dx, dy, dz, da, close = self._action_space.sample() if np.random.random() < self._height_hack_prob: dz = -1 return [dx, dy, dz, da, 0]
[ "def", "sample_action", "(", "self", ",", "obs", ",", "explore_prob", ")", ":", "dx", ",", "dy", ",", "dz", ",", "da", ",", "close", "=", "self", ".", "_action_space", ".", "sample", "(", ")", "if", "np", ".", "random", ".", "random", "(", ")", "<", "self", ".", "_height_hack_prob", ":", "dz", "=", "-", "1", "return", "[", "dx", ",", "dy", ",", "dz", ",", "da", ",", "0", "]" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/baselines/enjoy_kuka_diverse_object_grasping.py#L29-L35
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/signaltools.py
python
convolve2d
(in1, in2, mode='full', boundary='fill', fillvalue=0)
return out
Convolve two 2-dimensional arrays. Convolve `in1` and `in2` with output size determined by `mode`, and boundary conditions determined by `boundary` and `fillvalue`. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear convolution of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. In 'valid' mode, either `in1` or `in2` must be at least as large as the other in every dimension. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. boundary : str {'fill', 'wrap', 'symm'}, optional A flag indicating how to handle boundaries: ``fill`` pad input arrays with fillvalue. (default) ``wrap`` circular boundary conditions. ``symm`` symmetrical boundary conditions. fillvalue : scalar, optional Value to fill pad input arrays with. Default is 0. Returns ------- out : ndarray A 2-dimensional array containing a subset of the discrete linear convolution of `in1` with `in2`. Examples -------- Compute the gradient of an image by 2D convolution with a complex Scharr operator. (Horizontal operator is real, vertical is imaginary.) Use symmetric boundary condition to avoid creating edges at the image boundaries. >>> from scipy import signal >>> from scipy import misc >>> ascent = misc.ascent() >>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j], ... [-10+0j, 0+ 0j, +10 +0j], ... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy >>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same') >>> import matplotlib.pyplot as plt >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15)) >>> ax_orig.imshow(ascent, cmap='gray') >>> ax_orig.set_title('Original') >>> ax_orig.set_axis_off() >>> ax_mag.imshow(np.absolute(grad), cmap='gray') >>> ax_mag.set_title('Gradient magnitude') >>> ax_mag.set_axis_off() >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles >>> ax_ang.set_title('Gradient orientation') >>> ax_ang.set_axis_off() >>> fig.show()
Convolve two 2-dimensional arrays.
[ "Convolve", "two", "2", "-", "dimensional", "arrays", "." ]
def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0): """ Convolve two 2-dimensional arrays. Convolve `in1` and `in2` with output size determined by `mode`, and boundary conditions determined by `boundary` and `fillvalue`. Parameters ---------- in1 : array_like First input. in2 : array_like Second input. Should have the same number of dimensions as `in1`. mode : str {'full', 'valid', 'same'}, optional A string indicating the size of the output: ``full`` The output is the full discrete linear convolution of the inputs. (Default) ``valid`` The output consists only of those elements that do not rely on the zero-padding. In 'valid' mode, either `in1` or `in2` must be at least as large as the other in every dimension. ``same`` The output is the same size as `in1`, centered with respect to the 'full' output. boundary : str {'fill', 'wrap', 'symm'}, optional A flag indicating how to handle boundaries: ``fill`` pad input arrays with fillvalue. (default) ``wrap`` circular boundary conditions. ``symm`` symmetrical boundary conditions. fillvalue : scalar, optional Value to fill pad input arrays with. Default is 0. Returns ------- out : ndarray A 2-dimensional array containing a subset of the discrete linear convolution of `in1` with `in2`. Examples -------- Compute the gradient of an image by 2D convolution with a complex Scharr operator. (Horizontal operator is real, vertical is imaginary.) Use symmetric boundary condition to avoid creating edges at the image boundaries. >>> from scipy import signal >>> from scipy import misc >>> ascent = misc.ascent() >>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j], ... [-10+0j, 0+ 0j, +10 +0j], ... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy >>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same') >>> import matplotlib.pyplot as plt >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15)) >>> ax_orig.imshow(ascent, cmap='gray') >>> ax_orig.set_title('Original') >>> ax_orig.set_axis_off() >>> ax_mag.imshow(np.absolute(grad), cmap='gray') >>> ax_mag.set_title('Gradient magnitude') >>> ax_mag.set_axis_off() >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles >>> ax_ang.set_title('Gradient orientation') >>> ax_ang.set_axis_off() >>> fig.show() """ in1 = asarray(in1) in2 = asarray(in2) if not in1.ndim == in2.ndim == 2: raise ValueError('convolve2d inputs must both be 2D arrays') if _inputs_swap_needed(mode, in1.shape, in2.shape): in1, in2 = in2, in1 val = _valfrommode(mode) bval = _bvalfromboundary(boundary) out = sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue) return out
[ "def", "convolve2d", "(", "in1", ",", "in2", ",", "mode", "=", "'full'", ",", "boundary", "=", "'fill'", ",", "fillvalue", "=", "0", ")", ":", "in1", "=", "asarray", "(", "in1", ")", "in2", "=", "asarray", "(", "in2", ")", "if", "not", "in1", ".", "ndim", "==", "in2", ".", "ndim", "==", "2", ":", "raise", "ValueError", "(", "'convolve2d inputs must both be 2D arrays'", ")", "if", "_inputs_swap_needed", "(", "mode", ",", "in1", ".", "shape", ",", "in2", ".", "shape", ")", ":", "in1", ",", "in2", "=", "in2", ",", "in1", "val", "=", "_valfrommode", "(", "mode", ")", "bval", "=", "_bvalfromboundary", "(", "boundary", ")", "out", "=", "sigtools", ".", "_convolve2d", "(", "in1", ",", "in2", ",", "1", ",", "val", ",", "bval", ",", "fillvalue", ")", "return", "out" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/signaltools.py#L973-L1059
nlohmann/json
eb2182414749825be086c825edb5229e5c28503d
third_party/cpplint/cpplint.py
python
CheckForHeaderGuard
(filename, clean_lines, error)
Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found.
Checks that the file contains a header guard.
[ "Checks", "that", "the", "file", "contains", "a", "header", "guard", "." ]
def CheckForHeaderGuard(filename, clean_lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found. """ # Don't check for header guards if there are error suppression # comments somewhere in this file. # # Because this is silencing a warning for a nonexistent line, we # only support the very specific NOLINT(build/header_guard) syntax, # and not the general NOLINT or NOLINT(*) syntax. raw_lines = clean_lines.lines_without_raw_strings for i in raw_lines: if Search(r'//\s*NOLINT\(build/header_guard\)', i): return # Allow pragma once instead of header guards for i in raw_lines: if Search(r'^\s*#pragma\s+once', i): return cppvar = GetHeaderGuardCPPVariable(filename) ifndef = '' ifndef_linenum = 0 define = '' endif = '' endif_linenum = 0 for linenum, line in enumerate(raw_lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef or not define or ifndef != define: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) # Check for "//" comments on endif line. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error) match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) if match: if match.group(1) == '_': # Issue low severity warning for deprecated double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif // %s"' % cppvar) return # Didn't find the corresponding "//" comment. If this file does not # contain any "//" comments at all, it could be that the compiler # only wants "/**/" comments, look for those instead. no_single_line_comments = True for i in xrange(1, len(raw_lines) - 1): line = raw_lines[i] if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): no_single_line_comments = False break if no_single_line_comments: match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) if match: if match.group(1) == '_': # Low severity warning for double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif /* %s */"' % cppvar) return # Didn't find anything error(filename, endif_linenum, 'build/header_guard', 5, '#endif line should be "#endif // %s"' % cppvar)
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "clean_lines", ",", "error", ")", ":", "# Don't check for header guards if there are error suppression", "# comments somewhere in this file.", "#", "# Because this is silencing a warning for a nonexistent line, we", "# only support the very specific NOLINT(build/header_guard) syntax,", "# and not the general NOLINT or NOLINT(*) syntax.", "raw_lines", "=", "clean_lines", ".", "lines_without_raw_strings", "for", "i", "in", "raw_lines", ":", "if", "Search", "(", "r'//\\s*NOLINT\\(build/header_guard\\)'", ",", "i", ")", ":", "return", "# Allow pragma once instead of header guards", "for", "i", "in", "raw_lines", ":", "if", "Search", "(", "r'^\\s*#pragma\\s+once'", ",", "i", ")", ":", "return", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "ifndef", "=", "''", "ifndef_linenum", "=", "0", "define", "=", "''", "endif", "=", "''", "endif_linenum", "=", "0", "for", "linenum", ",", "line", "in", "enumerate", "(", "raw_lines", ")", ":", "linesplit", "=", "line", ".", "split", "(", ")", "if", "len", "(", "linesplit", ")", ">=", "2", ":", "# find the first occurrence of #ifndef and #define, save arg", "if", "not", "ifndef", "and", "linesplit", "[", "0", "]", "==", "'#ifndef'", ":", "# set ifndef to the header guard presented on the #ifndef line.", "ifndef", "=", "linesplit", "[", "1", "]", "ifndef_linenum", "=", "linenum", "if", "not", "define", "and", "linesplit", "[", "0", "]", "==", "'#define'", ":", "define", "=", "linesplit", "[", "1", "]", "# find the last occurrence of #endif, save entire line", "if", "line", ".", "startswith", "(", "'#endif'", ")", ":", "endif", "=", "line", "endif_linenum", "=", "linenum", "if", "not", "ifndef", "or", "not", "define", "or", "ifndef", "!=", "define", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #ifndef header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__", "# for backward compatibility.", "if", "ifndef", "!=", "cppvar", ":", "error_level", "=", "0", "if", "ifndef", "!=", "cppvar", "+", "'_'", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "ifndef_linenum", "]", ",", "ifndef_linenum", ",", "error", ")", "error", "(", "filename", ",", "ifndef_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#ifndef header guard has wrong style, please use: %s'", "%", "cppvar", ")", "# Check for \"//\" comments on endif line.", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "endif_linenum", "]", ",", "endif_linenum", ",", "error", ")", "match", "=", "Match", "(", "r'#endif\\s*//\\s*'", "+", "cppvar", "+", "r'(_)?\\b'", ",", "endif", ")", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'_'", ":", "# Issue low severity warning for deprecated double trailing underscore", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "0", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")", "return", "# Didn't find the corresponding \"//\" comment. If this file does not", "# contain any \"//\" comments at all, it could be that the compiler", "# only wants \"/**/\" comments, look for those instead.", "no_single_line_comments", "=", "True", "for", "i", "in", "xrange", "(", "1", ",", "len", "(", "raw_lines", ")", "-", "1", ")", ":", "line", "=", "raw_lines", "[", "i", "]", "if", "Match", "(", "r'^(?:(?:\\'(?:\\.|[^\\'])*\\')|(?:\"(?:\\.|[^\"])*\")|[^\\'\"])*//'", ",", "line", ")", ":", "no_single_line_comments", "=", "False", "break", "if", "no_single_line_comments", ":", "match", "=", "Match", "(", "r'#endif\\s*/\\*\\s*'", "+", "cppvar", "+", "r'(_)?\\s*\\*/'", ",", "endif", ")", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'_'", ":", "# Low severity warning for double trailing underscore", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "0", ",", "'#endif line should be \"#endif /* %s */\"'", "%", "cppvar", ")", "return", "# Didn't find anything", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "5", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")" ]
https://github.com/nlohmann/json/blob/eb2182414749825be086c825edb5229e5c28503d/third_party/cpplint/cpplint.py#L2363-L2463
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/math_grad.py
python
_SparseSegmentSumGrad
(op, grad)
return (math_ops.unsorted_segment_sum( array_ops.gather(grad, op.inputs[2]), op.inputs[1], input_rows), None, None)
Gradient for SparseSegmentSum.
Gradient for SparseSegmentSum.
[ "Gradient", "for", "SparseSegmentSum", "." ]
def _SparseSegmentSumGrad(op, grad): """Gradient for SparseSegmentSum.""" input_rows = array_ops.shape(op.inputs[0])[0] return (math_ops.unsorted_segment_sum( array_ops.gather(grad, op.inputs[2]), op.inputs[1], input_rows), None, None)
[ "def", "_SparseSegmentSumGrad", "(", "op", ",", "grad", ")", ":", "input_rows", "=", "array_ops", ".", "shape", "(", "op", ".", "inputs", "[", "0", "]", ")", "[", "0", "]", "return", "(", "math_ops", ".", "unsorted_segment_sum", "(", "array_ops", ".", "gather", "(", "grad", ",", "op", ".", "inputs", "[", "2", "]", ")", ",", "op", ".", "inputs", "[", "1", "]", ",", "input_rows", ")", ",", "None", ",", "None", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/math_grad.py#L169-L174
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py
python
TensorArray.dtype
(self)
return self._dtype
The data type of this TensorArray.
The data type of this TensorArray.
[ "The", "data", "type", "of", "this", "TensorArray", "." ]
def dtype(self): """The data type of this TensorArray.""" return self._dtype
[ "def", "dtype", "(", "self", ")", ":", "return", "self", ".", "_dtype" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py#L152-L154
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py
python
Table.validate_version
(self, where=None)
are we trying to operate on an old version?
are we trying to operate on an old version?
[ "are", "we", "trying", "to", "operate", "on", "an", "old", "version?" ]
def validate_version(self, where=None): """ are we trying to operate on an old version? """ if where is not None: if self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1: ws = incompatibility_doc % ".".join([str(x) for x in self.version]) warnings.warn(ws, IncompatibilityWarning)
[ "def", "validate_version", "(", "self", ",", "where", "=", "None", ")", ":", "if", "where", "is", "not", "None", ":", "if", "self", ".", "version", "[", "0", "]", "<=", "0", "and", "self", ".", "version", "[", "1", "]", "<=", "10", "and", "self", ".", "version", "[", "2", "]", "<", "1", ":", "ws", "=", "incompatibility_doc", "%", "\".\"", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "version", "]", ")", "warnings", ".", "warn", "(", "ws", ",", "IncompatibilityWarning", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py#L3379-L3384
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/tseries/offsets.py
python
BusinessHourMixin.next_bday
(self)
Used for moving to next business day.
Used for moving to next business day.
[ "Used", "for", "moving", "to", "next", "business", "day", "." ]
def next_bday(self): """ Used for moving to next business day. """ if self.n >= 0: nb_offset = 1 else: nb_offset = -1 if self._prefix.startswith("C"): # CustomBusinessHour return CustomBusinessDay( n=nb_offset, weekmask=self.weekmask, holidays=self.holidays, calendar=self.calendar, ) else: return BusinessDay(n=nb_offset)
[ "def", "next_bday", "(", "self", ")", ":", "if", "self", ".", "n", ">=", "0", ":", "nb_offset", "=", "1", "else", ":", "nb_offset", "=", "-", "1", "if", "self", ".", "_prefix", ".", "startswith", "(", "\"C\"", ")", ":", "# CustomBusinessHour", "return", "CustomBusinessDay", "(", "n", "=", "nb_offset", ",", "weekmask", "=", "self", ".", "weekmask", ",", "holidays", "=", "self", ".", "holidays", ",", "calendar", "=", "self", ".", "calendar", ",", ")", "else", ":", "return", "BusinessDay", "(", "n", "=", "nb_offset", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/tseries/offsets.py#L704-L721
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tarfile.py
python
TarFile.open
(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs)
Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'r:xz' open for reading with lzma compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'w:xz' open for writing with lzma compression 'x' or 'x:' create a tarfile exclusively without compression, raise an exception if the file is already created 'x:gz' create a gzip compressed tarfile, raise an exception if the file is already created 'x:bz2' create a bzip2 compressed tarfile, raise an exception if the file is already created 'x:xz' create an lzma compressed tarfile, raise an exception if the file is already created 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'r|xz' open an lzma compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing 'w|xz' open an lzma compressed stream for writing
Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
[ "Open", "a", "tar", "archive", "for", "reading", "writing", "or", "appending", ".", "Return", "an", "appropriate", "TarFile", "class", "." ]
def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'r:xz' open for reading with lzma compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'w:xz' open for writing with lzma compression 'x' or 'x:' create a tarfile exclusively without compression, raise an exception if the file is already created 'x:gz' create a gzip compressed tarfile, raise an exception if the file is already created 'x:bz2' create a bzip2 compressed tarfile, raise an exception if the file is already created 'x:xz' create an lzma compressed tarfile, raise an exception if the file is already created 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'r|xz' open an lzma compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing 'w|xz' open an lzma compressed stream for writing """ if not name and not fileobj: raise ValueError("nothing to open") if mode in ("r", "r:*"): # Find out which *open() is appropriate for opening the file. def not_compressed(comptype): return cls.OPEN_METH[comptype] == 'taropen' for comptype in sorted(cls.OPEN_METH, key=not_compressed): func = getattr(cls, cls.OPEN_METH[comptype]) if fileobj is not None: saved_pos = fileobj.tell() try: return func(name, "r", fileobj, **kwargs) except (ReadError, CompressionError): if fileobj is not None: fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") elif ":" in mode: filemode, comptype = mode.split(":", 1) filemode = filemode or "r" comptype = comptype or "tar" # Select the *open() function according to # given compression. if comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) else: raise CompressionError("unknown compression type %r" % comptype) return func(name, filemode, fileobj, **kwargs) elif "|" in mode: filemode, comptype = mode.split("|", 1) filemode = filemode or "r" comptype = comptype or "tar" if filemode not in ("r", "w"): raise ValueError("mode must be 'r' or 'w'") stream = _Stream(name, filemode, comptype, fileobj, bufsize) try: t = cls(name, filemode, stream, **kwargs) except: stream.close() raise t._extfileobj = False return t elif mode in ("a", "w", "x"): return cls.taropen(name, mode, fileobj, **kwargs) raise ValueError("undiscernible mode")
[ "def", "open", "(", "cls", ",", "name", "=", "None", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "bufsize", "=", "RECORDSIZE", ",", "*", "*", "kwargs", ")", ":", "if", "not", "name", "and", "not", "fileobj", ":", "raise", "ValueError", "(", "\"nothing to open\"", ")", "if", "mode", "in", "(", "\"r\"", ",", "\"r:*\"", ")", ":", "# Find out which *open() is appropriate for opening the file.", "def", "not_compressed", "(", "comptype", ")", ":", "return", "cls", ".", "OPEN_METH", "[", "comptype", "]", "==", "'taropen'", "for", "comptype", "in", "sorted", "(", "cls", ".", "OPEN_METH", ",", "key", "=", "not_compressed", ")", ":", "func", "=", "getattr", "(", "cls", ",", "cls", ".", "OPEN_METH", "[", "comptype", "]", ")", "if", "fileobj", "is", "not", "None", ":", "saved_pos", "=", "fileobj", ".", "tell", "(", ")", "try", ":", "return", "func", "(", "name", ",", "\"r\"", ",", "fileobj", ",", "*", "*", "kwargs", ")", "except", "(", "ReadError", ",", "CompressionError", ")", ":", "if", "fileobj", "is", "not", "None", ":", "fileobj", ".", "seek", "(", "saved_pos", ")", "continue", "raise", "ReadError", "(", "\"file could not be opened successfully\"", ")", "elif", "\":\"", "in", "mode", ":", "filemode", ",", "comptype", "=", "mode", ".", "split", "(", "\":\"", ",", "1", ")", "filemode", "=", "filemode", "or", "\"r\"", "comptype", "=", "comptype", "or", "\"tar\"", "# Select the *open() function according to", "# given compression.", "if", "comptype", "in", "cls", ".", "OPEN_METH", ":", "func", "=", "getattr", "(", "cls", ",", "cls", ".", "OPEN_METH", "[", "comptype", "]", ")", "else", ":", "raise", "CompressionError", "(", "\"unknown compression type %r\"", "%", "comptype", ")", "return", "func", "(", "name", ",", "filemode", ",", "fileobj", ",", "*", "*", "kwargs", ")", "elif", "\"|\"", "in", "mode", ":", "filemode", ",", "comptype", "=", "mode", ".", "split", "(", "\"|\"", ",", "1", ")", "filemode", "=", "filemode", "or", "\"r\"", "comptype", "=", "comptype", "or", "\"tar\"", "if", "filemode", "not", "in", "(", "\"r\"", ",", "\"w\"", ")", ":", "raise", "ValueError", "(", "\"mode must be 'r' or 'w'\"", ")", "stream", "=", "_Stream", "(", "name", ",", "filemode", ",", "comptype", ",", "fileobj", ",", "bufsize", ")", "try", ":", "t", "=", "cls", "(", "name", ",", "filemode", ",", "stream", ",", "*", "*", "kwargs", ")", "except", ":", "stream", ".", "close", "(", ")", "raise", "t", ".", "_extfileobj", "=", "False", "return", "t", "elif", "mode", "in", "(", "\"a\"", ",", "\"w\"", ",", "\"x\"", ")", ":", "return", "cls", ".", "taropen", "(", "name", ",", "mode", ",", "fileobj", ",", "*", "*", "kwargs", ")", "raise", "ValueError", "(", "\"undiscernible mode\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tarfile.py#L1527-L1615
arkenthera/electron-vibrancy
383153ef9ccb23a6c7517150d6bb0794dff3115e
scripts/cpplint.py
python
_ShouldPrintError
(category, confidence, linenum)
return True
If confidence >= verbose, category passes filter and is not suppressed.
If confidence >= verbose, category passes filter and is not suppressed.
[ "If", "confidence", ">", "=", "verbose", "category", "passes", "filter", "and", "is", "not", "suppressed", "." ]
def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True
[ "def", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "# There are three ways we might decide not to print an error message:", "# a \"NOLINT(category)\" comment appears in the source,", "# the verbosity level isn't high enough, or the filters filter it out.", "if", "IsErrorSuppressedByNolint", "(", "category", ",", "linenum", ")", ":", "return", "False", "if", "confidence", "<", "_cpplint_state", ".", "verbose_level", ":", "return", "False", "is_filtered", "=", "False", "for", "one_filter", "in", "_Filters", "(", ")", ":", "if", "one_filter", ".", "startswith", "(", "'-'", ")", ":", "if", "category", ".", "startswith", "(", "one_filter", "[", "1", ":", "]", ")", ":", "is_filtered", "=", "True", "elif", "one_filter", ".", "startswith", "(", "'+'", ")", ":", "if", "category", ".", "startswith", "(", "one_filter", "[", "1", ":", "]", ")", ":", "is_filtered", "=", "False", "else", ":", "assert", "False", "# should have been checked for in SetFilter.", "if", "is_filtered", ":", "return", "False", "return", "True" ]
https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L929-L954
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetNoImportLibrary
(self, config)
return noimplib == 'true'
If NoImportLibrary: true, ninja will not expect the output to include an import library.
If NoImportLibrary: true, ninja will not expect the output to include an import library.
[ "If", "NoImportLibrary", ":", "true", "ninja", "will", "not", "expect", "the", "output", "to", "include", "an", "import", "library", "." ]
def GetNoImportLibrary(self, config): """If NoImportLibrary: true, ninja will not expect the output to include an import library.""" config = self._TargetConfig(config) noimplib = self._Setting(('NoImportLibrary',), config) return noimplib == 'true'
[ "def", "GetNoImportLibrary", "(", "self", ",", "config", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "noimplib", "=", "self", ".", "_Setting", "(", "(", "'NoImportLibrary'", ",", ")", ",", "config", ")", "return", "noimplib", "==", "'true'" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/msvs_emulation.py#L418-L423
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/random.py
python
Random.vonmisesvariate
(self, mu, kappa)
return theta
Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.
Circular data distribution.
[ "Circular", "data", "distribution", "." ]
def vonmisesvariate(self, mu, kappa): """Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. """ # mu: mean angle (in radians between 0 and 2*pi) # kappa: concentration parameter kappa (>= 0) # if kappa = 0 generate uniform random angle # Based upon an algorithm published in: Fisher, N.I., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. # Thanks to Magnus Kessler for a correction to the # implementation of step 4. random = self.random if kappa <= 1e-6: return TWOPI * random() s = 0.5 / kappa r = s + _sqrt(1.0 + s * s) while 1: u1 = random() z = _cos(_pi * u1) d = z / (r + z) u2 = random() if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d): break q = 1.0 / r f = (q + z) / (1.0 + q * z) u3 = random() if u3 > 0.5: theta = (mu + _acos(f)) % TWOPI else: theta = (mu - _acos(f)) % TWOPI return theta
[ "def", "vonmisesvariate", "(", "self", ",", "mu", ",", "kappa", ")", ":", "# mu: mean angle (in radians between 0 and 2*pi)", "# kappa: concentration parameter kappa (>= 0)", "# if kappa = 0 generate uniform random angle", "# Based upon an algorithm published in: Fisher, N.I.,", "# \"Statistical Analysis of Circular Data\", Cambridge", "# University Press, 1993.", "# Thanks to Magnus Kessler for a correction to the", "# implementation of step 4.", "random", "=", "self", ".", "random", "if", "kappa", "<=", "1e-6", ":", "return", "TWOPI", "*", "random", "(", ")", "s", "=", "0.5", "/", "kappa", "r", "=", "s", "+", "_sqrt", "(", "1.0", "+", "s", "*", "s", ")", "while", "1", ":", "u1", "=", "random", "(", ")", "z", "=", "_cos", "(", "_pi", "*", "u1", ")", "d", "=", "z", "/", "(", "r", "+", "z", ")", "u2", "=", "random", "(", ")", "if", "u2", "<", "1.0", "-", "d", "*", "d", "or", "u2", "<=", "(", "1.0", "-", "d", ")", "*", "_exp", "(", "d", ")", ":", "break", "q", "=", "1.0", "/", "r", "f", "=", "(", "q", "+", "z", ")", "/", "(", "1.0", "+", "q", "*", "z", ")", "u3", "=", "random", "(", ")", "if", "u3", ">", "0.5", ":", "theta", "=", "(", "mu", "+", "_acos", "(", "f", ")", ")", "%", "TWOPI", "else", ":", "theta", "=", "(", "mu", "-", "_acos", "(", "f", ")", ")", "%", "TWOPI", "return", "theta" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/random.py#L456-L500
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
win32/Lib/regutil.py
python
GetRegistryDefaultValue
(subkey, rootkey=None)
return win32api.RegQueryValue(rootkey, subkey)
A helper to return the default value for a key in the registry.
A helper to return the default value for a key in the registry.
[ "A", "helper", "to", "return", "the", "default", "value", "for", "a", "key", "in", "the", "registry", "." ]
def GetRegistryDefaultValue(subkey, rootkey=None): """A helper to return the default value for a key in the registry.""" if rootkey is None: rootkey = GetRootKey() return win32api.RegQueryValue(rootkey, subkey)
[ "def", "GetRegistryDefaultValue", "(", "subkey", ",", "rootkey", "=", "None", ")", ":", "if", "rootkey", "is", "None", ":", "rootkey", "=", "GetRootKey", "(", ")", "return", "win32api", ".", "RegQueryValue", "(", "rootkey", ",", "subkey", ")" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/Lib/regutil.py#L37-L41
BSVino/DoubleAction
c550b168a3e919926c198c30240f506538b92e75
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py
python
_Tokenizer.ConsumeByteString
(self)
return "".join(list)
Consumes a byte array value. Returns: The array parsed (as a string). Raises: ParseError: If a byte array value couldn't be consumed.
Consumes a byte array value.
[ "Consumes", "a", "byte", "array", "value", "." ]
def ConsumeByteString(self): """Consumes a byte array value. Returns: The array parsed (as a string). Raises: ParseError: If a byte array value couldn't be consumed. """ list = [self._ConsumeSingleByteString()] while len(self.token) > 0 and self.token[0] in ('\'', '"'): list.append(self._ConsumeSingleByteString()) return "".join(list)
[ "def", "ConsumeByteString", "(", "self", ")", ":", "list", "=", "[", "self", ".", "_ConsumeSingleByteString", "(", ")", "]", "while", "len", "(", "self", ".", "token", ")", ">", "0", "and", "self", ".", "token", "[", "0", "]", "in", "(", "'\\''", ",", "'\"'", ")", ":", "list", ".", "append", "(", "self", ".", "_ConsumeSingleByteString", "(", ")", ")", "return", "\"\"", ".", "join", "(", "list", ")" ]
https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/text_format.py#L530-L542
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Node/FS.py
python
Base.get_labspath
(self)
return self.dir.entry_labspath(self.name)
Get the absolute path of the file.
Get the absolute path of the file.
[ "Get", "the", "absolute", "path", "of", "the", "file", "." ]
def get_labspath(self): """Get the absolute path of the file.""" return self.dir.entry_labspath(self.name)
[ "def", "get_labspath", "(", "self", ")", ":", "return", "self", ".", "dir", ".", "entry_labspath", "(", "self", ".", "name", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Node/FS.py#L830-L832
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py
python
Dirichlet.std
(self, name="std")
Standard deviation of the distribution.
Standard deviation of the distribution.
[ "Standard", "deviation", "of", "the", "distribution", "." ]
def std(self, name="std"): """Standard deviation of the distribution.""" with ops.name_scope(self.name): with ops.op_scope([], name): return math_ops.sqrt(self.variance())
[ "def", "std", "(", "self", ",", "name", "=", "\"std\"", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "]", ",", "name", ")", ":", "return", "math_ops", ".", "sqrt", "(", "self", ".", "variance", "(", ")", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/dirichlet.py#L252-L256
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/joblib/joblib/externals/loky/process_executor.py
python
_get_chunks
(chunksize, *iterables)
Iterates over zip()ed iterables in chunks.
Iterates over zip()ed iterables in chunks.
[ "Iterates", "over", "zip", "()", "ed", "iterables", "in", "chunks", "." ]
def _get_chunks(chunksize, *iterables): """Iterates over zip()ed iterables in chunks. """ if sys.version_info < (3, 3): it = itertools.izip(*iterables) else: it = zip(*iterables) while True: chunk = tuple(itertools.islice(it, chunksize)) if not chunk: return yield chunk
[ "def", "_get_chunks", "(", "chunksize", ",", "*", "iterables", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "3", ")", ":", "it", "=", "itertools", ".", "izip", "(", "*", "iterables", ")", "else", ":", "it", "=", "zip", "(", "*", "iterables", ")", "while", "True", ":", "chunk", "=", "tuple", "(", "itertools", ".", "islice", "(", "it", ",", "chunksize", ")", ")", "if", "not", "chunk", ":", "return", "yield", "chunk" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/externals/loky/process_executor.py#L331-L341
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0341-Flatten-Nested-List-Iterator/0341.py
python
NestedInteger.getInteger
(self)
@return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list :rtype int
[]
def getInteger(self): """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list :rtype int """
[ "def", "getInteger", "(", "self", ")", ":" ]
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0341-Flatten-Nested-List-Iterator/0341.py#L8-L13
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
PyGridTableBase.Destroy
(*args, **kwargs)
return _grid.PyGridTableBase_Destroy(*args, **kwargs)
Destroy(self) Deletes the C++ object this Python object is a proxy for.
Destroy(self)
[ "Destroy", "(", "self", ")" ]
def Destroy(*args, **kwargs): """ Destroy(self) Deletes the C++ object this Python object is a proxy for. """ args[0].this.own(False) return _grid.PyGridTableBase_Destroy(*args, **kwargs)
[ "def", "Destroy", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "[", "0", "]", ".", "this", ".", "own", "(", "False", ")", "return", "_grid", ".", "PyGridTableBase_Destroy", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L941-L948