nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py
python
_format_elemcreate
(etype, script=False, *args, **kw)
return spec, opts
Formats args and kw according to the given element factory etype.
Formats args and kw according to the given element factory etype.
[ "Formats", "args", "and", "kw", "according", "to", "the", "given", "element", "factory", "etype", "." ]
def _format_elemcreate(etype, script=False, *args, **kw): """Formats args and kw according to the given element factory etype.""" spec = None opts = () if etype in ("image", "vsapi"): if etype == "image": # define an element based on an image # first arg should be the default image name iname = args[0] # next args, if any, are statespec/value pairs which is almost # a mapdict, but we just need the value imagespec = _join(_mapdict_values(args[1:])) spec = "%s %s" % (iname, imagespec) else: # define an element whose visual appearance is drawn using the # Microsoft Visual Styles API which is responsible for the # themed styles on Windows XP and Vista. # Availability: Tk 8.6, Windows XP and Vista. class_name, part_id = args[:2] statemap = _join(_mapdict_values(args[2:])) spec = "%s %s %s" % (class_name, part_id, statemap) opts = _format_optdict(kw, script) elif etype == "from": # clone an element # it expects a themename and optionally an element to clone from, # otherwise it will clone {} (empty element) spec = args[0] # theme name if len(args) > 1: # elementfrom specified opts = (_format_optvalue(args[1], script),) if script: spec = '{%s}' % spec opts = ' '.join(opts) return spec, opts
[ "def", "_format_elemcreate", "(", "etype", ",", "script", "=", "False", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "spec", "=", "None", "opts", "=", "(", ")", "if", "etype", "in", "(", "\"image\"", ",", "\"vsapi\"", ")", ":", "if", "etype", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py#L117-L152
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridInterface.HideProperty
(*args, **kwargs)
return _propgrid.PropertyGridInterface_HideProperty(*args, **kwargs)
HideProperty(self, PGPropArg id, bool hide=True, int flags=PG_RECURSE) -> bool
HideProperty(self, PGPropArg id, bool hide=True, int flags=PG_RECURSE) -> bool
[ "HideProperty", "(", "self", "PGPropArg", "id", "bool", "hide", "=", "True", "int", "flags", "=", "PG_RECURSE", ")", "-", ">", "bool" ]
def HideProperty(*args, **kwargs): """HideProperty(self, PGPropArg id, bool hide=True, int flags=PG_RECURSE) -> bool""" return _propgrid.PropertyGridInterface_HideProperty(*args, **kwargs)
[ "def", "HideProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_HideProperty", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1288-L1290
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py
python
easy_install.check_site_dir
(self)
Verify that self.install_dir is .pth-capable dir, if needed
Verify that self.install_dir is .pth-capable dir, if needed
[ "Verify", "that", "self", ".", "install_dir", "is", ".", "pth", "-", "capable", "dir", "if", "needed" ]
def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir, 'easy-install.pth') if not os.path.exists(instdir): try: os.makedirs(instdir) except (OSError, IOError): self.cant_write_to_target() # Is it a configured, PYTHONPATH, implicit, or explicit site dir? is_site_dir = instdir in self.all_site_dirs if not is_site_dir and not self.multi_version: # No? Then directly test whether it does .pth file processing is_site_dir = self.check_pth_processing() else: # make sure we can write to target dir testfile = self.pseudo_tempname() + '.write-test' test_exists = os.path.exists(testfile) try: if test_exists: os.unlink(testfile) open(testfile, 'w').close() os.unlink(testfile) except (OSError, IOError): self.cant_write_to_target() if not is_site_dir and not self.multi_version: # Can't install non-multi to non-site dir with easy_install pythonpath = os.environ.get('PYTHONPATH', '') log.warn(self.__no_default_msg, self.install_dir, pythonpath) if is_site_dir: if self.pth_file is None: self.pth_file = PthDistributions(pth_file, self.all_site_dirs) else: self.pth_file = None if instdir not in map(normalize_path, _pythonpath()): # only PYTHONPATH dirs need a site.py, so pretend it's there self.sitepy_installed = True elif self.multi_version and not os.path.exists(pth_file): self.sitepy_installed = True # don't need site.py in this case self.pth_file = None # and don't create a .pth file self.install_dir = instdir
[ "def", "check_site_dir", "(", "self", ")", ":", "instdir", "=", "normalize_path", "(", "self", ".", "install_dir", ")", "pth_file", "=", "os", ".", "path", ".", "join", "(", "instdir", ",", "'easy-install.pth'", ")", "if", "not", "os", ".", "path", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/command/easy_install.py#L457-L504
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/report.py
python
Displayer.display
(self, loops=None, level=None, cols=None)
return df.loc[rows, cols].to_string()
Display the report file. Parameters ---------- loops: list, optional List of loop names (e.g., ['A', 'Y']) level: int, optional Maximum level of loop nest to print. cols: list, optional List of column names. (e.g., ['Trip Count']) Returns ---------- str String representation of pandas dataframe being displayed.
Display the report file. Parameters ---------- loops: list, optional List of loop names (e.g., ['A', 'Y']) level: int, optional Maximum level of loop nest to print. cols: list, optional List of column names. (e.g., ['Trip Count']) Returns ---------- str String representation of pandas dataframe being displayed.
[ "Display", "the", "report", "file", ".", "Parameters", "----------", "loops", ":", "list", "optional", "List", "of", "loop", "names", "(", "e", ".", "g", ".", "[", "A", "Y", "]", ")", "level", ":", "int", "optional", "Maximum", "level", "of", "loop", ...
def display(self, loops=None, level=None, cols=None): """Display the report file. Parameters ---------- loops: list, optional List of loop names (e.g., ['A', 'Y']) level: int, optional Maximum level of loop nest to print. cols: list, optional List of column names. (e.g., ['Trip Count']) Returns ---------- str String representation of pandas dataframe being displayed. """ if loops is None: loops = self._loop_name_aux if level is None: level = self._max_level if cols is None: cols = self._category_aux selected = [] for l in loops: if type(l) != str: l = str(l).split(",")[0].split("(")[1] # TODO: add support for axis value specification for k in self._loop_name_aux: if l in k: selected.append(k) rows = [] if level > self._max_level: rows = selected else: for k in selected: lev = k.count('+') if lev <= level: rows.append(k) ncols = [] for c in cols: for ca in self._category_aux: if c in ca: ncols.append(ca) alignment = ('left',) for i in range(len(cols)): alignment = alignment + ('right',) df = pd.DataFrame(data=self._data, index=self._loop_name_aux) print(tabulate(df.loc[rows, cols], headers=cols, tablefmt='psql', colalign=alignment)) print('* Units in {}'.format(self.unit)) splt = df.loc[rows, cols].to_string().split("\n") pd.set_option('max_colwidth', len(splt[0]) * 100) return df.loc[rows, cols].to_string()
[ "def", "display", "(", "self", ",", "loops", "=", "None", ",", "level", "=", "None", ",", "cols", "=", "None", ")", ":", "if", "loops", "is", "None", ":", "loops", "=", "self", ".", "_loop_name_aux", "if", "level", "is", "None", ":", "level", "=", ...
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/report.py#L376-L434
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/build/scanner.py
python
Scanner.pattern
(self)
Returns a pattern to use for scanning.
Returns a pattern to use for scanning.
[ "Returns", "a", "pattern", "to", "use", "for", "scanning", "." ]
def pattern (self): """ Returns a pattern to use for scanning. """ raise BaseException ("method must be overriden")
[ "def", "pattern", "(", "self", ")", ":", "raise", "BaseException", "(", "\"method must be overriden\"", ")" ]
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/scanner.py#L97-L100
zlgopen/awtk
2c49e854a78749d9092907c027a7fba9062be549
3rd/mbedtls/scripts/assemble_changelog.py
python
ChangelogFormat.split_categories
(cls, version_body)
Split a changelog version section body into categories. Return a list of `CategoryContent` the name is category title without any formatting.
Split a changelog version section body into categories.
[ "Split", "a", "changelog", "version", "section", "body", "into", "categories", "." ]
def split_categories(cls, version_body): """Split a changelog version section body into categories. Return a list of `CategoryContent` the name is category title without any formatting. """ raise NotImplementedError
[ "def", "split_categories", "(", "cls", ",", "version_body", ")", ":", "raise", "NotImplementedError" ]
https://github.com/zlgopen/awtk/blob/2c49e854a78749d9092907c027a7fba9062be549/3rd/mbedtls/scripts/assemble_changelog.py#L106-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/sidebar.py
python
get_widget_padding
(widget)
return padx, pady
Get the total padding of a Tk widget, including its border.
Get the total padding of a Tk widget, including its border.
[ "Get", "the", "total", "padding", "of", "a", "Tk", "widget", "including", "its", "border", "." ]
def get_widget_padding(widget): """Get the total padding of a Tk widget, including its border.""" # TODO: use also in codecontext.py manager = widget.winfo_manager() if manager == 'pack': info = widget.pack_info() elif manager == 'grid': info = widget.grid_info() else: raise ValueError(f"Unsupported geometry manager: {manager}") # All values are passed through getint(), since some # values may be pixel objects, which can't simply be added to ints. padx = sum(map(widget.tk.getint, [ info['padx'], widget.cget('padx'), widget.cget('border'), ])) pady = sum(map(widget.tk.getint, [ info['pady'], widget.cget('pady'), widget.cget('border'), ])) return padx, pady
[ "def", "get_widget_padding", "(", "widget", ")", ":", "# TODO: use also in codecontext.py", "manager", "=", "widget", ".", "winfo_manager", "(", ")", "if", "manager", "==", "'pack'", ":", "info", "=", "widget", ".", "pack_info", "(", ")", "elif", "manager", "=...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/sidebar.py#L17-L40
fossephate/JoyCon-Driver
857e4e76e26f05d72400ae5d9f2a22cae88f3548
joycon-driver/full/wxWidgets-3.0.3/build/tools/builder.py
python
Builder.doSetup
(self)
Do anything special needed to configure the environment to build with this builder.
Do anything special needed to configure the environment to build with this builder.
[ "Do", "anything", "special", "needed", "to", "configure", "the", "environment", "to", "build", "with", "this", "builder", "." ]
def doSetup(self): """ Do anything special needed to configure the environment to build with this builder. """ pass
[ "def", "doSetup", "(", "self", ")", ":", "pass" ]
https://github.com/fossephate/JoyCon-Driver/blob/857e4e76e26f05d72400ae5d9f2a22cae88f3548/joycon-driver/full/wxWidgets-3.0.3/build/tools/builder.py#L46-L51
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/training/saver.py
python
update_checkpoint_state
(save_dir, model_checkpoint_path, all_model_checkpoint_paths=None, latest_filename=None)
Updates the content of the 'checkpoint' file. This updates the checkpoint file containing a CheckpointState proto. Args: save_dir: Directory where the model was saved. model_checkpoint_path: The checkpoint file. all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted checkpoints, sorted from oldest to newest. If this is a non-empty list, the last element must be equal to model_checkpoint_path. These paths are also saved in the CheckpointState proto. latest_filename: Optional name of the checkpoint file. Default to 'checkpoint'. Raises: RuntimeError: If any of the model checkpoint paths conflict with the file containing CheckpointSate.
Updates the content of the 'checkpoint' file.
[ "Updates", "the", "content", "of", "the", "checkpoint", "file", "." ]
def update_checkpoint_state(save_dir, model_checkpoint_path, all_model_checkpoint_paths=None, latest_filename=None): """Updates the content of the 'checkpoint' file. This updates the checkpoint file containing a CheckpointState proto. Args: save_dir: Directory where the model was saved. model_checkpoint_path: The checkpoint file. all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted checkpoints, sorted from oldest to newest. If this is a non-empty list, the last element must be equal to model_checkpoint_path. These paths are also saved in the CheckpointState proto. latest_filename: Optional name of the checkpoint file. Default to 'checkpoint'. Raises: RuntimeError: If any of the model checkpoint paths conflict with the file containing CheckpointSate. """ _update_checkpoint_state( save_dir=save_dir, model_checkpoint_path=model_checkpoint_path, all_model_checkpoint_paths=all_model_checkpoint_paths, latest_filename=latest_filename, save_relative_paths=False)
[ "def", "update_checkpoint_state", "(", "save_dir", ",", "model_checkpoint_path", ",", "all_model_checkpoint_paths", "=", "None", ",", "latest_filename", "=", "None", ")", ":", "_update_checkpoint_state", "(", "save_dir", "=", "save_dir", ",", "model_checkpoint_path", "=...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/saver.py#L799-L827
strukturag/libheif
0082fea96ee70a20c8906a0373bedec0c01777bc
scripts/cpplint.py
python
CheckLanguage
(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error)
Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found.
Checks rules from the 'C++ language rules' section of cppguide.html.
[ "Checks", "rules", "from", "the", "C", "++", "language", "rules", "section", "of", "cppguide", ".", "html", "." ]
def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Reset include state across preprocessor directives. This is meant # to silence warnings for conditional includes. match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) if match: include_state.ResetSection(match.group(1)) # Make Windows paths like Unix. fullname = os.path.abspath(filename).replace('\\', '/') # Perform other checks now that we are sure that this is not an include line CheckCasts(filename, clean_lines, linenum, error) CheckGlobalStatic(filename, clean_lines, linenum, error) CheckPrintf(filename, clean_lines, linenum, error) if file_extension == 'h': # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes declare or disable copy/assign # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(unknown): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue if Search(r'base::size\(.+\)', tok): continue if Search(r'std::size\(.+\)', tok): continue if Search(r'std::extent<.+>', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension == 'h' and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'https://google.github.io/styleguide/cppguide.html#Namespaces' ' for more information.')
[ "def", "CheckLanguage", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "file_extension", ",", "include_state", ",", "nesting_state", ",", "error", ")", ":", "# If the line is empty or consists of entirely a comment, no need to", "# check it.", "line", "=", "cle...
https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L4549-L4707
p4lang/p4c
3272e79369f20813cc1a555a5eb26f44432f84a4
tools/cpplint.py
python
CheckCasts
(filename, clean_lines, linenum, error)
Various cast related checks. 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.
Various cast related checks.
[ "Various", "cast", "related", "checks", "." ]
def CheckCasts(filename, clean_lines, linenum, error): """Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b' r'(int|float|double|bool|char|int32|uint32|int64|uint64)' r'(\([^)].*)', line) expecting_function = ExpectingFunctionArgs(clean_lines, linenum) if match and not expecting_function: matched_type = match.group(2) # matched_new_or_template is used to silence two false positives: # - New operators # - Template arguments with function types # # For template arguments, we match on types immediately following # an opening bracket without any spaces. This is a fast way to # silence the common case where the function type is the first # template argument. False negative with less-than comparison is # avoided because those operators are usually followed by a space. # # function<double(double)> // bracket + no space = false positive # value < double(42) // bracket + space = true positive matched_new_or_template = match.group(1) # Avoid arrays by looking for brackets that come after the closing # parenthesis. if Match(r'\([^()]+\)\s*\[', match.group(3)): return # Other things to ignore: # - Function pointers # - Casts to pointer types # - Placement new # - Alias declarations matched_funcptr = match.group(3) if (matched_new_or_template is None and not (matched_funcptr and (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', matched_funcptr) or matched_funcptr.startswith('(*)'))) and not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and not Search(r'new\(\S+\)\s*' + matched_type, line)): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % matched_type) if not expecting_function: CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. # # Some non-identifier character is required before the '&' for the # expression to be recognized as a cast. These are casts: # expression = &static_cast<int*>(temporary()); # function(&(int*)(temporary())); # # This is not a cast: # reference_type&(int* function_param); match = Search( r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) if match: # Try a better error message when the & is bound to something # dereferenced by the casted pointer, as opposed to the casted # pointer itself. parenthesis_error = False match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) if match: _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) if x1 >= 0 and clean_lines.elided[y1][x1] == '(': _, y2, x2 = CloseExpression(clean_lines, y1, x1) if x2 >= 0: extended_line = clean_lines.elided[y2][x2:] if y2 < clean_lines.NumLines() - 1: extended_line += clean_lines.elided[y2 + 1] if Match(r'\s*(?:->|\[)', extended_line): parenthesis_error = True if parenthesis_error: error(filename, linenum, 'readability/casting', 4, ('Are you taking an address of something dereferenced ' 'from a cast? Wrapping the dereferenced expression in ' 'parentheses will make the binding more obvious')) else: error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after'))
[ "def", "CheckCasts", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Check to see if they're using an conversion function cast.", "# I just try to capture the most common basic t...
https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/cpplint.py#L5701-L5817
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.ping_stop
(self)
Stop sending ICMPv6 Echo Requests.
Stop sending ICMPv6 Echo Requests.
[ "Stop", "sending", "ICMPv6", "Echo", "Requests", "." ]
def ping_stop(self): """Stop sending ICMPv6 Echo Requests.""" self.execute_command('ping stop')
[ "def", "ping_stop", "(", "self", ")", ":", "self", ".", "execute_command", "(", "'ping stop'", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L259-L261
gtcasl/gpuocelot
fa63920ee7c5f9a86e264cd8acd4264657cbd190
ocelot/scripts/which.py
python
which_files
(file, mode=os.F_OK | os.X_OK, path=None, pathext=None)
Generate full paths, where the file*is accesible under mode and is located in the directory passed as a part of the file name, or in any directory on path if a base file name is passed. The mode matches an existing executable file by default. The path defaults to the PATH environment variable, or to os.defpath if the PATH variable is not set. On Windows, a current directory is searched before directories in the PATH variable, but not before directories in an explicitly passed path string or iterable. The pathext is used to match files with any of the extensions appended to file. On Windows, it defaults to the ``PATHEXT`` environment variable. If the PATHEXT variable is not set, then the default pathext value is hardcoded for different Windows versions, to match the actual search performed on command execution. On Windows <= 4.x, ie. NT and older, it defaults to '.COM;.EXE;.BAT;.CMD'. On Windows 5.x, ie. 2k/XP/2003, the extensions '.VBS;.VBE;.JS;.JSE;.WSF;.WSH' are appended, On Windows >= 6.x, ie. Vista/2008/7, the extension '.MSC' is further appended. The actual search on command execution may differ under Wine, which may use a different default value, that is not treated specially here. In each directory, the file is first searched without any additional extension, even when a pathext string or iterable is explicitly passed. >>> def test(expected, *args, **argd): ... result = list(which_files(*args, **argd)) ... assert result == expected, 'which_files: %s != %s' % (result, expected) ... ... try: ... result = [ which(*args, **argd) ] ... except IOError: ... result = [] ... assert result[:1] == expected[:1], 'which: %s != %s' % (result[:1], expected[:1]) >>> ### Set up >>> import stat, tempfile >>> dir = tempfile.mkdtemp(prefix='test-') >>> ext = '.ext' >>> tmp = tempfile.NamedTemporaryFile(prefix='command-', suffix=ext, dir=dir) >>> name = tmp.name >>> file = os.path.basename(name) >>> here = os.path.join(os.curdir, file) >>> nonexistent = '%s-nonexistent' % name >>> path = os.pathsep.join([ nonexistent, name, dir, dir ]) ... # Test also that duplicates are removed, and non-existent objects ... # or non-directories in path do not trigger any exceptions. >>> ### Test permissions >>> test(_windows and [name] or [], file, path=path) >>> test(_windows and [name] or [], file, mode=os.X_OK, path=path) ... # executable flag is not needed on Windows >>> test([name], file, mode=os.F_OK, path=path) >>> test([name], file, mode=os.R_OK, path=path) >>> test([name], file, mode=os.W_OK, path=path) >>> test([name], file, mode=os.R_OK|os.W_OK, path=path) >>> os.chmod(name, stat.S_IRWXU) >>> test([name], file, mode=os.R_OK|os.W_OK|os.X_OK, path=path) >>> ### Test paths >>> _save_path = os.environ.get('PATH', '') >>> cwd = os.getcwd() >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> test([], nonexistent, path=path) >>> test([name], file, path=path) >>> test([name], name, path=path) >>> test([name], name, path='') >>> test([name], name, path=nonexistent) >>> os.chdir(dir) >>> test([name], file, path=path) >>> test([here], file, path=os.curdir) >>> test([name], name, path=os.curdir) >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> os.environ['PATH'] = path >>> test(_windows and [here] or [name], file) ... # current directory is always searched first on Windows >>> os.environ['PATH'] = os.curdir >>> test([here], file) >>> test([name], name) >>> os.environ['PATH'] = '' >>> test(_windows and [here] or [], file) >>> os.environ['PATH'] = nonexistent >>> test(_windows and [here] or [], file) >>> os.chdir(cwd) >>> os.environ['PATH'] = path >>> test([name], file) >>> os.environ['PATH'] = _save_path >>> ### Test extensions >>> test([], file[:-4], path=path, pathext='') >>> test([], file[:-4], path=path, pathext=nonexistent) >>> test([name], file[:-4], path=path, pathext=ext) >>> test([name], file, path=path, pathext=ext) >>> test([name], file, path=path, pathext='') >>> test([name], file, path=path, pathext=nonexistent) >>> ### Tear down >>> tmp.close() >>> os.rmdir(dir)
Generate full paths, where the file*is accesible under mode and is located in the directory passed as a part of the file name, or in any directory on path if a base file name is passed.
[ "Generate", "full", "paths", "where", "the", "file", "*", "is", "accesible", "under", "mode", "and", "is", "located", "in", "the", "directory", "passed", "as", "a", "part", "of", "the", "file", "name", "or", "in", "any", "directory", "on", "path", "if", ...
def which_files(file, mode=os.F_OK | os.X_OK, path=None, pathext=None): """ Generate full paths, where the file*is accesible under mode and is located in the directory passed as a part of the file name, or in any directory on path if a base file name is passed. The mode matches an existing executable file by default. The path defaults to the PATH environment variable, or to os.defpath if the PATH variable is not set. On Windows, a current directory is searched before directories in the PATH variable, but not before directories in an explicitly passed path string or iterable. The pathext is used to match files with any of the extensions appended to file. On Windows, it defaults to the ``PATHEXT`` environment variable. If the PATHEXT variable is not set, then the default pathext value is hardcoded for different Windows versions, to match the actual search performed on command execution. On Windows <= 4.x, ie. NT and older, it defaults to '.COM;.EXE;.BAT;.CMD'. On Windows 5.x, ie. 2k/XP/2003, the extensions '.VBS;.VBE;.JS;.JSE;.WSF;.WSH' are appended, On Windows >= 6.x, ie. Vista/2008/7, the extension '.MSC' is further appended. The actual search on command execution may differ under Wine, which may use a different default value, that is not treated specially here. In each directory, the file is first searched without any additional extension, even when a pathext string or iterable is explicitly passed. >>> def test(expected, *args, **argd): ... result = list(which_files(*args, **argd)) ... assert result == expected, 'which_files: %s != %s' % (result, expected) ... ... try: ... result = [ which(*args, **argd) ] ... except IOError: ... result = [] ... assert result[:1] == expected[:1], 'which: %s != %s' % (result[:1], expected[:1]) >>> ### Set up >>> import stat, tempfile >>> dir = tempfile.mkdtemp(prefix='test-') >>> ext = '.ext' >>> tmp = tempfile.NamedTemporaryFile(prefix='command-', suffix=ext, dir=dir) >>> name = tmp.name >>> file = os.path.basename(name) >>> here = os.path.join(os.curdir, file) >>> nonexistent = '%s-nonexistent' % name >>> path = os.pathsep.join([ nonexistent, name, dir, dir ]) ... # Test also that duplicates are removed, and non-existent objects ... # or non-directories in path do not trigger any exceptions. >>> ### Test permissions >>> test(_windows and [name] or [], file, path=path) >>> test(_windows and [name] or [], file, mode=os.X_OK, path=path) ... # executable flag is not needed on Windows >>> test([name], file, mode=os.F_OK, path=path) >>> test([name], file, mode=os.R_OK, path=path) >>> test([name], file, mode=os.W_OK, path=path) >>> test([name], file, mode=os.R_OK|os.W_OK, path=path) >>> os.chmod(name, stat.S_IRWXU) >>> test([name], file, mode=os.R_OK|os.W_OK|os.X_OK, path=path) >>> ### Test paths >>> _save_path = os.environ.get('PATH', '') >>> cwd = os.getcwd() >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> test([], nonexistent, path=path) >>> test([name], file, path=path) >>> test([name], name, path=path) >>> test([name], name, path='') >>> test([name], name, path=nonexistent) >>> os.chdir(dir) >>> test([name], file, path=path) >>> test([here], file, path=os.curdir) >>> test([name], name, path=os.curdir) >>> test([], file, path='') >>> test([], file, path=nonexistent) >>> os.environ['PATH'] = path >>> test(_windows and [here] or [name], file) ... # current directory is always searched first on Windows >>> os.environ['PATH'] = os.curdir >>> test([here], file) >>> test([name], name) >>> os.environ['PATH'] = '' >>> test(_windows and [here] or [], file) >>> os.environ['PATH'] = nonexistent >>> test(_windows and [here] or [], file) >>> os.chdir(cwd) >>> os.environ['PATH'] = path >>> test([name], file) >>> os.environ['PATH'] = _save_path >>> ### Test extensions >>> test([], file[:-4], path=path, pathext='') >>> test([], file[:-4], path=path, pathext=nonexistent) >>> test([name], file[:-4], path=path, pathext=ext) >>> test([name], file, path=path, pathext=ext) >>> test([name], file, path=path, pathext='') >>> test([name], file, path=path, pathext=nonexistent) >>> ### Tear down >>> tmp.close() >>> os.rmdir(dir) """ filepath, file = os.path.split(file) if filepath: path = (filepath,) elif path is None: path = os.environ.get('PATH', os.defpath).split(os.pathsep) if _windows and not os.curdir in path: path.insert(0, os.curdir) # current directory is always searched first on Windows elif isinstance(path, basestring): path = path.split(os.pathsep) if pathext is None: pathext = [''] if _windows: pathext += (os.environ.get('PATHEXT', '') or _getwinpathext()).lower().split(os.pathsep) elif isinstance(pathext, basestring): pathext = pathext.split(os.pathsep) if not '' in pathext: pathext.insert(0, '') # always check command without extension, even for an explicitly passed pathext seen = set() for dir in path: if dir: # only non-empty directories are searched id = os.path.normcase(os.path.abspath(dir)) if not id in seen: # each directory is searched only once seen.add(id) woex = os.path.join(dir, file) for ext in pathext: name = woex + ext if os.path.exists(name) and os.access(name, mode): yield name
[ "def", "which_files", "(", "file", ",", "mode", "=", "os", ".", "F_OK", "|", "os", ".", "X_OK", ",", "path", "=", "None", ",", "pathext", "=", "None", ")", ":", "filepath", ",", "file", "=", "os", ".", "path", ".", "split", "(", "file", ")", "i...
https://github.com/gtcasl/gpuocelot/blob/fa63920ee7c5f9a86e264cd8acd4264657cbd190/ocelot/scripts/which.py#L88-L230
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/operator/_local_operator.py
python
LocalOperator.__init__
( self, hilbert: AbstractHilbert, operators: Union[List[Array], Array] = [], acting_on: Union[List[int], List[List[int]]] = [], constant: numbers.Number = 0, dtype: Optional[DType] = None, )
r""" Constructs a new ``LocalOperator`` given a hilbert space and (if specified) a constant level shift. Args: hilbert (netket.AbstractHilbert): Hilbert space the operator acts on. operators (list(numpy.array) or numpy.array): A list of operators, in matrix form. acting_on (list(numpy.array) or numpy.array): A list of sites, which the corresponding operators act on. constant (float): Level shift for operator. Default is 0.0. Examples: Constructs a ``LocalOperator`` without any operators. >>> from netket.hilbert import CustomHilbert >>> from netket.operator import LocalOperator >>> hi = CustomHilbert(local_states=[-1, 1])**20 >>> empty_hat = LocalOperator(hi) >>> print(len(empty_hat.acting_on)) 0
r""" Constructs a new ``LocalOperator`` given a hilbert space and (if specified) a constant level shift.
[ "r", "Constructs", "a", "new", "LocalOperator", "given", "a", "hilbert", "space", "and", "(", "if", "specified", ")", "a", "constant", "level", "shift", "." ]
def __init__( self, hilbert: AbstractHilbert, operators: Union[List[Array], Array] = [], acting_on: Union[List[int], List[List[int]]] = [], constant: numbers.Number = 0, dtype: Optional[DType] = None, ): r""" Constructs a new ``LocalOperator`` given a hilbert space and (if specified) a constant level shift. Args: hilbert (netket.AbstractHilbert): Hilbert space the operator acts on. operators (list(numpy.array) or numpy.array): A list of operators, in matrix form. acting_on (list(numpy.array) or numpy.array): A list of sites, which the corresponding operators act on. constant (float): Level shift for operator. Default is 0.0. Examples: Constructs a ``LocalOperator`` without any operators. >>> from netket.hilbert import CustomHilbert >>> from netket.operator import LocalOperator >>> hi = CustomHilbert(local_states=[-1, 1])**20 >>> empty_hat = LocalOperator(hi) >>> print(len(empty_hat.acting_on)) 0 """ super().__init__(hilbert) self._constant = constant if not all( [_is_sorted(hilbert.states_at_index(i)) for i in range(hilbert.size)] ): raise ValueError( dedent( """LocalOperator needs an hilbert space with sorted state values at every site. """ ) ) # check if passing a single operator or a list of operators if isinstance(acting_on, numbers.Number): acting_on = [acting_on] is_nested = any(hasattr(i, "__len__") for i in acting_on) if not is_nested: operators = [operators] acting_on = [acting_on] operators = [np.asarray(operator) for operator in operators] # If we asked for a specific dtype, enforce it. if dtype is None: dtype = functools.reduce( lambda dt, op: np.promote_types(dt, op.dtype), operators, np.float32 ) self._dtype = dtype self._init_zero() self.mel_cutoff = 1.0e-6 self._nonzero_diagonal = np.abs(self._constant) >= self.mel_cutoff """True if at least one element in the diagonal of the operator is nonzero""" for op, act in zip(operators, acting_on): if len(act) > 0: self._add_operator(op, act)
[ "def", "__init__", "(", "self", ",", "hilbert", ":", "AbstractHilbert", ",", "operators", ":", "Union", "[", "List", "[", "Array", "]", ",", "Array", "]", "=", "[", "]", ",", "acting_on", ":", "Union", "[", "List", "[", "int", "]", ",", "List", "["...
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/operator/_local_operator.py#L202-L273
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/data_flow_ops.py
python
QueueBase._scope_vals
(self, vals)
Return a list of values to pass to `name_scope()`. Args: vals: A tensor, a list or tuple of tensors, or a dictionary. Returns: The values in vals as a list.
Return a list of values to pass to `name_scope()`.
[ "Return", "a", "list", "of", "values", "to", "pass", "to", "name_scope", "()", "." ]
def _scope_vals(self, vals): """Return a list of values to pass to `name_scope()`. Args: vals: A tensor, a list or tuple of tensors, or a dictionary. Returns: The values in vals as a list. """ if isinstance(vals, (list, tuple)): return vals elif isinstance(vals, dict): return vals.values() else: return [vals]
[ "def", "_scope_vals", "(", "self", ",", "vals", ")", ":", "if", "isinstance", "(", "vals", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "vals", "elif", "isinstance", "(", "vals", ",", "dict", ")", ":", "return", "vals", ".", "values", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_ops.py#L271-L285
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py
python
_PropertyName
(proto_field_name)
return proto_field_name
Returns the name of the public property attribute which clients can use to get and (in some cases) set the value of a protocol message field. Args: proto_field_name: The protocol message field name, exactly as it appears (or would appear) in a .proto file.
Returns the name of the public property attribute which clients can use to get and (in some cases) set the value of a protocol message field.
[ "Returns", "the", "name", "of", "the", "public", "property", "attribute", "which", "clients", "can", "use", "to", "get", "and", "(", "in", "some", "cases", ")", "set", "the", "value", "of", "a", "protocol", "message", "field", "." ]
def _PropertyName(proto_field_name): """Returns the name of the public property attribute which clients can use to get and (in some cases) set the value of a protocol message field. Args: proto_field_name: The protocol message field name, exactly as it appears (or would appear) in a .proto file. """ # TODO(robinson): Escape Python keywords (e.g., yield), and test this support. # nnorwitz makes my day by writing: # """ # FYI. See the keyword module in the stdlib. This could be as simple as: # # if keyword.iskeyword(proto_field_name): # return proto_field_name + "_" # return proto_field_name # """ # Kenton says: The above is a BAD IDEA. People rely on being able to use # getattr() and setattr() to reflectively manipulate field values. If we # rename the properties, then every such user has to also make sure to apply # the same transformation. Note that currently if you name a field "yield", # you can still access it just fine using getattr/setattr -- it's not even # that cumbersome to do so. # TODO(kenton): Remove this method entirely if/when everyone agrees with my # position. return proto_field_name
[ "def", "_PropertyName", "(", "proto_field_name", ")", ":", "# TODO(robinson): Escape Python keywords (e.g., yield), and test this support.", "# nnorwitz makes my day by writing:", "# \"\"\"", "# FYI. See the keyword module in the stdlib. This could be as simple as:", "#", "# if keyword.iskeyw...
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/google/protobuf/internal/python_message.py#L109-L135
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/path.py/path.py
python
Path.relpath
(self, start='.')
return cwd.relpathto(self)
Return this path as a relative path, based from `start`, which defaults to the current working directory.
Return this path as a relative path, based from `start`, which defaults to the current working directory.
[ "Return", "this", "path", "as", "a", "relative", "path", "based", "from", "start", "which", "defaults", "to", "the", "current", "working", "directory", "." ]
def relpath(self, start='.'): """ Return this path as a relative path, based from `start`, which defaults to the current working directory. """ cwd = self._next_class(start) return cwd.relpathto(self)
[ "def", "relpath", "(", "self", ",", "start", "=", "'.'", ")", ":", "cwd", "=", "self", ".", "_next_class", "(", "start", ")", "return", "cwd", ".", "relpathto", "(", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/path.py/path.py#L467-L472
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/optimize/nonlin.py
python
LowRankMatrix.solve
(self, v, tol=0)
return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds)
Evaluate w = M^-1 v
Evaluate w = M^-1 v
[ "Evaluate", "w", "=", "M^", "-", "1", "v" ]
def solve(self, v, tol=0): """Evaluate w = M^-1 v""" if self.collapsed is not None: return solve(self.collapsed, v) return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds)
[ "def", "solve", "(", "self", ",", "v", ",", "tol", "=", "0", ")", ":", "if", "self", ".", "collapsed", "is", "not", "None", ":", "return", "solve", "(", "self", ".", "collapsed", ",", "v", ")", "return", "LowRankMatrix", ".", "_solve", "(", "v", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/nonlin.py#L760-L764
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/HeppyCore/python/utils/eostools.py
python
fileExists
( path )
return result
Returns true if path is a file or directory stored locally, or on EOS. This function checks for the file or directory existence.
Returns true if path is a file or directory stored locally, or on EOS.
[ "Returns", "true", "if", "path", "is", "a", "file", "or", "directory", "stored", "locally", "or", "on", "EOS", "." ]
def fileExists( path ): """Returns true if path is a file or directory stored locally, or on EOS. This function checks for the file or directory existence.""" eos = isEOSDir(path) result = False if eos: # print 'eos', path result = isEOSFile(path) else: # print 'not eos', path #check locally result = os.path.exists(path) # print result return result
[ "def", "fileExists", "(", "path", ")", ":", "eos", "=", "isEOSDir", "(", "path", ")", "result", "=", "False", "if", "eos", ":", "# print 'eos', path", "result", "=", "isEOSFile", "(", "path", ")", "else", ":", "# print 'not eos', path", "#check locally", "re...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/HeppyCore/python/utils/eostools.py#L198-L213
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/examples/surface_chemistry/sofc.py
python
show_coverages
(s)
Print the coverages for surface s.
Print the coverages for surface s.
[ "Print", "the", "coverages", "for", "surface", "s", "." ]
def show_coverages(s): """Print the coverages for surface s.""" print('\n{0}\n'.format(s.name)) cov = s.coverages names = s.species_names for n in range(s.n_species): print('{0:16s} {1:13.4g}'.format(names[n], cov[n]))
[ "def", "show_coverages", "(", "s", ")", ":", "print", "(", "'\\n{0}\\n'", ".", "format", "(", "s", ".", "name", ")", ")", "cov", "=", "s", ".", "coverages", "names", "=", "s", ".", "species_names", "for", "n", "in", "range", "(", "s", ".", "n_speci...
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/examples/surface_chemistry/sofc.py#L46-L52
google/shaka-player-embedded
dabbeb5b47cc257b37b9a254661546352aaf0afe
shaka/tools/idl/exposed_type_generator.py
python
_GetPublicFieldName
(attr)
return re.sub(r'([A-Z])', r'_\1', attr.name).lower()
Converts a lowerCamelCase field name to lower_with_underscores.
Converts a lowerCamelCase field name to lower_with_underscores.
[ "Converts", "a", "lowerCamelCase", "field", "name", "to", "lower_with_underscores", "." ]
def _GetPublicFieldName(attr): """Converts a lowerCamelCase field name to lower_with_underscores.""" return re.sub(r'([A-Z])', r'_\1', attr.name).lower()
[ "def", "_GetPublicFieldName", "(", "attr", ")", ":", "return", "re", ".", "sub", "(", "r'([A-Z])'", ",", "r'_\\1'", ",", "attr", ".", "name", ")", ".", "lower", "(", ")" ]
https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/idl/exposed_type_generator.py#L88-L90
zeakey/DeepSkeleton
dc70170f8fd2ec8ca1157484ce66129981104486
scripts/cpp_lint.py
python
UpdateIncludeState
(filename, include_state, io=codecs)
return True
Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was succesfully added. False otherwise.
Fill up the include_state with new includes found from the file.
[ "Fill", "up", "the", "include_state", "with", "new", "includes", "found", "from", "the", "file", "." ]
def UpdateIncludeState(filename, include_state, io=codecs): """Fill up the include_state with new includes found from the file. Args: filename: the name of the header to read. include_state: an _IncludeState instance in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was succesfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) # The value formatting is cute, but not really used right now. # What matters here is that the key is in include_state. include_state.setdefault(include, '%s:%d' % (filename, linenum)) return True
[ "def", "UpdateIncludeState", "(", "filename", ",", "include_state", ",", "io", "=", "codecs", ")", ":", "headerfile", "=", "None", "try", ":", "headerfile", "=", "io", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", "excep...
https://github.com/zeakey/DeepSkeleton/blob/dc70170f8fd2ec8ca1157484ce66129981104486/scripts/cpp_lint.py#L4454-L4480
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
Dialog.GetAffirmativeId
(*args, **kwargs)
return _windows_.Dialog_GetAffirmativeId(*args, **kwargs)
GetAffirmativeId(self) -> int
GetAffirmativeId(self) -> int
[ "GetAffirmativeId", "(", "self", ")", "-", ">", "int" ]
def GetAffirmativeId(*args, **kwargs): """GetAffirmativeId(self) -> int""" return _windows_.Dialog_GetAffirmativeId(*args, **kwargs)
[ "def", "GetAffirmativeId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "Dialog_GetAffirmativeId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L757-L759
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/linear.py
python
LinearRegressor.__init__
(self, feature_columns=None, model_dir=None, weight_column_name=None, optimizer=None, gradient_clip_norm=None, enable_centered_bias=True, target_dimension=1, config=None)
Construct a `LinearRegressor` estimator object. Args: feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph, etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `tf.Optimizer` used to train the model. If `None`, will use an Ftrl optimizer. gradient_clip_norm: A `float` > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See `tf.clip_by_global_norm` for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. target_dimension: dimension of the target for multilabels. config: `RunConfig` object to configure the runtime settings. Returns: A `LinearRegressor` estimator.
Construct a `LinearRegressor` estimator object.
[ "Construct", "a", "LinearRegressor", "estimator", "object", "." ]
def __init__(self, feature_columns=None, model_dir=None, weight_column_name=None, optimizer=None, gradient_clip_norm=None, enable_centered_bias=True, target_dimension=1, config=None): """Construct a `LinearRegressor` estimator object. Args: feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph, etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `tf.Optimizer` used to train the model. If `None`, will use an Ftrl optimizer. gradient_clip_norm: A `float` > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See `tf.clip_by_global_norm` for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. target_dimension: dimension of the target for multilabels. config: `RunConfig` object to configure the runtime settings. Returns: A `LinearRegressor` estimator. """ _changing(feature_columns) super(LinearRegressor, self).__init__( model_dir=model_dir, weight_column_name=weight_column_name, linear_feature_columns=feature_columns, linear_optimizer=optimizer, gradient_clip_norm=gradient_clip_norm, enable_centered_bias=enable_centered_bias, target_dimension=target_dimension, config=config) self._feature_columns_inferred = False
[ "def", "__init__", "(", "self", ",", "feature_columns", "=", "None", ",", "model_dir", "=", "None", ",", "weight_column_name", "=", "None", ",", "optimizer", "=", "None", ",", "gradient_clip_norm", "=", "None", ",", "enable_centered_bias", "=", "True", ",", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/linear.py#L270-L315
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2B_TIMEOUT.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2B_TIMEOUT)
Returns new TPM2B_TIMEOUT object constructed from its marshaled representation in the given byte buffer
Returns new TPM2B_TIMEOUT object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2B_TIMEOUT", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2B_TIMEOUT object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2B_TIMEOUT)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2B_TIMEOUT", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L3946-L3950
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/algorithm_detail/mask_workspace.py
python
mask_spectra
(mask_info, workspace, spectra_block, detector_type)
return workspace
Masks particular spectra on the workspace. There are several spectra specifications which need to be evaluated 1. General singular spectrum numbers 2. General spectrum ranges 3. Detector-specific horizontal singular strips 4. Detector-specific horizontal range strips 5. Detector-specific vertical singular strips 6. Detector-specific vertical range strips 7. Blocks 8. Cross Blocks :param mask_info: a SANSStateMask object. :param workspace: the workspace to be masked. :param spectra_block: a SpectraBlock object, which contains instrument information to calculate the selected spectra. :param detector_type: the selected detector type :return: the masked workspace.
Masks particular spectra on the workspace.
[ "Masks", "particular", "spectra", "on", "the", "workspace", "." ]
def mask_spectra(mask_info, workspace, spectra_block, detector_type): """ Masks particular spectra on the workspace. There are several spectra specifications which need to be evaluated 1. General singular spectrum numbers 2. General spectrum ranges 3. Detector-specific horizontal singular strips 4. Detector-specific horizontal range strips 5. Detector-specific vertical singular strips 6. Detector-specific vertical range strips 7. Blocks 8. Cross Blocks :param mask_info: a SANSStateMask object. :param workspace: the workspace to be masked. :param spectra_block: a SpectraBlock object, which contains instrument information to calculate the selected spectra. :param detector_type: the selected detector type :return: the masked workspace. """ total_spectra = [] # All masks are detector-specific, hence we pull out only the relevant part detector = mask_info.detectors[detector_type.value] # ---------------------- # Single spectra # ----------------------- single_spectra = detector.single_spectra if single_spectra: total_spectra.extend(single_spectra) # ---------------------- # Spectrum range # ----------------------- spectrum_range_start = detector.spectrum_range_start spectrum_range_stop = detector.spectrum_range_stop if spectrum_range_start and spectrum_range_stop: for start, stop in zip(spectrum_range_start, spectrum_range_stop): total_spectra.extend(list(range(start, stop + 1))) # --------------------------- # Horizontal single spectrum # --------------------------- single_horizontal_strip_masks = detector.single_horizontal_strip_mask if single_horizontal_strip_masks: for single_horizontal_strip_mask in single_horizontal_strip_masks: total_spectra.extend(spectra_block.get_block(single_horizontal_strip_mask, 0, 1, None)) # --------------------------- # Vertical single spectrum # --------------------------- single_vertical_strip_masks = detector.single_vertical_strip_mask if single_vertical_strip_masks: for single_vertical_strip_mask in single_vertical_strip_masks: total_spectra.extend(spectra_block.get_block(0, single_vertical_strip_mask, None, 1)) # --------------------------- # Horizontal spectrum range # --------------------------- range_horizontal_strip_start = detector.range_horizontal_strip_start range_horizontal_strip_stop = detector.range_horizontal_strip_stop if range_horizontal_strip_start and range_horizontal_strip_stop: for start, stop in zip(range_horizontal_strip_start, range_horizontal_strip_stop): number_of_strips = abs(stop - start) + 1 total_spectra.extend(spectra_block.get_block(start, 0, number_of_strips, None)) # --------------------------- # Vertical spectrum range # --------------------------- range_vertical_strip_start = detector.range_vertical_strip_start range_vertical_strip_stop = detector.range_vertical_strip_stop if range_vertical_strip_start and range_vertical_strip_stop: for start, stop in zip(range_vertical_strip_start, range_vertical_strip_stop): number_of_strips = abs(stop - start) + 1 total_spectra.extend(spectra_block.get_block(0, start, None, number_of_strips)) # --------------------------- # Blocks # --------------------------- block_horizontal_start = detector.block_horizontal_start block_horizontal_stop = detector.block_horizontal_stop block_vertical_start = detector.block_vertical_start block_vertical_stop = detector.block_vertical_stop if block_horizontal_start and block_horizontal_stop and block_vertical_start and block_vertical_stop: for h_start, h_stop, v_start, v_stop in zip(block_horizontal_start, block_horizontal_stop, block_vertical_start, block_vertical_stop): x_dim = abs(v_stop - v_start) + 1 y_dim = abs(h_stop - h_start) + 1 total_spectra.extend(spectra_block.get_block(h_start, v_start, y_dim, x_dim)) # --------------------------- # Blocks Cross # --------------------------- block_cross_horizontal = detector.block_cross_horizontal block_cross_vertical = detector.block_cross_vertical if block_cross_horizontal and block_cross_vertical: for horizontal, vertical in zip(block_cross_horizontal, block_cross_vertical): total_spectra.extend(spectra_block.get_block(horizontal, vertical, 1, 1)) if not total_spectra: return workspace # Perform the masking ws_spectra_list = workspace.getSpectrumNumbers() # Any gaps in the spectra list we skip over attempting to mask filtered_mask_spectra = [spec for spec in total_spectra if spec in ws_spectra_list] if len(filtered_mask_spectra) != len(total_spectra): log = Logger("SANS - Mask Workspace") log.warning("Skipped masking some spectrum numbers that do not exist in the workspace. Re-run" " with logging set to information for more details") log.information("The following spectrum numbers do not exist in the ws (cropped to component):") for i in list(set(total_spectra) - set(filtered_mask_spectra)): log.information(str(i)) mask_name = "MaskSpectra" mask_options = {"InputWorkspace": workspace, "InputWorkspaceIndexType": "SpectrumNumber", "OutputWorkspace": "__dummy"} mask_alg = create_unmanaged_algorithm(mask_name, **mask_options) mask_alg.setProperty("InputWorkspaceIndexSet", list(set(filtered_mask_spectra))) mask_alg.setProperty("OutputWorkspace", workspace) mask_alg.execute() workspace = mask_alg.getProperty("OutputWorkspace").value return workspace
[ "def", "mask_spectra", "(", "mask_info", ",", "workspace", ",", "spectra_block", ",", "detector_type", ")", ":", "total_spectra", "=", "[", "]", "# All masks are detector-specific, hence we pull out only the relevant part", "detector", "=", "mask_info", ".", "detectors", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/mask_workspace.py#L157-L285
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
Contrib/FreeWilson/freewilson.py
python
FWDecompose
(scaffolds, mols, scores, decomp_params=default_decomp_params)
return FreeWilsonDecomposition(rgroups, rgroup_idx, lm, r2, descriptors)
Perform a free wilson analysis : param scaffolds : scaffold or list of scaffolds to use for the rgroup decomposition : param mols : molecules to decompose : param scores : list of floating point numbers for the regression ( you may need convert these to their logs in some cases) : param decomp_params : RgroupDecompositionParams default [ default_decomp_params = rdkit.Chem.rdRGroupDecomposition.RGroupDecompositionParameters() default_decomp_params.matchingStrategy = rgd.GA default_decomp_params.onlyMatchAtRGroups = False ] If you only want to decompose on specific group locations set onlyMatchAtRGroups to True >>> from rdkit import Chem >>> from freewilson import FWBuild, FWDecompose >>> from rdkit.Chem import Descriptors >>> scaffold = Chem.MolFromSmiles("c1cccnc1") >>> mols = [Chem.MolFromSmiles("c1cccnc1"+"C"*(i+1)) for i in range(100)] >>> scores = [Descriptors.MolLogP(m) for m in mols] >>> fw = FWDecompose(scaffold, mols, scores) >>> for pred in FWBuild(fw): ... print(pred) For an easy way to report predictions see >>> import sys >>> predictions_to_csv(sys.stdout, fw, FWBuild(fw)) See FWBuild docs to see how to filter predictions, molecular weight or molecular properties.
Perform a free wilson analysis : param scaffolds : scaffold or list of scaffolds to use for the rgroup decomposition : param mols : molecules to decompose : param scores : list of floating point numbers for the regression ( you may need convert these to their logs in some cases) : param decomp_params : RgroupDecompositionParams default [ default_decomp_params = rdkit.Chem.rdRGroupDecomposition.RGroupDecompositionParameters() default_decomp_params.matchingStrategy = rgd.GA default_decomp_params.onlyMatchAtRGroups = False ] If you only want to decompose on specific group locations set onlyMatchAtRGroups to True
[ "Perform", "a", "free", "wilson", "analysis", ":", "param", "scaffolds", ":", "scaffold", "or", "list", "of", "scaffolds", "to", "use", "for", "the", "rgroup", "decomposition", ":", "param", "mols", ":", "molecules", "to", "decompose", ":", "param", "scores"...
def FWDecompose(scaffolds, mols, scores, decomp_params=default_decomp_params) -> FreeWilsonDecomposition: """ Perform a free wilson analysis : param scaffolds : scaffold or list of scaffolds to use for the rgroup decomposition : param mols : molecules to decompose : param scores : list of floating point numbers for the regression ( you may need convert these to their logs in some cases) : param decomp_params : RgroupDecompositionParams default [ default_decomp_params = rdkit.Chem.rdRGroupDecomposition.RGroupDecompositionParameters() default_decomp_params.matchingStrategy = rgd.GA default_decomp_params.onlyMatchAtRGroups = False ] If you only want to decompose on specific group locations set onlyMatchAtRGroups to True >>> from rdkit import Chem >>> from freewilson import FWBuild, FWDecompose >>> from rdkit.Chem import Descriptors >>> scaffold = Chem.MolFromSmiles("c1cccnc1") >>> mols = [Chem.MolFromSmiles("c1cccnc1"+"C"*(i+1)) for i in range(100)] >>> scores = [Descriptors.MolLogP(m) for m in mols] >>> fw = FWDecompose(scaffold, mols, scores) >>> for pred in FWBuild(fw): ... print(pred) For an easy way to report predictions see >>> import sys >>> predictions_to_csv(sys.stdout, fw, FWBuild(fw)) See FWBuild docs to see how to filter predictions, molecular weight or molecular properties. """ descriptors = [] # list of descriptors, one per matched molecules # descriptors are 1/0 if a sidechain is present matched_scores = [] # scores from the matching molecules rgroup_idx = {} # rgroup index into descriptor { smiles: idx } rgroups = defaultdict(list) # final list of rgrups/sidechains if len(mols) != len(scores): raise ValueError(f"The number of molecules must match the number of scores #mols {len(mols)} #scores {len(scores)}") # decompose the rgroups logger.info(f"Decomposing {len(mols)} molecules...") decomposer = rgd.RGroupDecomposition(scaffolds, decomp_params) for mol, score in tqdm(zip(mols, scores)): if decomposer.Add(mol) >= 0: matched_scores.append(score) decomposer.Process() logger.info(f"Matched {len(matched_scores)} out of {len(mols)}") if not(matched_scores): logger.error("No scaffolds matched the input molecules") return decomposition = decomposition = decomposer.GetRGroupsAsRows(asSmiles=True) logger.info("Get unique rgroups...") rgroup_counts = defaultdict(int) for row in decomposition: for rgroup,smiles in row.items(): rgroup_counts[smiles] += 1 if smiles not in rgroup_idx: rgroup_idx[smiles] = len(rgroup_idx) rgroups[rgroup].append(RGroup(smiles, rgroup, 0, 0)) logger.info(f"Descriptor size {len(rgroup_idx)}") # get the descriptors list, one-hot encoding per rgroup for row in decomposition: descriptor = [0] * len(rgroup_idx) descriptors.append(descriptor) for smiles in row.values(): if smiles in rgroup_idx: descriptor[rgroup_idx[smiles]] = 1 assert len(descriptors) == len(matched_scores), f"Number of descriptors({len(descriptors)}) doesn't match number of matcved scores({len(matched_scores)})" # Perform the Ridge Regression logger.info("Ridge Regressing...") lm = Ridge() lm.fit(descriptors, matched_scores) preds = lm.predict(descriptors) r2 = r2_score(matched_scores, preds) logger.info(f"R2 {r2}") logger.info(f"Intercept = {lm.intercept_:.2f}") for sidechains in rgroups.values(): for rgroup in sidechains: rgroup.count = rgroup_counts[rgroup.smiles] rgroup.coefficient = lm.coef_[rgroup_idx[rgroup.smiles]] rgroup.idx = rgroup_idx[rgroup.smiles] return FreeWilsonDecomposition(rgroups, rgroup_idx, lm, r2, descriptors)
[ "def", "FWDecompose", "(", "scaffolds", ",", "mols", ",", "scores", ",", "decomp_params", "=", "default_decomp_params", ")", "->", "FreeWilsonDecomposition", ":", "descriptors", "=", "[", "]", "# list of descriptors, one per matched molecules", "# descriptors are 1/0 if ...
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/Contrib/FreeWilson/freewilson.py#L241-L331
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_grad.py
python
_ResizeBicubicGrad
(op, grad)
return [grad0, None]
The derivatives for bicubic resizing. Args: op: The ResizeBicubic op. grad: The tensor representing the gradient w.r.t. the output. Returns: The gradients w.r.t. the input.
The derivatives for bicubic resizing.
[ "The", "derivatives", "for", "bicubic", "resizing", "." ]
def _ResizeBicubicGrad(op, grad): """The derivatives for bicubic resizing. Args: op: The ResizeBicubic op. grad: The tensor representing the gradient w.r.t. the output. Returns: The gradients w.r.t. the input. """ allowed_types = [dtypes.float32, dtypes.float64] grad0 = None if op.inputs[0].dtype in allowed_types: grad0 = gen_image_ops.resize_bicubic_grad( grad, op.inputs[0], align_corners=op.get_attr("align_corners"), half_pixel_centers=op.get_attr("half_pixel_centers")) return [grad0, None]
[ "def", "_ResizeBicubicGrad", "(", "op", ",", "grad", ")", ":", "allowed_types", "=", "[", "dtypes", ".", "float32", ",", "dtypes", ".", "float64", "]", "grad0", "=", "None", "if", "op", ".", "inputs", "[", "0", "]", ".", "dtype", "in", "allowed_types",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_grad.py#L95-L113
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
cmake/tribits/doc/sphinx/sphinx_rst_generator.py
python
SphinxRstGenerator.create_rst_dir
(self)
Creates copied_files directory in Sphinx directory. All include files will be copy there.
Creates copied_files directory in Sphinx directory. All include files will be copy there.
[ "Creates", "copied_files", "directory", "in", "Sphinx", "directory", ".", "All", "include", "files", "will", "be", "copy", "there", "." ]
def create_rst_dir(self) -> None: """ Creates copied_files directory in Sphinx directory. All include files will be copy there. """ if self.rst_dir is not None: if not os.path.exists(self.rst_dir): os.makedirs(self.rst_dir)
[ "def", "create_rst_dir", "(", "self", ")", "->", "None", ":", "if", "self", ".", "rst_dir", "is", "not", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "rst_dir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "...
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/cmake/tribits/doc/sphinx/sphinx_rst_generator.py#L98-L104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItemData.GetWidth
(self)
return self._rect.width
Returns the item width, in pixels.
Returns the item width, in pixels.
[ "Returns", "the", "item", "width", "in", "pixels", "." ]
def GetWidth(self): """ Returns the item width, in pixels. """ return self._rect.width
[ "def", "GetWidth", "(", "self", ")", ":", "return", "self", ".", "_rect", ".", "width" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L3106-L3109
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
packages/Python/lldbsuite/support/seven.py
python
unhexlify
(hexstr)
return bitcast_to_string(binascii.unhexlify(hexstr))
Hex-decode a string. The result is always a string.
Hex-decode a string. The result is always a string.
[ "Hex", "-", "decode", "a", "string", ".", "The", "result", "is", "always", "a", "string", "." ]
def unhexlify(hexstr): """Hex-decode a string. The result is always a string.""" return bitcast_to_string(binascii.unhexlify(hexstr))
[ "def", "unhexlify", "(", "hexstr", ")", ":", "return", "bitcast_to_string", "(", "binascii", ".", "unhexlify", "(", "hexstr", ")", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/packages/Python/lldbsuite/support/seven.py#L45-L47
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/inspect.py
python
getinnerframes
(tb, context=1)
return framelist
Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.
Get a list of records for a traceback's frame and all lower frames.
[ "Get", "a", "list", "of", "records", "for", "a", "traceback", "s", "frame", "and", "all", "lower", "frames", "." ]
def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) tb = tb.tb_next return framelist
[ "def", "getinnerframes", "(", "tb", ",", "context", "=", "1", ")", ":", "framelist", "=", "[", "]", "while", "tb", ":", "framelist", ".", "append", "(", "(", "tb", ".", "tb_frame", ",", ")", "+", "getframeinfo", "(", "tb", ",", "context", ")", ")",...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/inspect.py#L1036-L1045
kevin-ssy/Optical-Flow-Guided-Feature
07d4501a29002ee7821c38c1820e4a64c1acf6e8
lib/caffe-action/scripts/cpp_lint.py
python
_NestingState.SeenOpenBrace
(self)
return (not self.stack) or self.stack[-1].seen_open_brace
Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace.
Check if we have seen the opening brace for the innermost block.
[ "Check", "if", "we", "have", "seen", "the", "opening", "brace", "for", "the", "innermost", "block", "." ]
def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace
[ "def", "SeenOpenBrace", "(", "self", ")", ":", "return", "(", "not", "self", ".", "stack", ")", "or", "self", ".", "stack", "[", "-", "1", "]", ".", "seen_open_brace" ]
https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/scripts/cpp_lint.py#L1931-L1938
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/xml/sax/xmlreader.py
python
InputSource.setByteStream
(self, bytefile)
Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.
Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source.
[ "Set", "the", "byte", "stream", "(", "a", "Python", "file", "-", "like", "object", "which", "does", "not", "perform", "byte", "-", "to", "-", "character", "conversion", ")", "for", "this", "input", "source", "." ]
def setByteStream(self, bytefile): """Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.""" self.__bytefile = bytefile
[ "def", "setByteStream", "(", "self", ",", "bytefile", ")", ":", "self", ".", "__bytefile", "=", "bytefile" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/xml/sax/xmlreader.py#L240-L251
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py
python
classname
(object, modname)
return name
Get a class name and qualify it with a module name if necessary.
Get a class name and qualify it with a module name if necessary.
[ "Get", "a", "class", "name", "and", "qualify", "it", "with", "a", "module", "name", "if", "necessary", "." ]
def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" name = object.__name__ if object.__module__ != modname: name = object.__module__ + '.' + name return name
[ "def", "classname", "(", "object", ",", "modname", ")", ":", "name", "=", "object", ".", "__name__", "if", "object", ".", "__module__", "!=", "modname", ":", "name", "=", "object", ".", "__module__", "+", "'.'", "+", "name", "return", "name" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py#L107-L112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/ssl_support.py
python
opener_for
(ca_bundle=None)
return urllib.request.build_opener( VerifyingHTTPSHandler(ca_bundle or find_ca_bundle()) ).open
Get a urlopen() replacement that uses ca_bundle for verification
Get a urlopen() replacement that uses ca_bundle for verification
[ "Get", "a", "urlopen", "()", "replacement", "that", "uses", "ca_bundle", "for", "verification" ]
def opener_for(ca_bundle=None): """Get a urlopen() replacement that uses ca_bundle for verification""" return urllib.request.build_opener( VerifyingHTTPSHandler(ca_bundle or find_ca_bundle()) ).open
[ "def", "opener_for", "(", "ca_bundle", "=", "None", ")", ":", "return", "urllib", ".", "request", ".", "build_opener", "(", "VerifyingHTTPSHandler", "(", "ca_bundle", "or", "find_ca_bundle", "(", ")", ")", ")", ".", "open" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/ssl_support.py#L210-L214
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/arrayprint.py
python
_make_options_dict
(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, sign=None, formatter=None, floatmode=None, legacy=None)
return options
make a dictionary out of the non-None arguments, plus sanity checks
make a dictionary out of the non-None arguments, plus sanity checks
[ "make", "a", "dictionary", "out", "of", "the", "non", "-", "None", "arguments", "plus", "sanity", "checks" ]
def _make_options_dict(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, sign=None, formatter=None, floatmode=None, legacy=None): """ make a dictionary out of the non-None arguments, plus sanity checks """ options = {k: v for k, v in locals().items() if v is not None} if suppress is not None: options['suppress'] = bool(suppress) modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal'] if floatmode not in modes + [None]: raise ValueError("floatmode option must be one of " + ", ".join('"{}"'.format(m) for m in modes)) if sign not in [None, '-', '+', ' ']: raise ValueError("sign option must be one of ' ', '+', or '-'") if legacy not in [None, False, '1.13']: warnings.warn("legacy printing option can currently only be '1.13' or " "`False`", stacklevel=3) if threshold is not None: # forbid the bad threshold arg suggested by stack overflow, gh-12351 if not isinstance(threshold, numbers.Number): raise TypeError("threshold must be numeric") if np.isnan(threshold): raise ValueError("threshold must be non-NAN, try " "sys.maxsize for untruncated representation") return options
[ "def", "_make_options_dict", "(", "precision", "=", "None", ",", "threshold", "=", "None", ",", "edgeitems", "=", "None", ",", "linewidth", "=", "None", ",", "suppress", "=", "None", ",", "nanstr", "=", "None", ",", "infstr", "=", "None", ",", "sign", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/arrayprint.py#L69-L97
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/middle/passes/fusing/decomposition.py
python
convert_batch_norm
(graph: Graph)
This function finds FusedBatchNorm layer (or BatchNorm for MXNet) and replaces with Mul->Add->Mul->Add sequence.
This function finds FusedBatchNorm layer (or BatchNorm for MXNet) and replaces with Mul->Add->Mul->Add sequence.
[ "This", "function", "finds", "FusedBatchNorm", "layer", "(", "or", "BatchNorm", "for", "MXNet", ")", "and", "replaces", "with", "Mul", "-", ">", "Add", "-", ">", "Mul", "-", ">", "Add", "sequence", "." ]
def convert_batch_norm(graph: Graph): """ This function finds FusedBatchNorm layer (or BatchNorm for MXNet) and replaces with Mul->Add->Mul->Add sequence. """ nodes = graph.get_op_nodes() for node in nodes: if node.has_valid('op') and (node.op in ['FusedBatchNorm', 'FusedBatchNormV2', 'FusedBatchNormV3', 'BatchNorm', 'BatchNormalization', 'batchNormInference']): if any([node.in_port(i).data.get_value() is None for i in range(1, len(node.in_ports()))]): log.warning('Cannot translate FusedBatchNorm {} node with non-constant weights'.format( node.name if node.has_valid('name') else '<UNKNOWN>')) continue const = node.in_port(1).get_source() node.in_port(1).disconnect() beta = node.in_port(2).get_source() node.in_port(2).disconnect() mean = node.in_port(3).get_source() node.in_port(3).disconnect() variance = node.in_port(4).get_source() node.in_port(4).disconnect() eps = node.eps if node.has_valid('fix_gamma') and node.fix_gamma: const.data.get_value().fill(1.) can_be_fused = False if not node.soft_get('can_be_fused') else True scale = 1. / np.sqrt(variance.data.get_value() + eps) shift = (mean.data.get_value() * (-1)) * scale # Expand dims for current layout broadcast_dims_cnt = len(node.in_port(0).data.get_shape()) - 2 if graph.graph['layout'] == 'NCHW' else 0 # Update values and shapes with new shape expand_node_shape(const, broadcast_dims_cnt) expand_node_shape(beta, broadcast_dims_cnt) for idx in range(broadcast_dims_cnt): scale = np.expand_dims(scale, axis=-1) shift = np.expand_dims(shift, axis=-1) _fused_batch_norm_decomposition(graph, node.in_port(0), node.out_port(0), const, beta, scale, shift, can_be_fused)
[ "def", "convert_batch_norm", "(", "graph", ":", "Graph", ")", ":", "nodes", "=", "graph", ".", "get_op_nodes", "(", ")", "for", "node", "in", "nodes", ":", "if", "node", ".", "has_valid", "(", "'op'", ")", "and", "(", "node", ".", "op", "in", "[", ...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/middle/passes/fusing/decomposition.py#L24-L71
anestisb/oatdump_plus
ba858c1596598f0d9ae79c14d08c708cecc50af3
tools/cpplint.py
python
CheckSectionSpacing
(filename, clean_lines, class_info, linenum, error)
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for additional blank line issues related to sections.
[ "Checks", "for", "additional", "blank", "line", "issues", "related", "to", "sections", "." ]
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1))
[ "def", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "class_info", ",", "linenum", ",", "error", ")", ":", "# Skip checks if the class is small, where small means 25 lines or less.", "# 25 lines seems like a good cutoff since that's the usual height of", "# termina...
https://github.com/anestisb/oatdump_plus/blob/ba858c1596598f0d9ae79c14d08c708cecc50af3/tools/cpplint.py#L2525-L2577
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo._create_gnu_long_header
(cls, name, type, encoding, errors)
return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \ cls._create_payload(name)
Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name.
Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
[ "Return", "a", "GNUTYPE_LONGNAME", "or", "GNUTYPE_LONGLINK", "sequence" ]
def _create_gnu_long_header(cls, name, type, encoding, errors): """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence for name. """ name = name.encode(encoding, errors) + NUL info = {} info["name"] = "././@LongLink" info["type"] = type info["size"] = len(name) info["magic"] = GNU_MAGIC # create extended header + name blocks. return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \ cls._create_payload(name)
[ "def", "_create_gnu_long_header", "(", "cls", ",", "name", ",", "type", ",", "encoding", ",", "errors", ")", ":", "name", "=", "name", ".", "encode", "(", "encoding", ",", "errors", ")", "+", "NUL", "info", "=", "{", "}", "info", "[", "\"name\"", "]"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2303-L2331
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Utilities/Scripts/SlicerWizard/ExtensionWizard.py
python
ExtensionWizard.describe
(self, args)
Generate extension description and write it to :attr:`sys.stdout`. :param args.destination: Location (directory) of the extension to describe. :type args.destination: :class:`str` If something goes wrong, the application displays a suitable error message.
Generate extension description and write it to :attr:`sys.stdout`.
[ "Generate", "extension", "description", "and", "write", "it", "to", ":", "attr", ":", "sys", ".", "stdout", "." ]
def describe(self, args): """Generate extension description and write it to :attr:`sys.stdout`. :param args.destination: Location (directory) of the extension to describe. :type args.destination: :class:`str` If something goes wrong, the application displays a suitable error message. """ try: r = None if args.localExtensionsDir: r = SourceTreeDirectory(args.localExtensionsDir, os.path.relpath(args.destination, args.localExtensionsDir)) else: r = getRepo(args.destination) if r is None: xd = ExtensionDescription(sourcedir=args.destination) else: xd = ExtensionDescription(repo=r) xd.write(sys.stdout) except: die("failed to describe extension: %s" % sys.exc_info()[1])
[ "def", "describe", "(", "self", ",", "args", ")", ":", "try", ":", "r", "=", "None", "if", "args", ".", "localExtensionsDir", ":", "r", "=", "SourceTreeDirectory", "(", "args", ".", "localExtensionsDir", ",", "os", ".", "path", ".", "relpath", "(", "ar...
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Utilities/Scripts/SlicerWizard/ExtensionWizard.py#L143-L170
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py
python
Decimal.is_canonical
(self)
return True
Return True if self is canonical; otherwise return False. Currently, the encoding of a Decimal instance is always canonical, so this method returns True for any Decimal.
Return True if self is canonical; otherwise return False.
[ "Return", "True", "if", "self", "is", "canonical", ";", "otherwise", "return", "False", "." ]
def is_canonical(self): """Return True if self is canonical; otherwise return False. Currently, the encoding of a Decimal instance is always canonical, so this method returns True for any Decimal. """ return True
[ "def", "is_canonical", "(", "self", ")", ":", "return", "True" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L3007-L3013
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/bdb.py
python
Bdb.get_stack
(self, f, t)
return stack, i
Return a list of (frame, lineno) in a stack trace and a size. List starts with original calling frame, if there is one. Size may be number of frames above or below f.
Return a list of (frame, lineno) in a stack trace and a size.
[ "Return", "a", "list", "of", "(", "frame", "lineno", ")", "in", "a", "stack", "trace", "and", "a", "size", "." ]
def get_stack(self, f, t): """Return a list of (frame, lineno) in a stack trace and a size. List starts with original calling frame, if there is one. Size may be number of frames above or below f. """ stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if f is None: i = max(0, len(stack) - 1) return stack, i
[ "def", "get_stack", "(", "self", ",", "f", ",", "t", ")", ":", "stack", "=", "[", "]", "if", "t", "and", "t", ".", "tb_frame", "is", "f", ":", "t", "=", "t", ".", "tb_next", "while", "f", "is", "not", "None", ":", "stack", ".", "append", "(",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/bdb.py#L509-L530
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py
python
simplify_parfor_body_CFG
(blocks)
simplify CFG of body loops in parfors
simplify CFG of body loops in parfors
[ "simplify", "CFG", "of", "body", "loops", "in", "parfors" ]
def simplify_parfor_body_CFG(blocks): """simplify CFG of body loops in parfors""" for block in blocks.values(): for stmt in block.body: if isinstance(stmt, Parfor): parfor = stmt # add dummy return to enable CFG creation # can't use dummy_return_in_loop_body since body changes last_block = parfor.loop_body[max(parfor.loop_body.keys())] scope = last_block.scope loc = ir.Loc("parfors_dummy", -1) const = ir.Var(scope, mk_unique_var("$const"), loc) last_block.body.append(ir.Assign(ir.Const(0, loc), const, loc)) last_block.body.append(ir.Return(const, loc)) parfor.loop_body = simplify_CFG(parfor.loop_body) last_block = parfor.loop_body[max(parfor.loop_body.keys())] last_block.body.pop() # call on body recursively simplify_parfor_body_CFG(parfor.loop_body)
[ "def", "simplify_parfor_body_CFG", "(", "blocks", ")", ":", "for", "block", "in", "blocks", ".", "values", "(", ")", ":", "for", "stmt", "in", "block", ".", "body", ":", "if", "isinstance", "(", "stmt", ",", "Parfor", ")", ":", "parfor", "=", "stmt", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/parfor.py#L3802-L3820
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py
python
Entry.__init__
(self, master=None, widget=None, **kw)
Constructs a Ttk Entry widget with the parent master. STANDARD OPTIONS class, cursor, style, takefocus, xscrollcommand WIDGET-SPECIFIC OPTIONS exportselection, invalidcommand, justify, show, state, textvariable, validate, validatecommand, width VALIDATION MODES none, key, focus, focusin, focusout, all
Constructs a Ttk Entry widget with the parent master.
[ "Constructs", "a", "Ttk", "Entry", "widget", "with", "the", "parent", "master", "." ]
def __init__(self, master=None, widget=None, **kw): """Constructs a Ttk Entry widget with the parent master. STANDARD OPTIONS class, cursor, style, takefocus, xscrollcommand WIDGET-SPECIFIC OPTIONS exportselection, invalidcommand, justify, show, state, textvariable, validate, validatecommand, width VALIDATION MODES none, key, focus, focusin, focusout, all """ Widget.__init__(self, master, widget or "ttk::entry", kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "widget", "=", "None", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "widget", "or", "\"ttk::entry\"", ",", "kw", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py#L650-L666
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py
python
_tensor_gather_helper
(gather_indices, gather_from, batch_size, range_size, gather_shape, name=None)
Helper for gathering the right indices from the tensor. This works by reshaping gather_from to gather_shape (e.g. [-1]) and then gathering from that according to the gather_indices, which are offset by the right amounts in order to preserve the batch order. Args: gather_indices: The tensor indices that we use to gather. gather_from: The tensor that we are gathering from. batch_size: The input batch size. range_size: The number of values in each range. Likely equal to beam_width. gather_shape: What we should reshape gather_from to in order to preserve the correct values. An example is when gather_from is the attention from an AttentionWrapperState with shape [batch_size, beam_width, attention_size]. There, we want to preserve the attention_size elements, so gather_shape is [batch_size * beam_width, -1]. Then, upon reshape, we still have the attention_size as desired. name: The tensor name for set of operations. By default this is 'tensor_gather_helper'. The final output is named 'output'. Returns: output: Gathered tensor of shape tf.shape(gather_from)[:1+len(gather_shape)]
Helper for gathering the right indices from the tensor.
[ "Helper", "for", "gathering", "the", "right", "indices", "from", "the", "tensor", "." ]
def _tensor_gather_helper(gather_indices, gather_from, batch_size, range_size, gather_shape, name=None): """Helper for gathering the right indices from the tensor. This works by reshaping gather_from to gather_shape (e.g. [-1]) and then gathering from that according to the gather_indices, which are offset by the right amounts in order to preserve the batch order. Args: gather_indices: The tensor indices that we use to gather. gather_from: The tensor that we are gathering from. batch_size: The input batch size. range_size: The number of values in each range. Likely equal to beam_width. gather_shape: What we should reshape gather_from to in order to preserve the correct values. An example is when gather_from is the attention from an AttentionWrapperState with shape [batch_size, beam_width, attention_size]. There, we want to preserve the attention_size elements, so gather_shape is [batch_size * beam_width, -1]. Then, upon reshape, we still have the attention_size as desired. name: The tensor name for set of operations. By default this is 'tensor_gather_helper'. The final output is named 'output'. Returns: output: Gathered tensor of shape tf.shape(gather_from)[:1+len(gather_shape)] """ with ops.name_scope(name, "tensor_gather_helper"): range_ = array_ops.expand_dims(math_ops.range(batch_size) * range_size, 1) gather_indices = array_ops.reshape(gather_indices + range_, [-1]) output = array_ops.gather( array_ops.reshape(gather_from, gather_shape), gather_indices) final_shape = array_ops.shape(gather_from)[:1 + len(gather_shape)] static_batch_size = tensor_util.constant_value(batch_size) final_static_shape = (tensor_shape.TensorShape([static_batch_size]) .concatenate( gather_from.shape[1:1 + len(gather_shape)])) output = array_ops.reshape(output, final_shape, name="output") output.set_shape(final_static_shape) return output
[ "def", "_tensor_gather_helper", "(", "gather_indices", ",", "gather_from", ",", "batch_size", ",", "range_size", ",", "gather_shape", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"tensor_gather_helper\"", ")", ":", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/seq2seq/python/ops/beam_search_decoder.py#L771-L808
peterljq/OpenMMD
795d4dd660cf7e537ceb599fdb038c5388b33390
3D Pose Baseline to VMD/src/cameras.py
python
load_cameras
( bpath='cameras.h5', subjects=[1,5,6,7,8,9,11] )
return rcams
Loads the cameras of h36m Args bpath: path to hdf5 file with h36m camera data subjects: List of ints representing the subject IDs for which cameras are requested Returns rcams: dictionary of 4 tuples per subject ID containing its camera parameters for the 4 h36m cams
Loads the cameras of h36m
[ "Loads", "the", "cameras", "of", "h36m" ]
def load_cameras( bpath='cameras.h5', subjects=[1,5,6,7,8,9,11] ): """Loads the cameras of h36m Args bpath: path to hdf5 file with h36m camera data subjects: List of ints representing the subject IDs for which cameras are requested Returns rcams: dictionary of 4 tuples per subject ID containing its camera parameters for the 4 h36m cams """ rcams = {} with h5py.File(bpath,'r') as hf: for s in subjects: for c in range(4): # There are 4 cameras in human3.6m rcams[(s, c+1)] = load_camera_params(hf, 'subject%d/camera%d/{0}' % (s,c+1) ) return rcams
[ "def", "load_cameras", "(", "bpath", "=", "'cameras.h5'", ",", "subjects", "=", "[", "1", ",", "5", ",", "6", ",", "7", ",", "8", ",", "9", ",", "11", "]", ")", ":", "rcams", "=", "{", "}", "with", "h5py", ".", "File", "(", "bpath", ",", "'r'...
https://github.com/peterljq/OpenMMD/blob/795d4dd660cf7e537ceb599fdb038c5388b33390/3D Pose Baseline to VMD/src/cameras.py#L122-L138
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ConfigParser.py
python
RawConfigParser.readfp
(self, fp, filename=None)
Like read() but the argument must be a file-like object. The `fp' argument must have a `readline' method. Optional second argument is the `filename', which if not given, is taken from fp.name. If fp has no `name' attribute, `<???>' is used.
Like read() but the argument must be a file-like object.
[ "Like", "read", "()", "but", "the", "argument", "must", "be", "a", "file", "-", "like", "object", "." ]
def readfp(self, fp, filename=None): """Like read() but the argument must be a file-like object. The `fp' argument must have a `readline' method. Optional second argument is the `filename', which if not given, is taken from fp.name. If fp has no `name' attribute, `<???>' is used. """ if filename is None: try: filename = fp.name except AttributeError: filename = '<???>' self._read(fp, filename)
[ "def", "readfp", "(", "self", ",", "fp", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "try", ":", "filename", "=", "fp", ".", "name", "except", "AttributeError", ":", "filename", "=", "'<???>'", "self", ".", "_read", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ConfigParser.py#L310-L324
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/BatchNormalization.py
python
BatchNormalization.slow_convergence_rate
(self, slow_convergence_rate)
Sets the coefficient for calculating the exponential moving mean and variance.
Sets the coefficient for calculating the exponential moving mean and variance.
[ "Sets", "the", "coefficient", "for", "calculating", "the", "exponential", "moving", "mean", "and", "variance", "." ]
def slow_convergence_rate(self, slow_convergence_rate): """Sets the coefficient for calculating the exponential moving mean and variance. """ if slow_convergence_rate <= 0 or slow_convergence_rate > 1: raise ValueError('The `slow_convergence_rate` must be in (0, 1].') self._internal.set_slow_convergence_rate(float(slow_convergence_rate))
[ "def", "slow_convergence_rate", "(", "self", ",", "slow_convergence_rate", ")", ":", "if", "slow_convergence_rate", "<=", "0", "or", "slow_convergence_rate", ">", "1", ":", "raise", "ValueError", "(", "'The `slow_convergence_rate` must be in (0, 1].'", ")", "self", ".",...
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/BatchNormalization.py#L92-L99
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-local-4.1.0/SCons/Node/__init__.py
python
Node.set_always_build
(self, always_build = 1)
Set the Node's always_build value.
Set the Node's always_build value.
[ "Set", "the", "Node", "s", "always_build", "value", "." ]
def set_always_build(self, always_build = 1): """Set the Node's always_build value.""" self.always_build = always_build
[ "def", "set_always_build", "(", "self", ",", "always_build", "=", "1", ")", ":", "self", ".", "always_build", "=", "always_build" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-local-4.1.0/SCons/Node/__init__.py#L1245-L1247
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
util/py_lib/seqan/dddoc/core.py
python
App.getNextId
(self)
return self.next_id - 1
Returns an identifier. Each id is only returned once.
Returns an identifier.
[ "Returns", "an", "identifier", "." ]
def getNextId(self): """Returns an identifier. Each id is only returned once. """ assert False, "For future use." self.next_id += 1 return self.next_id - 1
[ "def", "getNextId", "(", "self", ")", ":", "assert", "False", ",", "\"For future use.\"", "self", ".", "next_id", "+=", "1", "return", "self", ".", "next_id", "-", "1" ]
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/util/py_lib/seqan/dddoc/core.py#L1026-L1033
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
TypeHandler.WriteClientGLReturnLog
(self, func, file)
Writes the return value logging code.
Writes the return value logging code.
[ "Writes", "the", "return", "value", "logging", "code", "." ]
def WriteClientGLReturnLog(self, func, file): """Writes the return value logging code.""" if func.return_type != "void": file.Write(' GPU_CLIENT_LOG("return:" << result)\n')
[ "def", "WriteClientGLReturnLog", "(", "self", ",", "func", ",", "file", ")", ":", "if", "func", ".", "return_type", "!=", "\"void\"", ":", "file", ".", "Write", "(", "' GPU_CLIENT_LOG(\"return:\" << result)\\n'", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L2197-L2200
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/training/optimizer.py
python
Optimizer._apply_sparse
(self, grad, var)
Add ops to apply sparse gradients to `var`. Args: grad: `IndexedSlices`. var: A `Variable` object. Return: An `Operation`.
Add ops to apply sparse gradients to `var`.
[ "Add", "ops", "to", "apply", "sparse", "gradients", "to", "var", "." ]
def _apply_sparse(self, grad, var): """Add ops to apply sparse gradients to `var`. Args: grad: `IndexedSlices`. var: A `Variable` object. Return: An `Operation`. """ raise NotImplementedError()
[ "def", "_apply_sparse", "(", "self", ",", "grad", ",", "var", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/optimizer.py#L413-L423
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/apps/service.py
python
PropertyService.AddAllElementsFromAllPages
(self, link_finder, func)
return link_finder
retrieve all pages and add all elements
retrieve all pages and add all elements
[ "retrieve", "all", "pages", "and", "add", "all", "elements" ]
def AddAllElementsFromAllPages(self, link_finder, func): """retrieve all pages and add all elements""" next = link_finder.GetNextLink() while next is not None: next_feed = self.Get(next.href, converter=func) for a_entry in next_feed.entry: link_finder.entry.append(a_entry) next = next_feed.GetNextLink() return link_finder
[ "def", "AddAllElementsFromAllPages", "(", "self", ",", "link_finder", ",", "func", ")", ":", "next", "=", "link_finder", ".", "GetNextLink", "(", ")", "while", "next", "is", "not", "None", ":", "next_feed", "=", "self", ".", "Get", "(", "next", ".", "hre...
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/apps/service.py#L485-L493
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
third_party/cpplint.py
python
_IncludeState.IsInAlphabeticalOrder
(self, clean_lines, linenum, header_path)
return True
Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order.
Check if a header is in alphabetical order with the previous header.
[ "Check", "if", "a", "header", "is", "in", "alphabetical", "order", "with", "the", "previous", "header", "." ]
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): return False return True
[ "def", "IsInAlphabeticalOrder", "(", "self", ",", "clean_lines", ",", "linenum", ",", "header_path", ")", ":", "# If previous section is different from current section, _last_header will", "# be reset to empty string, so it's always less than current header.", "#", "# If previous line ...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/third_party/cpplint.py#L785-L804
interpretml/interpret
29466bffc04505fe4f836a83fcfebfd313ac8454
python/interpret-core/interpret/glassbox/ebm/internal.py
python
Booster.generate_term_update
( self, term_idx, generate_update_options, learning_rate, min_samples_leaf, max_leaves, )
return gain.value
Generates a boosting step update per feature by growing a shallow decision tree. Args: term_idx: The index for the term to generate the update for generate_update_options: C interface options learning_rate: Learning rate as a float. min_samples_leaf: Min observations required to split. max_leaves: Max leaf nodes on feature step. Returns: gain for the generated boosting step.
Generates a boosting step update per feature by growing a shallow decision tree.
[ "Generates", "a", "boosting", "step", "update", "per", "feature", "by", "growing", "a", "shallow", "decision", "tree", "." ]
def generate_term_update( self, term_idx, generate_update_options, learning_rate, min_samples_leaf, max_leaves, ): """ Generates a boosting step update per feature by growing a shallow decision tree. Args: term_idx: The index for the term to generate the update for generate_update_options: C interface options learning_rate: Learning rate as a float. min_samples_leaf: Min observations required to split. max_leaves: Max leaf nodes on feature step. Returns: gain for the generated boosting step. """ # log.debug("Boosting step start") self._term_idx = -1 native = Native.get_native_singleton() gain = ct.c_double(0.0) n_features = len(self.term_features[term_idx]) max_leaves_arr = np.full(n_features, max_leaves, dtype=ct.c_int64, order="C") return_code = native._unsafe.GenerateModelUpdate( self._booster_handle, term_idx, generate_update_options, learning_rate, min_samples_leaf, Native._make_pointer(max_leaves_arr, np.int64), ct.byref(gain), ) if return_code: # pragma: no cover raise Native._get_native_exception(return_code, "GenerateModelUpdate") self._term_idx = term_idx # log.debug("Boosting step end") return gain.value
[ "def", "generate_term_update", "(", "self", ",", "term_idx", ",", "generate_update_options", ",", "learning_rate", ",", "min_samples_leaf", ",", "max_leaves", ",", ")", ":", "# log.debug(\"Boosting step start\")", "self", ".", "_term_idx", "=", "-", "1", "native", "...
https://github.com/interpretml/interpret/blob/29466bffc04505fe4f836a83fcfebfd313ac8454/python/interpret-core/interpret/glassbox/ebm/internal.py#L1089-L1137
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_PrepareListOfSources
(spec, generator_flags, gyp_file)
return (sources, excluded_sources)
Prepare list of sources and excluded sources. Besides the sources specified directly in the spec, adds the gyp file so that a change to it will cause a re-compile. Also adds appropriate sources for actions and copies. Assumes later stage will un-exclude files which have custom build steps attached. Arguments: spec: The target dictionary containing the properties of the target. gyp_file: The name of the gyp file. Returns: A pair of (list of sources, list of excluded sources). The sources will be relative to the gyp file.
Prepare list of sources and excluded sources.
[ "Prepare", "list", "of", "sources", "and", "excluded", "sources", "." ]
def _PrepareListOfSources(spec, generator_flags, gyp_file): """Prepare list of sources and excluded sources. Besides the sources specified directly in the spec, adds the gyp file so that a change to it will cause a re-compile. Also adds appropriate sources for actions and copies. Assumes later stage will un-exclude files which have custom build steps attached. Arguments: spec: The target dictionary containing the properties of the target. gyp_file: The name of the gyp file. Returns: A pair of (list of sources, list of excluded sources). The sources will be relative to the gyp file. """ sources = OrderedSet() _AddNormalizedSources(sources, spec.get('sources', [])) excluded_sources = OrderedSet() # Add in the gyp file. if not generator_flags.get('standalone'): sources.add(gyp_file) # Add in 'action' inputs and outputs. for a in spec.get('actions', []): inputs = a['inputs'] inputs = [_NormalizedSource(i) for i in inputs] # Add all inputs to sources and excluded sources. inputs = OrderedSet(inputs) sources.update(inputs) if not spec.get('msvs_external_builder'): excluded_sources.update(inputs) if int(a.get('process_outputs_as_sources', False)): _AddNormalizedSources(sources, a.get('outputs', [])) # Add in 'copies' inputs and outputs. for cpy in spec.get('copies', []): _AddNormalizedSources(sources, cpy.get('files', [])) return (sources, excluded_sources)
[ "def", "_PrepareListOfSources", "(", "spec", ",", "generator_flags", ",", "gyp_file", ")", ":", "sources", "=", "OrderedSet", "(", ")", "_AddNormalizedSources", "(", "sources", ",", "spec", ".", "get", "(", "'sources'", ",", "[", "]", ")", ")", "excluded_sou...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L1446-L1482
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/exceptions.py
python
HashMismatch.__init__
(self, allowed, gots)
:param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion
:param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion
[ ":", "param", "allowed", ":", "A", "dict", "of", "algorithm", "names", "pointing", "to", "lists", "of", "allowed", "hex", "digests", ":", "param", "gots", ":", "A", "dict", "of", "algorithm", "names", "pointing", "to", "hashes", "we", "actually", "got", ...
def __init__(self, allowed, gots): # type: (Dict[str, List[str]], Dict[str, _Hash]) -> None """ :param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion """ self.allowed = allowed self.gots = gots
[ "def", "__init__", "(", "self", ",", "allowed", ",", "gots", ")", ":", "# type: (Dict[str, List[str]], Dict[str, _Hash]) -> None", "self", ".", "allowed", "=", "allowed", "self", ".", "gots", "=", "gots" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/exceptions.py#L317-L326
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/traceback.py
python
print_list
(extracted_list, file=None)
Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.
Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.
[ "Print", "the", "list", "of", "tuples", "as", "returned", "by", "extract_tb", "()", "or", "extract_stack", "()", "as", "a", "formatted", "stack", "trace", "to", "the", "given", "file", "." ]
def print_list(extracted_list, file=None): """Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.""" if file is None: file = sys.stderr for item in StackSummary.from_list(extracted_list).format(): print(item, file=file, end="")
[ "def", "print_list", "(", "extracted_list", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "for", "item", "in", "StackSummary", ".", "from_list", "(", "extracted_list", ")", ".", "format", "(", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/traceback.py#L19-L25
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
ppapi/generators/idl_parser.py
python
IDLParser.p_struct_list
(self, p)
struct_list : member_attribute ';' struct_list | member_function ';' struct_list |
struct_list : member_attribute ';' struct_list | member_function ';' struct_list |
[ "struct_list", ":", "member_attribute", ";", "struct_list", "|", "member_function", ";", "struct_list", "|" ]
def p_struct_list(self, p): """struct_list : member_attribute ';' struct_list | member_function ';' struct_list |""" if len(p) > 1: p[0] = ListFromConcat(p[1], p[3])
[ "def", "p_struct_list", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", ">", "1", ":", "p", "[", "0", "]", "=", "ListFromConcat", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/ppapi/generators/idl_parser.py#L799-L803
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/bdb.py
python
Bdb.user_exception
(self, frame, exc_info)
This method is called if an exception occurs, but only if we are to stop at or just below this level.
This method is called if an exception occurs, but only if we are to stop at or just below this level.
[ "This", "method", "is", "called", "if", "an", "exception", "occurs", "but", "only", "if", "we", "are", "to", "stop", "at", "or", "just", "below", "this", "level", "." ]
def user_exception(self, frame, exc_info): exc_type, exc_value, exc_traceback = exc_info """This method is called if an exception occurs, but only if we are to stop at or just below this level.""" pass
[ "def", "user_exception", "(", "self", ",", "frame", ",", "exc_info", ")", ":", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "exc_info", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/bdb.py#L170-L174
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops_v2.py
python
he_uniform
(seed=None)
return VarianceScaling( scale=2., mode="fan_in", distribution="uniform", seed=seed)
He uniform variance scaling initializer. It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(6 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))
He uniform variance scaling initializer.
[ "He", "uniform", "variance", "scaling", "initializer", "." ]
def he_uniform(seed=None): """He uniform variance scaling initializer. It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(6 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) """ return VarianceScaling( scale=2., mode="fan_in", distribution="uniform", seed=seed)
[ "def", "he_uniform", "(", "seed", "=", "None", ")", ":", "return", "VarianceScaling", "(", "scale", "=", "2.", ",", "mode", "=", "\"fan_in\"", ",", "distribution", "=", "\"uniform\"", ",", "seed", "=", "seed", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops_v2.py#L702-L720
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_action_let_eqns_lcb_action_rcb
(p)
action : LET eqns sequence
action : LET eqns sequence
[ "action", ":", "LET", "eqns", "sequence" ]
def p_action_let_eqns_lcb_action_rcb(p): 'action : LET eqns sequence' p[0] = LetAction(*(p[2]+[p[3]]))
[ "def", "p_action_let_eqns_lcb_action_rcb", "(", "p", ")", ":", "p", "[", "0", "]", "=", "LetAction", "(", "*", "(", "p", "[", "2", "]", "+", "[", "p", "[", "3", "]", "]", ")", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L2421-L2423
TheImagingSource/tiscamera
baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6
tools/tcam-capture/tcam_capture/TcamSpinBox.py
python
TcamSpinBox.mouseReleaseEvent
(self, event)
Reset mouse related properties
Reset mouse related properties
[ "Reset", "mouse", "related", "properties" ]
def mouseReleaseEvent(self, event): """ Reset mouse related properties """ self.is_active = False super().mouseReleaseEvent(event)
[ "def", "mouseReleaseEvent", "(", "self", ",", "event", ")", ":", "self", ".", "is_active", "=", "False", "super", "(", ")", ".", "mouseReleaseEvent", "(", "event", ")" ]
https://github.com/TheImagingSource/tiscamera/blob/baacb4cfaa7858c2e6cfb4f1a297b404c4e002f6/tools/tcam-capture/tcam_capture/TcamSpinBox.py#L58-L63
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/urllib/parse.py
python
unquote
(string, encoding='utf-8', errors='replace')
return ''.join(res)
Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-encoded sequences are decoded with UTF-8, and invalid sequences are replaced by a placeholder character. unquote('abc%20def') -> 'abc def'.
Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-encoded sequences are decoded with UTF-8, and invalid sequences are replaced by a placeholder character.
[ "Replace", "%xx", "escapes", "by", "their", "single", "-", "character", "equivalent", ".", "The", "optional", "encoding", "and", "errors", "parameters", "specify", "how", "to", "decode", "percent", "-", "encoded", "sequences", "into", "Unicode", "characters", "a...
def unquote(string, encoding='utf-8', errors='replace'): """Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method. By default, percent-encoded sequences are decoded with UTF-8, and invalid sequences are replaced by a placeholder character. unquote('abc%20def') -> 'abc def'. """ if '%' not in string: string.split return string if encoding is None: encoding = 'utf-8' if errors is None: errors = 'replace' bits = _asciire.split(string) res = [bits[0]] append = res.append for i in range(1, len(bits), 2): append(unquote_to_bytes(bits[i]).decode(encoding, errors)) append(bits[i + 1]) return ''.join(res)
[ "def", "unquote", "(", "string", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "if", "'%'", "not", "in", "string", ":", "string", ".", "split", "return", "string", "if", "encoding", "is", "None", ":", "encoding", "=", "'ut...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/urllib/parse.py#L619-L642
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/backcall/backcall/_signatures.py
python
Signature.replace
(self, parameters=_void, return_annotation=_void)
return type(self)(parameters, return_annotation=return_annotation)
Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy.
Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy.
[ "Creates", "a", "customized", "copy", "of", "the", "Signature", ".", "Pass", "parameters", "and", "/", "or", "return_annotation", "arguments", "to", "override", "them", "in", "the", "new", "copy", "." ]
def replace(self, parameters=_void, return_annotation=_void): '''Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. ''' if parameters is _void: parameters = self.parameters.values() if return_annotation is _void: return_annotation = self._return_annotation return type(self)(parameters, return_annotation=return_annotation)
[ "def", "replace", "(", "self", ",", "parameters", "=", "_void", ",", "return_annotation", "=", "_void", ")", ":", "if", "parameters", "is", "_void", ":", "parameters", "=", "self", ".", "parameters", ".", "values", "(", ")", "if", "return_annotation", "is"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/backcall/backcall/_signatures.py#L597-L610
wisdompeak/LeetCode
ef729c1249ead3ead47f1a94b5eeb5958a69e152
Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.py
python
Solution.distinctSubseqII
(self, S)
return int(dp)
:type S: str :rtype: int
:type S: str :rtype: int
[ ":", "type", "S", ":", "str", ":", "rtype", ":", "int" ]
def distinctSubseqII(self, S): """ :type S: str :rtype: int """ last = [0 for _ in range(26)] dp = 0 M = 1e9+7 for ch in S: dp_temp = dp dp = dp_temp + (dp_temp +1 - last[ord(ch)-ord('a')]) dp %= M last[ord(ch)-ord('a')] = dp_temp+1 last[ord(ch)-ord('a')] %= M return int(dp)
[ "def", "distinctSubseqII", "(", "self", ",", "S", ")", ":", "last", "=", "[", "0", "for", "_", "in", "range", "(", "26", ")", "]", "dp", "=", "0", "M", "=", "1e9", "+", "7", "for", "ch", "in", "S", ":", "dp_temp", "=", "dp", "dp", "=", "dp_...
https://github.com/wisdompeak/LeetCode/blob/ef729c1249ead3ead47f1a94b5eeb5958a69e152/Dynamic_Programming/940.Distinct-Subsequences-II/940.Distinct-Subsequences-II.py#L2-L17
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
python
AppleScript_Suite_Events.start_log
(self, _no_object=None, _attributes={}, **_arguments)
start log: Start event logging in the script editor Keyword argument _attributes: AppleEvent attribute dictionary
start log: Start event logging in the script editor Keyword argument _attributes: AppleEvent attribute dictionary
[ "start", "log", ":", "Start", "event", "logging", "in", "the", "script", "editor", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def start_log(self, _no_object=None, _attributes={}, **_arguments): """start log: Start event logging in the script editor Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'ToyS' _subcode = 'log1' if _arguments: raise TypeError, 'No optional args expected' if _no_object is not None: raise TypeError, 'No direct arg expected' _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "start_log", "(", "self", ",", "_no_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'ToyS'", "_subcode", "=", "'log1'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optiona...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py#L580-L597
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py
python
_formatparam
(param, value=None, quote=True)
Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules.
Convenience function to format and return a key=value pair.
[ "Convenience", "function", "to", "format", "and", "return", "a", "key", "=", "value", "pair", "." ]
def _formatparam(param, value=None, quote=True): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. """ if value is not None and len(value) > 0: # A tuple is used for RFC 2231 encoded parameter values where items # are (charset, language, value). charset is a string, not a Charset # instance. if isinstance(value, tuple): # Encode as per RFC 2231 param += '*' value = utils.encode_rfc2231(value[2], value[0], value[1]) # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, utils.quote(value)) else: return '%s=%s' % (param, value) else: return param
[ "def", "_formatparam", "(", "param", ",", "value", "=", "None", ",", "quote", "=", "True", ")", ":", "if", "value", "is", "not", "None", "and", "len", "(", "value", ")", ">", "0", ":", "# A tuple is used for RFC 2231 encoded parameter values where items", "# a...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py#L38-L60
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/mox3/mox3/mox.py
python
And.__init__
(self, *args)
Initialize. Args: *args: One or more Comparator
Initialize.
[ "Initialize", "." ]
def __init__(self, *args): """Initialize. Args: *args: One or more Comparator """ self._comparators = args
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_comparators", "=", "args" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/mox3/mox3/mox.py#L1745-L1752
PaddlePaddle/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
tools/external_converter_v2/parser/caffe/parser_caffe.py
python
CaffeParser._UpgradeNetAsNeeded
(self)
same as caffe UpgradeNetAsNeeded.
same as caffe UpgradeNetAsNeeded.
[ "same", "as", "caffe", "UpgradeNetAsNeeded", "." ]
def _UpgradeNetAsNeeded(self): """ same as caffe UpgradeNetAsNeeded. """ if NetNeedsV0ToV1Upgrade(self.net_parameter): # NetParameter was specified using the old style (V0LayerParameter), need to upgrade. logger(verbose.INFO).feed("[ Upgrade Level 1 ] Details: need to upgrade from V0 to V1 [ ... ]") original_param = NetParameter() original_param.CopyFrom(self.net_parameter) if UpgradeV0Net(original_param, self.net_parameter): logger(verbose.WARNING).feed("[ Upgrade Level 1 ] Details: need to upgrade from V0 to V1 [ SUC ]") else: logger(verbose.FATAL).feed("[ Upgrade Level 1 ] Details: need to upgrade from V0 to V1 [ FAILED ]") exit() if NetNeedsDataUpgrade(self.net_parameter): logger(verbose.WARNING).feed("[ Upgrade Level 2 ] Details: need Data upgrade [ IGNORED ]") if NetNeedsV1ToV2Upgrade(self.net_parameter): logger(verbose.INFO).feed("[ Upgrade Level 3 ] Details: need to upgrade from V1 to V2 [ ... ]") original_param = NetParameter() original_param.CopyFrom(self.net_parameter) if UpgradeV1Net(original_param, self.net_parameter): logger(verbose.WARNING).feed("[ Upgrade Level 3 ] Details: need to upgrade from V1 to V2 [ SUC ]") else: logger(verbose.FATAL).feed("[ Upgrade Level 3 ] Details: need to upgrade from V1 to V2 [ FAILED ]") exit() if NetNeedsInputUpgrade(self.net_parameter): logger(verbose.INFO).feed("[ Upgrade Level 4 ] Details: need Input upgrade [ ... ]") UpgradeNetInput(self.net_parameter) logger(verbose.WARNING).feed("[ Upgrade Level 4 ] Details: need Input upgrade [ SUC ]") if NetNeedsBatchNormUpgrade(self.net_parameter): logger(verbose.INFO).feed("[ Upgrade Level 5 ] Details: need BatchNorm upgrade [ ... ]") UpgradeNetBatchNorm(self.net_parameter) logger(verbose.INFO).feed("[ Upgrade Level 5 ] Details: need BatchNorm upgrade [ ... ]")
[ "def", "_UpgradeNetAsNeeded", "(", "self", ")", ":", "if", "NetNeedsV0ToV1Upgrade", "(", "self", ".", "net_parameter", ")", ":", "# NetParameter was specified using the old style (V0LayerParameter), need to upgrade.", "logger", "(", "verbose", ".", "INFO", ")", ".", "feed...
https://github.com/PaddlePaddle/Anakin/blob/5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730/tools/external_converter_v2/parser/caffe/parser_caffe.py#L186-L218
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/masked/timectrl.py
python
TimeCtrl.ChangeValue
(self, value)
Validating ChangeValue function for time values: This function will do dynamic type checking on the value argument, and convert wxDateTime, mxDateTime, or 12/24 format time string into the appropriate format string for the control.
Validating ChangeValue function for time values: This function will do dynamic type checking on the value argument, and convert wxDateTime, mxDateTime, or 12/24 format time string into the appropriate format string for the control.
[ "Validating", "ChangeValue", "function", "for", "time", "values", ":", "This", "function", "will", "do", "dynamic", "type", "checking", "on", "the", "value", "argument", "and", "convert", "wxDateTime", "mxDateTime", "or", "12", "/", "24", "format", "time", "st...
def ChangeValue(self, value): """ Validating ChangeValue function for time values: This function will do dynamic type checking on the value argument, and convert wxDateTime, mxDateTime, or 12/24 format time string into the appropriate format string for the control. """ ## dbg('TimeCtrl::ChangeValue(%s)' % repr(value), indent=1) try: strtime = self._toGUI(self.__validateValue(value)) except: ## dbg('validation failed', indent=0) raise ## dbg('strtime:', strtime) self._ChangeValue(strtime)
[ "def", "ChangeValue", "(", "self", ",", "value", ")", ":", "## dbg('TimeCtrl::ChangeValue(%s)' % repr(value), indent=1)", "try", ":", "strtime", "=", "self", ".", "_toGUI", "(", "self", ".", "__validateValue", "(", "value", ")", ")", "except", ":", "## ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/timectrl.py#L642-L657
manutdzou/KITTI_SSD
5b620c2f291d36a0fe14489214f22a992f173f44
scripts/cpp_lint.py
python
CheckInvalidIncrement
(filename, clean_lines, linenum, error)
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for invalid increment *count++.
[ "Checks", "for", "invalid", "increment", "*", "count", "++", "." ]
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).')
[ "def", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "_RE_PATTERN_INVALID_INCREMENT", ".", "match", "(", "line", ")", ":", "error", ...
https://github.com/manutdzou/KITTI_SSD/blob/5b620c2f291d36a0fe14489214f22a992f173f44/scripts/cpp_lint.py#L1737-L1756
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListCtrl.DeleteColumn
(*args, **kwargs)
return _controls_.ListCtrl_DeleteColumn(*args, **kwargs)
DeleteColumn(self, int col) -> bool
DeleteColumn(self, int col) -> bool
[ "DeleteColumn", "(", "self", "int", "col", ")", "-", ">", "bool" ]
def DeleteColumn(*args, **kwargs): """DeleteColumn(self, int col) -> bool""" return _controls_.ListCtrl_DeleteColumn(*args, **kwargs)
[ "def", "DeleteColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_DeleteColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4649-L4651
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tix.py
python
ButtonBox.add
(self, name, cnf={}, **kw)
return btn
Add a button with given name to box.
Add a button with given name to box.
[ "Add", "a", "button", "with", "given", "name", "to", "box", "." ]
def add(self, name, cnf={}, **kw): """Add a button with given name to box.""" btn = self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = _dummyButton(self, name) return btn
[ "def", "add", "(", "self", ",", "name", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "btn", "=", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'add'", ",", "name", ",", "*", "self", ".", "_options", "(", "cnf", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tix.py#L566-L571
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
LogWindow.IsPassingMessages
(*args, **kwargs)
return _misc_.LogWindow_IsPassingMessages(*args, **kwargs)
IsPassingMessages(self) -> bool
IsPassingMessages(self) -> bool
[ "IsPassingMessages", "(", "self", ")", "-", ">", "bool" ]
def IsPassingMessages(*args, **kwargs): """IsPassingMessages(self) -> bool""" return _misc_.LogWindow_IsPassingMessages(*args, **kwargs)
[ "def", "IsPassingMessages", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "LogWindow_IsPassingMessages", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L1782-L1784
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
CustomTreeCtrl.GetSecondGradientColour
(self)
return self._secondcolour
Returns the second gradient colour for gradient-style selections. :return: An instance of :class:`Colour`.
Returns the second gradient colour for gradient-style selections.
[ "Returns", "the", "second", "gradient", "colour", "for", "gradient", "-", "style", "selections", "." ]
def GetSecondGradientColour(self): """ Returns the second gradient colour for gradient-style selections. :return: An instance of :class:`Colour`. """ return self._secondcolour
[ "def", "GetSecondGradientColour", "(", "self", ")", ":", "return", "self", ".", "_secondcolour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L4080-L4087
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/simple_server.py
python
WSGIServer.server_bind
(self)
Override server_bind to store the server name.
Override server_bind to store the server name.
[ "Override", "server_bind", "to", "store", "the", "server", "name", "." ]
def server_bind(self): """Override server_bind to store the server name.""" HTTPServer.server_bind(self) self.setup_environ()
[ "def", "server_bind", "(", "self", ")", ":", "HTTPServer", ".", "server_bind", "(", "self", ")", "self", ".", "setup_environ", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/wsgiref/simple_server.py#L46-L49
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/recordio.py
python
pack_img
(header, img, quality=95, img_fmt='.jpg')
return pack(header, buf.tostring())
Pack an image into ``MXImageRecord``. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. img : numpy.ndarray Image to be packed. quality : int Quality for JPEG encoding in range 1-100, or compression for PNG encoding in range 1-9. img_fmt : str Encoding of the image (.jpg for JPEG, .png for PNG). Returns ------- s : str The packed string. Examples -------- >>> label = 4 # label can also be a 1-D array, for example: label = [1,2,3] >>> id = 2574 >>> header = mx.recordio.IRHeader(0, label, id, 0) >>> img = cv2.imread('test.jpg') >>> packed_s = mx.recordio.pack_img(header, img)
Pack an image into ``MXImageRecord``.
[ "Pack", "an", "image", "into", "MXImageRecord", "." ]
def pack_img(header, img, quality=95, img_fmt='.jpg'): """Pack an image into ``MXImageRecord``. Parameters ---------- header : IRHeader Header of the image record. ``header.label`` can be a number or an array. See more detail in ``IRHeader``. img : numpy.ndarray Image to be packed. quality : int Quality for JPEG encoding in range 1-100, or compression for PNG encoding in range 1-9. img_fmt : str Encoding of the image (.jpg for JPEG, .png for PNG). Returns ------- s : str The packed string. Examples -------- >>> label = 4 # label can also be a 1-D array, for example: label = [1,2,3] >>> id = 2574 >>> header = mx.recordio.IRHeader(0, label, id, 0) >>> img = cv2.imread('test.jpg') >>> packed_s = mx.recordio.pack_img(header, img) """ assert cv2 is not None jpg_formats = ['.JPG', '.JPEG'] png_formats = ['.PNG'] encode_params = None if img_fmt.upper() in jpg_formats: encode_params = [cv2.IMWRITE_JPEG_QUALITY, quality] elif img_fmt.upper() in png_formats: encode_params = [cv2.IMWRITE_PNG_COMPRESSION, quality] ret, buf = cv2.imencode(img_fmt, img, encode_params) assert ret, 'failed to encode image' return pack(header, buf.tostring())
[ "def", "pack_img", "(", "header", ",", "img", ",", "quality", "=", "95", ",", "img_fmt", "=", "'.jpg'", ")", ":", "assert", "cv2", "is", "not", "None", "jpg_formats", "=", "[", "'.JPG'", ",", "'.JPEG'", "]", "png_formats", "=", "[", "'.PNG'", "]", "e...
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/recordio.py#L470-L509
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/xcodeproj_file.py
python
XCHierarchicalElement.Hashables
(self)
return hashables
Custom hashables for XCHierarchicalElements. XCHierarchicalElements are special. Generally, their hashes shouldn't change if the paths don't change. The normal XCObject implementation of Hashables adds a hashable for each object, which means that if the hierarchical structure changes (possibly due to changes caused when TakeOverOnlyChild runs and encounters slight changes in the hierarchy), the hashes will change. For example, if a project file initially contains a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent a/b. If someone later adds a/f2 to the project file, a/b can no longer be collapsed, and f1 winds up with parent b and grandparent a. That would be sufficient to change f1's hash. To counteract this problem, hashables for all XCHierarchicalElements except for the main group (which has neither a name nor a path) are taken to be just the set of path components. Because hashables are inherited from parents, this provides assurance that a/b/f1 has the same set of hashables whether its parent is b or a/b. The main group is a special case. As it is permitted to have no name or path, it is permitted to use the standard XCObject hash mechanism. This is not considered a problem because there can be only one main group.
Custom hashables for XCHierarchicalElements.
[ "Custom", "hashables", "for", "XCHierarchicalElements", "." ]
def Hashables(self): """Custom hashables for XCHierarchicalElements. XCHierarchicalElements are special. Generally, their hashes shouldn't change if the paths don't change. The normal XCObject implementation of Hashables adds a hashable for each object, which means that if the hierarchical structure changes (possibly due to changes caused when TakeOverOnlyChild runs and encounters slight changes in the hierarchy), the hashes will change. For example, if a project file initially contains a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent a/b. If someone later adds a/f2 to the project file, a/b can no longer be collapsed, and f1 winds up with parent b and grandparent a. That would be sufficient to change f1's hash. To counteract this problem, hashables for all XCHierarchicalElements except for the main group (which has neither a name nor a path) are taken to be just the set of path components. Because hashables are inherited from parents, this provides assurance that a/b/f1 has the same set of hashables whether its parent is b or a/b. The main group is a special case. As it is permitted to have no name or path, it is permitted to use the standard XCObject hash mechanism. This is not considered a problem because there can be only one main group. """ if self == self.PBXProjectAncestor()._properties['mainGroup']: # super return XCObject.Hashables(self) hashables = [] # Put the name in first, ensuring that if TakeOverOnlyChild collapses # children into a top-level group like "Source", the name always goes # into the list of hashables without interfering with path components. if 'name' in self._properties: # Make it less likely for people to manipulate hashes by following the # pattern of always pushing an object type value onto the list first. hashables.append(self.__class__.__name__ + '.name') hashables.append(self._properties['name']) # NOTE: This still has the problem that if an absolute path is encountered, # including paths with a sourceTree, they'll still inherit their parents' # hashables, even though the paths aren't relative to their parents. This # is not expected to be much of a problem in practice. path = self.PathFromSourceTreeAndPath() if path != None: components = path.split(posixpath.sep) for component in components: hashables.append(self.__class__.__name__ + '.path') hashables.append(component) hashables.extend(self._hashables) return hashables
[ "def", "Hashables", "(", "self", ")", ":", "if", "self", "==", "self", ".", "PBXProjectAncestor", "(", ")", ".", "_properties", "[", "'mainGroup'", "]", ":", "# super", "return", "XCObject", ".", "Hashables", "(", "self", ")", "hashables", "=", "[", "]",...
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/xcodeproj_file.py#L952-L1005
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/android_commands.py
python
AndroidCommands.GetMemoryUsageForPackage
(self, package)
return usage_dict, smaps
Returns the memory usage for all processes whose name contains |pacakge|. Args: package: A string holding process name to lookup pid list for. Returns: A tuple containg: [0]: Dict of {metric:usage_kb}, summed over all pids associated with |name|. The metric keys which may be included are: Size, Rss, Pss, Shared_Clean, Shared_Dirty, Private_Clean, Private_Dirty, Referenced, Swap, KernelPageSize, MMUPageSize, Nvidia (tablet only). [1]: a list with detailed /proc/[PID]/smaps information.
Returns the memory usage for all processes whose name contains |pacakge|.
[ "Returns", "the", "memory", "usage", "for", "all", "processes", "whose", "name", "contains", "|pacakge|", "." ]
def GetMemoryUsageForPackage(self, package): """Returns the memory usage for all processes whose name contains |pacakge|. Args: package: A string holding process name to lookup pid list for. Returns: A tuple containg: [0]: Dict of {metric:usage_kb}, summed over all pids associated with |name|. The metric keys which may be included are: Size, Rss, Pss, Shared_Clean, Shared_Dirty, Private_Clean, Private_Dirty, Referenced, Swap, KernelPageSize, MMUPageSize, Nvidia (tablet only). [1]: a list with detailed /proc/[PID]/smaps information. """ usage_dict = collections.defaultdict(int) pid_list = self.ExtractPid(package) smaps = collections.defaultdict(dict) for pid in pid_list: usage_dict_per_pid, smaps_per_pid = self.GetMemoryUsageForPid(pid) smaps[pid] = smaps_per_pid for (key, value) in usage_dict_per_pid.items(): usage_dict[key] += value return usage_dict, smaps
[ "def", "GetMemoryUsageForPackage", "(", "self", ",", "package", ")", ":", "usage_dict", "=", "collections", ".", "defaultdict", "(", "int", ")", "pid_list", "=", "self", ".", "ExtractPid", "(", "package", ")", "smaps", "=", "collections", ".", "defaultdict", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/android_commands.py#L1564-L1589
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
documentation/doxygen/converttonotebook.py
python
cppComments
(text)
return newtext
Converts comments delimited by // and on a new line into a markdown cell. For C++ files only. >>> cppComments('''// This is a ... // multiline comment ... void function(){}''') '# <markdowncell>\\n# This is a\\n# multiline comment\\n# <codecell>\\nvoid function(){}\\n' >>> cppComments('''void function(){ ... int variable = 5 // Comment not in cell ... // Comment also not in cell ... }''') 'void function(){\\n int variable = 5 // Comment not in cell\\n // Comment also not in cell\\n}\\n'
Converts comments delimited by // and on a new line into a markdown cell. For C++ files only. >>> cppComments('''// This is a ... // multiline comment ... void function(){}''') '# <markdowncell>\\n# This is a\\n# multiline comment\\n# <codecell>\\nvoid function(){}\\n' >>> cppComments('''void function(){ ... int variable = 5 // Comment not in cell ... // Comment also not in cell ... }''') 'void function(){\\n int variable = 5 // Comment not in cell\\n // Comment also not in cell\\n}\\n'
[ "Converts", "comments", "delimited", "by", "//", "and", "on", "a", "new", "line", "into", "a", "markdown", "cell", ".", "For", "C", "++", "files", "only", ".", ">>>", "cppComments", "(", "//", "This", "is", "a", "...", "//", "multiline", "comment", ".....
def cppComments(text): """ Converts comments delimited by // and on a new line into a markdown cell. For C++ files only. >>> cppComments('''// This is a ... // multiline comment ... void function(){}''') '# <markdowncell>\\n# This is a\\n# multiline comment\\n# <codecell>\\nvoid function(){}\\n' >>> cppComments('''void function(){ ... int variable = 5 // Comment not in cell ... // Comment also not in cell ... }''') 'void function(){\\n int variable = 5 // Comment not in cell\\n // Comment also not in cell\\n}\\n' """ text = text.splitlines() newtext = '' inComment = False for line in text: if line.startswith("//") and not inComment: # True if first line of comment inComment = True newtext += "# <markdowncell>\n" if line[2:].lstrip().startswith("#"): # Don't use .capitalize() if line starts with hash, ie it is a header newtext += ("# " + line[2:]+"\n") else: newtext += ("# " + line[2:].lstrip().capitalize()+"\n") elif inComment and not line.startswith("//"): # True if first line after comment inComment = False newtext += "# <codecell>\n" newtext += (line+"\n") elif inComment and line.startswith("//"): # True if in the middle of a comment block newtext += ("# " + line[2:] + "\n") else: newtext += (line+"\n") return newtext
[ "def", "cppComments", "(", "text", ")", ":", "text", "=", "text", ".", "splitlines", "(", ")", "newtext", "=", "''", "inComment", "=", "False", "for", "line", "in", "text", ":", "if", "line", ".", "startswith", "(", "\"//\"", ")", "and", "not", "inCo...
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/documentation/doxygen/converttonotebook.py#L339-L373
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py
python
BaseEventLoop.create_connection
( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)
return transport, protocol
Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair.
Connect to a TCP server.
[ "Connect", "to", "a", "TCP", "server", "." ]
async def create_connection( self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None): """Connect to a TCP server. Create a streaming transport connection to a given Internet host and port: socket family AF_INET or socket.AF_INET6 depending on host (or family if specified), socket type SOCK_STREAM. protocol_factory must be a callable returning a protocol instance. This method is a coroutine which will try to establish the connection in the background. When successful, the coroutine returns a (transport, protocol) pair. """ if server_hostname is not None and not ssl: raise ValueError('server_hostname is only meaningful with ssl') if server_hostname is None and ssl: # Use host as default for server_hostname. It is an error # if host is empty or not set, e.g. when an # already-connected socket was passed or when only a port # is given. To avoid this error, you can pass # server_hostname='' -- this will bypass the hostname # check. (This also means that if host is a numeric # IP/IPv6 address, we will attempt to verify that exact # address; this will probably fail, but it is possible to # create a certificate for a specific IP address, so we # don't judge it here.) if not host: raise ValueError('You must set server_hostname ' 'when using ssl without a host') server_hostname = host if ssl_handshake_timeout is not None and not ssl: raise ValueError( 'ssl_handshake_timeout is only meaningful with ssl') if host is not None or port is not None: if sock is not None: raise ValueError( 'host/port and sock can not be specified at the same time') infos = await self._ensure_resolved( (host, port), family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not infos: raise OSError('getaddrinfo() returned empty list') if local_addr is not None: laddr_infos = await self._ensure_resolved( local_addr, family=family, type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self) if not laddr_infos: raise OSError('getaddrinfo() returned empty list') exceptions = [] for family, type, proto, cname, address in infos: try: sock = socket.socket(family=family, type=type, proto=proto) sock.setblocking(False) if local_addr is not None: for _, _, _, _, laddr in laddr_infos: try: sock.bind(laddr) break except OSError as exc: msg = ( f'error while attempting to bind on ' f'address {laddr!r}: ' f'{exc.strerror.lower()}' ) exc = OSError(exc.errno, msg) exceptions.append(exc) else: sock.close() sock = None continue if self._debug: logger.debug("connect %r to %r", sock, address) await self.sock_connect(sock, address) except OSError as exc: if sock is not None: sock.close() exceptions.append(exc) except: if sock is not None: sock.close() raise else: break else: if len(exceptions) == 1: raise exceptions[0] else: # If they all have the same str(), raise one. model = str(exceptions[0]) if all(str(exc) == model for exc in exceptions): raise exceptions[0] # Raise a combined exception so the user can see all # the various error messages. raise OSError('Multiple exceptions: {}'.format( ', '.join(str(exc) for exc in exceptions))) else: if sock is None: raise ValueError( 'host and port was not specified and no sock specified') if sock.type != socket.SOCK_STREAM: # We allow AF_INET, AF_INET6, AF_UNIX as long as they # are SOCK_STREAM. # We support passing AF_UNIX sockets even though we have # a dedicated API for that: create_unix_connection. # Disallowing AF_UNIX in this method, breaks backwards # compatibility. raise ValueError( f'A Stream Socket was expected, got {sock!r}') transport, protocol = await self._create_connection_transport( sock, protocol_factory, ssl, server_hostname, ssl_handshake_timeout=ssl_handshake_timeout) if self._debug: # Get the socket from the transport because SSL transport closes # the old socket and creates a new SSL socket sock = transport.get_extra_info('socket') logger.debug("%r connected to %s:%r: (%r, %r)", sock, host, port, transport, protocol) return transport, protocol
[ "async", "def", "create_connection", "(", "self", ",", "protocol_factory", ",", "host", "=", "None", ",", "port", "=", "None", ",", "*", ",", "ssl", "=", "None", ",", "family", "=", "0", ",", "proto", "=", "0", ",", "flags", "=", "0", ",", "sock", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/asyncio/base_events.py#L866-L996
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/jormungandr/jormungandr/scenarios/new_default.py
python
get_kraken_id
(entrypoint_detail)
return '{};{}'.format(coord['lon'], coord['lat'])
returns a usable id for kraken from the entrypoint detail returns None if the original ID needs to be kept
returns a usable id for kraken from the entrypoint detail returns None if the original ID needs to be kept
[ "returns", "a", "usable", "id", "for", "kraken", "from", "the", "entrypoint", "detail", "returns", "None", "if", "the", "original", "ID", "needs", "to", "be", "kept" ]
def get_kraken_id(entrypoint_detail): """ returns a usable id for kraken from the entrypoint detail returns None if the original ID needs to be kept """ if not entrypoint_detail: # impossible to find the object return None emb_type = entrypoint_detail.get('embedded_type') if emb_type in ('stop_point', 'stop_area', 'administrative_region'): # for those object, we need to keep the original id, as there are specific treatment to be done return None # for the other objects the id is the object coordinated coord = entrypoint_detail.get(emb_type, {}).get('coord') if not coord: # no coordinate, we keep the original id return None return '{};{}'.format(coord['lon'], coord['lat'])
[ "def", "get_kraken_id", "(", "entrypoint_detail", ")", ":", "if", "not", "entrypoint_detail", ":", "# impossible to find the object", "return", "None", "emb_type", "=", "entrypoint_detail", ".", "get", "(", "'embedded_type'", ")", "if", "emb_type", "in", "(", "'stop...
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/scenarios/new_default.py#L868-L889
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/_vendor/six.py
python
python_2_unicode_compatible
(klass)
return klass
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing.
[ "A", "decorator", "that", "defines", "__unicode__", "and", "__str__", "methods", "under", "Python", "2", ".", "Under", "Python", "3", "it", "does", "nothing", "." ]
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass
[ "def", "python_2_unicode_compatible", "(", "klass", ")", ":", "if", "PY2", ":", "if", "'__str__'", "not", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "\"@python_2_unicode_compatible cannot be applied \"", "\"to %s because it doesn't define __str__().\""...
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/_vendor/six.py#L828-L843
nodejs/nan
8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62
cpplint.py
python
CheckSpacingForFunctionCall
(filename, clean_lines, linenum, error)
Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for the correctness of various spacing around function calls.
[ "Checks", "for", "the", "correctness", "of", "various", "spacing", "around", "function", "calls", "." ]
def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and not Search(r'\bcase\s+\(', fncall)): # TODO(unknown): Space after an operator function seem to be a common # error, silence those for now by restricting them to highest verbosity. if Search(r'\boperator_*\b', line): error(filename, linenum, 'whitespace/parens', 0, 'Extra space before ( in function call') else: error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )')
[ "def", "CheckSpacingForFunctionCall", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Since function calls often occur inside if/for/while/switch", "# expressions - which have th...
https://github.com/nodejs/nan/blob/8db8c8f544f2b6ce1b0859ef6ecdd0a3873a9e62/cpplint.py#L3177-L3251
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/psro_v2/meta_strategies.py
python
uniform_strategy
(solver, return_joint=False)
Returns a Random Uniform distribution on policies. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: uniform distribution on strategies.
Returns a Random Uniform distribution on policies.
[ "Returns", "a", "Random", "Uniform", "distribution", "on", "policies", "." ]
def uniform_strategy(solver, return_joint=False): """Returns a Random Uniform distribution on policies. Args: solver: GenPSROSolver instance. return_joint: If true, only returns marginals. Otherwise marginals as well as joint probabilities. Returns: uniform distribution on strategies. """ policies = solver.get_policies() policy_lengths = [len(pol) for pol in policies] result = [np.ones(pol_len) / pol_len for pol_len in policy_lengths] if not return_joint: return result else: joint_strategies = get_joint_strategy_from_marginals(result) return result, joint_strategies
[ "def", "uniform_strategy", "(", "solver", ",", "return_joint", "=", "False", ")", ":", "policies", "=", "solver", ".", "get_policies", "(", ")", "policy_lengths", "=", "[", "len", "(", "pol", ")", "for", "pol", "in", "policies", "]", "result", "=", "[", ...
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/psro_v2/meta_strategies.py#L28-L46
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/feature_extraction/text.py
python
CountVectorizer.get_feature_names
(self)
return [t for t, i in sorted(six.iteritems(self.vocabulary_), key=itemgetter(1))]
Array mapping from feature integer indices to feature name
Array mapping from feature integer indices to feature name
[ "Array", "mapping", "from", "feature", "integer", "indices", "to", "feature", "name" ]
def get_feature_names(self): """Array mapping from feature integer indices to feature name""" self._check_vocabulary() return [t for t, i in sorted(six.iteritems(self.vocabulary_), key=itemgetter(1))]
[ "def", "get_feature_names", "(", "self", ")", ":", "self", ".", "_check_vocabulary", "(", ")", "return", "[", "t", "for", "t", ",", "i", "in", "sorted", "(", "six", ".", "iteritems", "(", "self", ".", "vocabulary_", ")", ",", "key", "=", "itemgetter", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/feature_extraction/text.py#L928-L933
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/adaptors/paraview/pv_explorers.py
python
Camera.execute
(self, document)
moves camera into position for the current phi, theta value
moves camera into position for the current phi, theta value
[ "moves", "camera", "into", "position", "for", "the", "current", "phi", "theta", "value" ]
def execute(self, document): """moves camera into position for the current phi, theta value""" theta = document.descriptor['theta'] phi = document.descriptor['phi'] theta_rad = float(theta) / 180.0 * math.pi phi_rad = float(phi) / 180.0 * math.pi pos = [ math.cos(phi_rad) * self.distance * math.cos(theta_rad), math.sin(phi_rad) * self.distance * math.cos(theta_rad), math.sin(theta_rad) * self.distance ] up = [ + math.cos(phi_rad) * math.sin(theta_rad), - math.sin(phi_rad) * math.sin(theta_rad), + math.cos(theta_rad) ] for i in range(self.offset): pos.insert(0, pos.pop()) up.insert(0, up.pop()) pos[0] = float(self.center[0]) - pos[0] pos[1] = float(self.center[1]) + pos[1] pos[2] = float(self.center[2]) + pos[2] self.view.CameraPosition = pos self.view.CameraViewUp = up self.view.CameraFocalPoint = self.center
[ "def", "execute", "(", "self", ",", "document", ")", ":", "theta", "=", "document", ".", "descriptor", "[", "'theta'", "]", "phi", "=", "document", ".", "descriptor", "[", "'phi'", "]", "theta_rad", "=", "float", "(", "theta", ")", "/", "180.0", "*", ...
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/adaptors/paraview/pv_explorers.py#L305-L331
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
RigidObjectModel.setTransform
(self, R, t)
return _robotsim.RigidObjectModel_setTransform(self, R, t)
setTransform(RigidObjectModel self, double const [9] R, double const [3] t) Sets the rotation / translation (R,t) of the rigid object.
setTransform(RigidObjectModel self, double const [9] R, double const [3] t)
[ "setTransform", "(", "RigidObjectModel", "self", "double", "const", "[", "9", "]", "R", "double", "const", "[", "3", "]", "t", ")" ]
def setTransform(self, R, t): """ setTransform(RigidObjectModel self, double const [9] R, double const [3] t) Sets the rotation / translation (R,t) of the rigid object. """ return _robotsim.RigidObjectModel_setTransform(self, R, t)
[ "def", "setTransform", "(", "self", ",", "R", ",", "t", ")", ":", "return", "_robotsim", ".", "RigidObjectModel_setTransform", "(", "self", ",", "R", ",", "t", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L5473-L5482
cztomczak/cefpython
5679f28cec18a57a56e298da2927aac8d8f83ad6
tools/automate-git.py
python
get_chromium_versions
(commit)
return None
Returns the list of Chromium versions that contain the specified commit. Versions are listed oldest to newest.
Returns the list of Chromium versions that contain the specified commit. Versions are listed oldest to newest.
[ "Returns", "the", "list", "of", "Chromium", "versions", "that", "contain", "the", "specified", "commit", ".", "Versions", "are", "listed", "oldest", "to", "newest", "." ]
def get_chromium_versions(commit): """ Returns the list of Chromium versions that contain the specified commit. Versions are listed oldest to newest. """ cmd = '%s tag --contains %s' % (git_exe, commit) result = exec_cmd(cmd, chromium_src_dir) if result['out'] != '': return [line.strip() for line in result['out'].strip().split('\n')] return None
[ "def", "get_chromium_versions", "(", "commit", ")", ":", "cmd", "=", "'%s tag --contains %s'", "%", "(", "git_exe", ",", "commit", ")", "result", "=", "exec_cmd", "(", "cmd", ",", "chromium_src_dir", ")", "if", "result", "[", "'out'", "]", "!=", "''", ":",...
https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/automate-git.py#L531-L538
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/expressions/constants/constant.py
python
Constant.shape
(self)
return self._shape
Returns the (row, col) dimensions of the expression.
Returns the (row, col) dimensions of the expression.
[ "Returns", "the", "(", "row", "col", ")", "dimensions", "of", "the", "expression", "." ]
def shape(self) -> Tuple[int, ...]: """Returns the (row, col) dimensions of the expression. """ return self._shape
[ "def", "shape", "(", "self", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "return", "self", ".", "_shape" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/expressions/constants/constant.py#L103-L106
alexgkendall/caffe-segnet
344c113bf1832886f1cbe9f33ffe28a3beeaf412
scripts/cpp_lint.py
python
FindNextMultiLineCommentStart
(lines, lineix)
return len(lines)
Find the beginning marker for a multiline comment.
Find the beginning marker for a multiline comment.
[ "Find", "the", "beginning", "marker", "for", "a", "multiline", "comment", "." ]
def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'/*'", ")", ":", "# Only return this...
https://github.com/alexgkendall/caffe-segnet/blob/344c113bf1832886f1cbe9f33ffe28a3beeaf412/scripts/cpp_lint.py#L1123-L1131
etotheipi/BitcoinArmory
2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98
urllib3/packages/ordered_dict.py
python
OrderedDict.__repr__
(self, _repr_running={})
od.__repr__() <==> repr(od)
od.__repr__() <==> repr(od)
[ "od", ".", "__repr__", "()", "<", "==", ">", "repr", "(", "od", ")" ]
def __repr__(self, _repr_running={}): 'od.__repr__() <==> repr(od)' call_key = id(self), _get_ident() if call_key in _repr_running: return '...' _repr_running[call_key] = 1 try: if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key]
[ "def", "__repr__", "(", "self", ",", "_repr_running", "=", "{", "}", ")", ":", "call_key", "=", "id", "(", "self", ")", ",", "_get_ident", "(", ")", "if", "call_key", "in", "_repr_running", ":", "return", "'...'", "_repr_running", "[", "call_key", "]", ...
https://github.com/etotheipi/BitcoinArmory/blob/2a6fc5355bb0c6fe26e387ccba30a5baafe8cd98/urllib3/packages/ordered_dict.py#L198-L209
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/series.py
python
Series.dtype
(self)
return self._mgr.dtype
Return the dtype object of the underlying data.
Return the dtype object of the underlying data.
[ "Return", "the", "dtype", "object", "of", "the", "underlying", "data", "." ]
def dtype(self) -> DtypeObj: """ Return the dtype object of the underlying data. """ return self._mgr.dtype
[ "def", "dtype", "(", "self", ")", "->", "DtypeObj", ":", "return", "self", ".", "_mgr", ".", "dtype" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/series.py#L563-L567
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/__init__.py
python
RegenerateFlags
(options)
return flags
Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.) Any path options will be normalized relative to depth. The format flag is not included, as it is assumed the calling generator will set that as appropriate.
Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.)
[ "Given", "a", "parsed", "options", "object", "and", "taking", "the", "environment", "variables", "into", "account", "returns", "a", "list", "of", "flags", "that", "should", "regenerate", "an", "equivalent", "options", "object", "(", "even", "in", "the", "absen...
def RegenerateFlags(options): """Given a parsed options object, and taking the environment variables into account, returns a list of flags that should regenerate an equivalent options object (even in the absence of the environment variables.) Any path options will be normalized relative to depth. The format flag is not included, as it is assumed the calling generator will set that as appropriate. """ def FixPath(path): path = gyp.common.FixIfRelativePath(path, options.depth) if not path: return os.path.curdir return path def Noop(value): return value # We always want to ignore the environment when regenerating, to avoid # duplicate or changed flags in the environment at the time of regeneration. flags = ['--ignore-environment'] for name, metadata in options._regeneration_metadata.iteritems(): opt = metadata['opt'] value = getattr(options, name) value_predicate = metadata['type'] == 'path' and FixPath or Noop action = metadata['action'] env_name = metadata['env_name'] if action == 'append': flags.extend(RegenerateAppendFlag(opt, value, value_predicate, env_name, options)) elif action in ('store', None): # None is a synonym for 'store'. if value: flags.append(FormatOpt(opt, value_predicate(value))) elif options.use_environment and env_name and os.environ.get(env_name): flags.append(FormatOpt(opt, value_predicate(os.environ.get(env_name)))) elif action in ('store_true', 'store_false'): if ((action == 'store_true' and value) or (action == 'store_false' and not value)): flags.append(opt) elif options.use_environment and env_name: print >>sys.stderr, ('Warning: environment regeneration unimplemented ' 'for %s flag %r env_name %r' % (action, opt, env_name)) else: print >>sys.stderr, ('Warning: regeneration unimplemented for action %r ' 'flag %r' % (action, opt)) return flags
[ "def", "RegenerateFlags", "(", "options", ")", ":", "def", "FixPath", "(", "path", ")", ":", "path", "=", "gyp", ".", "common", ".", "FixIfRelativePath", "(", "path", ",", "options", ".", "depth", ")", "if", "not", "path", ":", "return", "os", ".", "...
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/__init__.py#L191-L239
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/centre_finder.py
python
PositionProviderFactory.get_increment_coord1_angle
(self, reducer, tolerance)
return tolerance/distance
Estimate an increment for the angle based on the specified coord1 increment for linear displacements and the distance from the sample to the detector. For a distance D and an increment dx, we estimate dAlpha to be tan(dAlpha)=dx/D. Since D >> dx, we can use Taylor expansion to set dAlpha = dx/D @param reducer: the reducer object @param tolerance: the tolerance
Estimate an increment for the angle based on the specified coord1 increment for linear displacements and the distance from the sample to the detector. For a distance D and an increment dx, we estimate dAlpha to be tan(dAlpha)=dx/D. Since D >> dx, we can use Taylor expansion to set dAlpha = dx/D
[ "Estimate", "an", "increment", "for", "the", "angle", "based", "on", "the", "specified", "coord1", "increment", "for", "linear", "displacements", "and", "the", "distance", "from", "the", "sample", "to", "the", "detector", ".", "For", "a", "distance", "D", "a...
def get_increment_coord1_angle(self, reducer, tolerance): ''' Estimate an increment for the angle based on the specified coord1 increment for linear displacements and the distance from the sample to the detector. For a distance D and an increment dx, we estimate dAlpha to be tan(dAlpha)=dx/D. Since D >> dx, we can use Taylor expansion to set dAlpha = dx/D @param reducer: the reducer object @param tolerance: the tolerance ''' workspace_name = reducer.get_sample().wksp_name workspace = mtd[workspace_name] instrument = workspace.getInstrument() detector_name = reducer.instrument.cur_detector().name() sample = instrument.getSample() component = instrument.getComponentByName(detector_name) # We use here the first detector entry. Do we need to have this smarter in the future? detector_bench = component[0] distance = detector_bench.getDistance(sample) return tolerance/distance
[ "def", "get_increment_coord1_angle", "(", "self", ",", "reducer", ",", "tolerance", ")", ":", "workspace_name", "=", "reducer", ".", "get_sample", "(", ")", ".", "wksp_name", "workspace", "=", "mtd", "[", "workspace_name", "]", "instrument", "=", "workspace", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/centre_finder.py#L538-L560
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py
python
zip_dir
(directory)
return result
zip a directory tree into a BytesIO object
zip a directory tree into a BytesIO object
[ "zip", "a", "directory", "tree", "into", "a", "BytesIO", "object" ]
def zip_dir(directory): """zip a directory tree into a BytesIO object""" result = io.BytesIO() dlen = len(directory) with ZipFile(result, "w") as zf: for root, dirs, files in os.walk(directory): for name in files: full = os.path.join(root, name) rel = root[dlen:] dest = os.path.join(rel, name) zf.write(full, dest) return result
[ "def", "zip_dir", "(", "directory", ")", ":", "result", "=", "io", ".", "BytesIO", "(", ")", "dlen", "=", "len", "(", "directory", ")", "with", "ZipFile", "(", "result", ",", "\"w\"", ")", "as", "zf", ":", "for", "root", ",", "dirs", ",", "files", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py#L1086-L1097
stan-dev/math
5fd79f89933269a4ca4d8dd1fde2a36d53d4768c
lib/boost_1.75.0/tools/build/src/build/targets.py
python
TargetRegistry.main_target_requirements
(self, specification, project)
return requirements
Returns the requirement to use when declaring a main target, which are obtained by - translating all specified property paths, and - refining project requirements with the one specified for the target 'specification' are the properties xplicitly specified for a main target 'project' is the project where the main taret is to be declared.
Returns the requirement to use when declaring a main target, which are obtained by - translating all specified property paths, and - refining project requirements with the one specified for the target
[ "Returns", "the", "requirement", "to", "use", "when", "declaring", "a", "main", "target", "which", "are", "obtained", "by", "-", "translating", "all", "specified", "property", "paths", "and", "-", "refining", "project", "requirements", "with", "the", "one", "s...
def main_target_requirements(self, specification, project): """Returns the requirement to use when declaring a main target, which are obtained by - translating all specified property paths, and - refining project requirements with the one specified for the target 'specification' are the properties xplicitly specified for a main target 'project' is the project where the main taret is to be declared.""" assert is_iterable_typed(specification, basestring) assert isinstance(project, ProjectTarget) # create a copy since the list is being modified specification = list(specification) specification.extend(toolset.requirements()) requirements = property_set.refine_from_user_input( project.get("requirements"), specification, project.project_module(), project.get("location")) return requirements
[ "def", "main_target_requirements", "(", "self", ",", "specification", ",", "project", ")", ":", "assert", "is_iterable_typed", "(", "specification", ",", "basestring", ")", "assert", "isinstance", "(", "project", ",", "ProjectTarget", ")", "# create a copy since the l...
https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/targets.py#L148-L167
limbo018/DREAMPlace
146c3b9fd003d1acd52c96d9fd02e3f0a05154e4
dreamplace/ops/electric_potential/electric_potential.py
python
ElectricPotential.__init__
( self, node_size_x, node_size_y, bin_center_x, bin_center_y, target_density, xl, yl, xh, yh, bin_size_x, bin_size_y, num_movable_nodes, num_terminals, num_filler_nodes, padding, deterministic_flag, # control whether to use deterministic routine sorted_node_map, movable_macro_mask=None, fast_mode=False, region_id=None, fence_regions=None, # [n_subregion, 4] as dummy macros added to initial density. (xl,yl,xh,yh) rectangles node2fence_region_map=None, placedb=None )
@brief initialization Be aware that all scalars must be python type instead of tensors. Otherwise, GPU version can be weirdly slow. @param node_size_x cell width array consisting of movable cells, fixed cells, and filler cells in order @param node_size_y cell height array consisting of movable cells, fixed cells, and filler cells in order @param movable_macro_mask some large movable macros need to be scaled to avoid halos @param bin_center_x bin center x locations @param bin_center_y bin center y locations @param target_density target density @param xl left boundary @param yl bottom boundary @param xh right boundary @param yh top boundary @param bin_size_x bin width @param bin_size_y bin height @param num_movable_nodes number of movable cells @param num_terminals number of fixed cells @param num_filler_nodes number of filler cells @param padding bin padding to boundary of placement region @param deterministic_flag control whether to use deterministic routine @param fast_mode if true, only gradient is computed, while objective computation is skipped @param region_id id for fence region, from 0 to N if there are N fence regions @param fence_regions # [n_subregion, 4] as dummy macros added to initial density. (xl,yl,xh,yh) rectangles @param node2fence_region_map node to region id map, non fence region is set to INT_MAX @param placedb
[]
def __init__( self, node_size_x, node_size_y, bin_center_x, bin_center_y, target_density, xl, yl, xh, yh, bin_size_x, bin_size_y, num_movable_nodes, num_terminals, num_filler_nodes, padding, deterministic_flag, # control whether to use deterministic routine sorted_node_map, movable_macro_mask=None, fast_mode=False, region_id=None, fence_regions=None, # [n_subregion, 4] as dummy macros added to initial density. (xl,yl,xh,yh) rectangles node2fence_region_map=None, placedb=None ): """ @brief initialization Be aware that all scalars must be python type instead of tensors. Otherwise, GPU version can be weirdly slow. @param node_size_x cell width array consisting of movable cells, fixed cells, and filler cells in order @param node_size_y cell height array consisting of movable cells, fixed cells, and filler cells in order @param movable_macro_mask some large movable macros need to be scaled to avoid halos @param bin_center_x bin center x locations @param bin_center_y bin center y locations @param target_density target density @param xl left boundary @param yl bottom boundary @param xh right boundary @param yh top boundary @param bin_size_x bin width @param bin_size_y bin height @param num_movable_nodes number of movable cells @param num_terminals number of fixed cells @param num_filler_nodes number of filler cells @param padding bin padding to boundary of placement region @param deterministic_flag control whether to use deterministic routine @param fast_mode if true, only gradient is computed, while objective computation is skipped @param region_id id for fence region, from 0 to N if there are N fence regions @param fence_regions # [n_subregion, 4] as dummy macros added to initial density. (xl,yl,xh,yh) rectangles @param node2fence_region_map node to region id map, non fence region is set to INT_MAX @param placedb """ if(region_id is not None): ### reconstruct data structure num_nodes = placedb.num_nodes if(region_id < len(placedb.regions)): self.fence_region_mask = node2fence_region_map[:num_movable_nodes] == region_id else: self.fence_region_mask = node2fence_region_map[:num_movable_nodes] >= len(placedb.regions) node_size_x = torch.cat([node_size_x[:num_movable_nodes][self.fence_region_mask], node_size_x[num_movable_nodes:num_nodes-num_filler_nodes], node_size_x[num_nodes-num_filler_nodes+placedb.filler_start_map[region_id]:num_nodes-num_filler_nodes+placedb.filler_start_map[region_id+1]]], 0) node_size_y = torch.cat([node_size_y[:num_movable_nodes][self.fence_region_mask], node_size_y[num_movable_nodes:num_nodes-num_filler_nodes], node_size_y[num_nodes-num_filler_nodes+placedb.filler_start_map[region_id]:num_nodes-num_filler_nodes+placedb.filler_start_map[region_id+1]]], 0) num_movable_nodes = (self.fence_region_mask).long().sum().item() num_filler_nodes = placedb.filler_start_map[region_id+1]-placedb.filler_start_map[region_id] if(movable_macro_mask is not None): movable_macro_mask = movable_macro_mask[self.fence_region_mask] ## sorted cell is recomputed sorted_node_map = torch.sort(node_size_x[:num_movable_nodes])[1].to(torch.int32) ## make pos mask for fast forward self.pos_mask = torch.zeros(2, placedb.num_nodes, dtype=torch.bool, device=node_size_x.device) self.pos_mask[0,:placedb.num_movable_nodes].masked_fill_(self.fence_region_mask, 1) self.pos_mask[1,:placedb.num_movable_nodes].masked_fill_(self.fence_region_mask, 1) self.pos_mask[:,placedb.num_movable_nodes:placedb.num_nodes-placedb.num_filler_nodes] = 1 self.pos_mask[:,placedb.num_nodes-placedb.num_filler_nodes+placedb.filler_start_map[region_id]:placedb.num_nodes-placedb.num_filler_nodes+placedb.filler_start_map[region_id+1]] = 1 self.pos_mask = self.pos_mask.view(-1) super(ElectricPotential, self).__init__(node_size_x=node_size_x, node_size_y=node_size_y, bin_center_x=bin_center_x, bin_center_y=bin_center_y, target_density=target_density, xl=xl, yl=yl, xh=xh, yh=yh, bin_size_x=bin_size_x, bin_size_y=bin_size_y, num_movable_nodes=num_movable_nodes, num_terminals=num_terminals, num_filler_nodes=num_filler_nodes, padding=padding, deterministic_flag=deterministic_flag, sorted_node_map=sorted_node_map, movable_macro_mask=movable_macro_mask) self.fast_mode = fast_mode self.fence_regions = fence_regions self.node2fence_region_map = node2fence_region_map self.placedb = placedb self.target_density = target_density self.region_id = region_id ## set by build_density_op func self.filler_start_map = None self.filler_beg = None self.filler_end = None
[ "def", "__init__", "(", "self", ",", "node_size_x", ",", "node_size_y", ",", "bin_center_x", ",", "bin_center_y", ",", "target_density", ",", "xl", ",", "yl", ",", "xh", ",", "yh", ",", "bin_size_x", ",", "bin_size_y", ",", "num_movable_nodes", ",", "num_ter...
https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/ops/electric_potential/electric_potential.py#L281-L392