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
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
CheckAltTokens
(filename, clean_lines, linenum, error)
Check alternative keywords being used in boolean expressions. 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.
Check alternative keywords being used in boolean expressions.
[ "Check", "alternative", "keywords", "being", "used", "in", "boolean", "expressions", "." ]
def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. 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] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
[ "def", "CheckAltTokens", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Avoid preprocessor lines", "if", "Match", "(", "r'^\\s*#'", ",", "line", ")", ":", "retur...
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L3409-L3438
VelsonWang/HmiFuncDesigner
439265da17bd3424e678932cbfbc0237b52630f3
HmiFuncDesigner/libs/qscintilla/Python/configure.py
python
quote
(path)
return path
Return a path with quotes added if it contains spaces. path is the path.
Return a path with quotes added if it contains spaces. path is the path.
[ "Return", "a", "path", "with", "quotes", "added", "if", "it", "contains", "spaces", ".", "path", "is", "the", "path", "." ]
def quote(path): """ Return a path with quotes added if it contains spaces. path is the path. """ if ' ' in path: path = '"%s"' % path return path
[ "def", "quote", "(", "path", ")", ":", "if", "' '", "in", "path", ":", "path", "=", "'\"%s\"'", "%", "path", "return", "path" ]
https://github.com/VelsonWang/HmiFuncDesigner/blob/439265da17bd3424e678932cbfbc0237b52630f3/HmiFuncDesigner/libs/qscintilla/Python/configure.py#L361-L369
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros/rosunit/src/rosunit/xmlrunner.py
python
_TestInfo.create_error
(test, time, error)
return info
Create a _TestInfo instance for an erroneous test.
Create a _TestInfo instance for an erroneous test.
[ "Create", "a", "_TestInfo", "instance", "for", "an", "erroneous", "test", "." ]
def create_error(test, time, error): """Create a _TestInfo instance for an erroneous test.""" info = _TestInfo(test, time) info._error = error return info
[ "def", "create_error", "(", "test", ",", "time", ",", "error", ")", ":", "info", "=", "_TestInfo", "(", "test", ",", "time", ")", "info", ".", "_error", "=", "error", "return", "info" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/rosunit/src/rosunit/xmlrunner.py#L52-L56
tensorflow/ngraph-bridge
ea6422491ec75504e78a63db029e7f74ec3479a5
examples/retrain_ngraph.py
python
save_graph_to_file
(graph_file_name, module_spec, class_count)
Saves an graph to file, creating a valid quantized one if necessary.
Saves an graph to file, creating a valid quantized one if necessary.
[ "Saves", "an", "graph", "to", "file", "creating", "a", "valid", "quantized", "one", "if", "necessary", "." ]
def save_graph_to_file(graph_file_name, module_spec, class_count): """Saves an graph to file, creating a valid quantized one if necessary.""" sess, _, _, _, _, _ = build_eval_session(module_spec, class_count) graph = sess.graph output_graph_def = tf.graph_util.convert_variables_to_constants( sess, graph.as_graph_def(), [FLAGS.final_tensor_name]) with tf.gfile.GFile(graph_file_name, 'wb') as f: f.write(output_graph_def.SerializeToString())
[ "def", "save_graph_to_file", "(", "graph_file_name", ",", "module_spec", ",", "class_count", ")", ":", "sess", ",", "_", ",", "_", ",", "_", ",", "_", ",", "_", "=", "build_eval_session", "(", "module_spec", ",", "class_count", ")", "graph", "=", "sess", ...
https://github.com/tensorflow/ngraph-bridge/blob/ea6422491ec75504e78a63db029e7f74ec3479a5/examples/retrain_ngraph.py#L939-L948
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
ci/checks/gitutils.py
python
listFilesToCheck
(filesDirs, filter=None)
return allFiles
Utility function to filter the input list of files/dirs based on the input filter method and returns all the files that need to be checked
Utility function to filter the input list of files/dirs based on the input filter method and returns all the files that need to be checked
[ "Utility", "function", "to", "filter", "the", "input", "list", "of", "files", "/", "dirs", "based", "on", "the", "input", "filter", "method", "and", "returns", "all", "the", "files", "that", "need", "to", "be", "checked" ]
def listFilesToCheck(filesDirs, filter=None): """ Utility function to filter the input list of files/dirs based on the input filter method and returns all the files that need to be checked """ allFiles = [] for f in filesDirs: if os.path.isfile(f): if filter is None or filter(f): allFiles.append(f) elif os.path.isdir(f): files = listAllFilesInDir(f) for f_ in files: if filter is None or filter(f_): allFiles.append(f_) return allFiles
[ "def", "listFilesToCheck", "(", "filesDirs", ",", "filter", "=", "None", ")", ":", "allFiles", "=", "[", "]", "for", "f", "in", "filesDirs", ":", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", ":", "if", "filter", "is", "None", "or", "filte...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/ci/checks/gitutils.py#L271-L286
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.get_backbone_router_jitter
(self)
return self.__parse_int(self.execute_command('bbr jitter'))
Get jitter (in seconds) for Backbone Router registration for Thread 1.2 FTD.
Get jitter (in seconds) for Backbone Router registration for Thread 1.2 FTD.
[ "Get", "jitter", "(", "in", "seconds", ")", "for", "Backbone", "Router", "registration", "for", "Thread", "1", ".", "2", "FTD", "." ]
def get_backbone_router_jitter(self) -> int: """Get jitter (in seconds) for Backbone Router registration for Thread 1.2 FTD.""" return self.__parse_int(self.execute_command('bbr jitter'))
[ "def", "get_backbone_router_jitter", "(", "self", ")", "->", "int", ":", "return", "self", ".", "__parse_int", "(", "self", ".", "execute_command", "(", "'bbr jitter'", ")", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L2062-L2064
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/internal/encoder.py
python
_TagSize
(field_number)
return _VarintSize(wire_format.PackTag(field_number, 0))
Returns the number of bytes required to serialize a tag with this field number.
Returns the number of bytes required to serialize a tag with this field number.
[ "Returns", "the", "number", "of", "bytes", "required", "to", "serialize", "a", "tag", "with", "this", "field", "number", "." ]
def _TagSize(field_number): """Returns the number of bytes required to serialize a tag with this field number.""" # Just pass in type 0, since the type won't affect the tag+type size. return _VarintSize(wire_format.PackTag(field_number, 0))
[ "def", "_TagSize", "(", "field_number", ")", ":", "# Just pass in type 0, since the type won't affect the tag+type size.", "return", "_VarintSize", "(", "wire_format", ".", "PackTag", "(", "field_number", ",", "0", ")", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/encoder.py#L111-L115
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
PreToolBar
(*args, **kwargs)
return val
PreToolBar() -> ToolBar
PreToolBar() -> ToolBar
[ "PreToolBar", "()", "-", ">", "ToolBar" ]
def PreToolBar(*args, **kwargs): """PreToolBar() -> ToolBar""" val = _controls_.new_PreToolBar(*args, **kwargs) return val
[ "def", "PreToolBar", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_controls_", ".", "new_PreToolBar", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L3983-L3986
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/accessor.py
python
PandasDelegate._add_delegate_accessors
( cls, delegate, accessors, typ: str, overwrite: bool = False )
Add accessors to cls from the delegate class. Parameters ---------- cls Class to add the methods/properties to. delegate Class to get methods/properties and doc-strings. accessors : list of str List of accessors to add. typ : {'property', 'method'} overwrite : bool, default False Overwrite the method/property in the target class if it exists.
Add accessors to cls from the delegate class.
[ "Add", "accessors", "to", "cls", "from", "the", "delegate", "class", "." ]
def _add_delegate_accessors( cls, delegate, accessors, typ: str, overwrite: bool = False ): """ Add accessors to cls from the delegate class. Parameters ---------- cls Class to add the methods/properties to. delegate Class to get methods/properties and doc-strings. accessors : list of str List of accessors to add. typ : {'property', 'method'} overwrite : bool, default False Overwrite the method/property in the target class if it exists. """ def _create_delegator_property(name): def _getter(self): return self._delegate_property_get(name) def _setter(self, new_values): return self._delegate_property_set(name, new_values) _getter.__name__ = name _setter.__name__ = name return property( fget=_getter, fset=_setter, doc=getattr(delegate, name).__doc__ ) def _create_delegator_method(name): def f(self, *args, **kwargs): return self._delegate_method(name, *args, **kwargs) f.__name__ = name f.__doc__ = getattr(delegate, name).__doc__ return f for name in accessors: if typ == "property": f = _create_delegator_property(name) else: f = _create_delegator_method(name) # don't overwrite existing methods/properties if overwrite or not hasattr(cls, name): setattr(cls, name, f)
[ "def", "_add_delegate_accessors", "(", "cls", ",", "delegate", ",", "accessors", ",", "typ", ":", "str", ",", "overwrite", ":", "bool", "=", "False", ")", ":", "def", "_create_delegator_property", "(", "name", ")", ":", "def", "_getter", "(", "self", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/accessor.py#L58-L109
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/computation/scope.py
python
Scope.full_scope
(self)
return DeepChainMap(*maps)
Return the full scope for use with passing to engines transparently as a mapping. Returns ------- vars : DeepChainMap All variables in this scope.
Return the full scope for use with passing to engines transparently as a mapping.
[ "Return", "the", "full", "scope", "for", "use", "with", "passing", "to", "engines", "transparently", "as", "a", "mapping", "." ]
def full_scope(self): """ Return the full scope for use with passing to engines transparently as a mapping. Returns ------- vars : DeepChainMap All variables in this scope. """ maps = [self.temps] + self.resolvers.maps + self.scope.maps return DeepChainMap(*maps)
[ "def", "full_scope", "(", "self", ")", ":", "maps", "=", "[", "self", ".", "temps", "]", "+", "self", ".", "resolvers", ".", "maps", "+", "self", ".", "scope", ".", "maps", "return", "DeepChainMap", "(", "*", "maps", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/computation/scope.py#L303-L314
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/distutils/sysconfig.py
python
customize_compiler
(compiler)
Do any platform-specific customization of a CCompiler instance. Mainly needed on Unix, so we can plug in the information that varies across Unices and is stored in Python's Makefile.
Do any platform-specific customization of a CCompiler instance.
[ "Do", "any", "platform", "-", "specific", "customization", "of", "a", "CCompiler", "instance", "." ]
def customize_compiler(compiler): """Do any platform-specific customization of a CCompiler instance. Mainly needed on Unix, so we can plug in the information that varies across Unices and is stored in Python's Makefile. """ if compiler.compiler_type == "unix": if sys.platform == "darwin": # Perform first-time customization of compiler-related # config vars on OS X now that we know we need a compiler. # This is primarily to support Pythons from binary # installers. The kind and paths to build tools on # the user system may vary significantly from the system # that Python itself was built on. Also the user OS # version and build tools may not support the same set # of CPU architectures for universal builds. global _config_vars # Use get_config_var() to ensure _config_vars is initialized. if not get_config_var('CUSTOMIZED_OSX_COMPILER'): import _osx_support _osx_support.customize_compiler(_config_vars) _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True' (cc, cxx, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \ get_config_vars('CC', 'CXX', 'CFLAGS', 'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS') if 'CC' in os.environ: newcc = os.environ['CC'] if (sys.platform == 'darwin' and 'LDSHARED' not in os.environ and ldshared.startswith(cc)): # On OS X, if CC is overridden, use that as the default # command for LDSHARED as well ldshared = newcc + ldshared[len(cc):] cc = newcc if 'CXX' in os.environ: cxx = os.environ['CXX'] if 'LDSHARED' in os.environ: ldshared = os.environ['LDSHARED'] if 'CPP' in os.environ: cpp = os.environ['CPP'] else: cpp = cc + " -E" # not always if 'LDFLAGS' in os.environ: ldshared = ldshared + ' ' + os.environ['LDFLAGS'] if 'CFLAGS' in os.environ: cflags = cflags + ' ' + os.environ['CFLAGS'] ldshared = ldshared + ' ' + os.environ['CFLAGS'] if 'CPPFLAGS' in os.environ: cpp = cpp + ' ' + os.environ['CPPFLAGS'] cflags = cflags + ' ' + os.environ['CPPFLAGS'] ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] if 'AR' in os.environ: ar = os.environ['AR'] if 'ARFLAGS' in os.environ: archiver = ar + ' ' + os.environ['ARFLAGS'] else: archiver = ar + ' ' + ar_flags cc_cmd = cc + ' ' + cflags compiler.set_executables( preprocessor=cpp, compiler=cc_cmd, compiler_so=cc_cmd + ' ' + ccshared, compiler_cxx=cxx, linker_so=ldshared, linker_exe=cc, archiver=archiver) compiler.shared_lib_extension = shlib_suffix
[ "def", "customize_compiler", "(", "compiler", ")", ":", "if", "compiler", ".", "compiler_type", "==", "\"unix\"", ":", "if", "sys", ".", "platform", "==", "\"darwin\"", ":", "# Perform first-time customization of compiler-related", "# config vars on OS X now that we know we...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/distutils/sysconfig.py#L168-L238
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
FlagValues._RegisterFlagByModuleId
(self, module_id, flag)
Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module.
Records the module that defines a specific flag.
[ "Records", "the", "module", "that", "defines", "a", "specific", "flag", "." ]
def _RegisterFlagByModuleId(self, module_id, flag): """Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag)
[ "def", "_RegisterFlagByModuleId", "(", "self", ",", "module_id", ",", "flag", ")", ":", "flags_by_module_id", "=", "self", ".", "FlagsByModuleIdDict", "(", ")", "flags_by_module_id", ".", "setdefault", "(", "module_id", ",", "[", "]", ")", ".", "append", "(", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L889-L897
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py
python
FieldStorage.read_lines_to_eof
(self)
Internal: read lines until EOF.
Internal: read lines until EOF.
[ "Internal", ":", "read", "lines", "until", "EOF", "." ]
def read_lines_to_eof(self): """Internal: read lines until EOF.""" while 1: line = self.fp.readline(1<<16) if not line: self.done = -1 break self.__write(line)
[ "def", "read_lines_to_eof", "(", "self", ")", ":", "while", "1", ":", "line", "=", "self", ".", "fp", ".", "readline", "(", "1", "<<", "16", ")", "if", "not", "line", ":", "self", ".", "done", "=", "-", "1", "break", "self", ".", "__write", "(", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/cgi.py#L680-L687
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py
python
_AddPrefix
(element, prefix)
Add |prefix| to |element| or each subelement if element is iterable.
Add |prefix| to |element| or each subelement if element is iterable.
[ "Add", "|prefix|", "to", "|element|", "or", "each", "subelement", "if", "element", "is", "iterable", "." ]
def _AddPrefix(element, prefix): """Add |prefix| to |element| or each subelement if element is iterable.""" if element is None: return element # Note, not Iterable because we don't want to handle strings like that. if isinstance(element, list) or isinstance(element, tuple): return [prefix + e for e in element] else: return prefix + element
[ "def", "_AddPrefix", "(", "element", ",", "prefix", ")", ":", "if", "element", "is", "None", ":", "return", "element", "# Note, not Iterable because we don't want to handle strings like that.", "if", "isinstance", "(", "element", ",", "list", ")", "or", "isinstance", ...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/msvs_emulation.py#L79-L87
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/cef_parser.py
python
obj_class.is_library_side
(self)
return self.attribs['source'] == 'library'
Returns true if the class is implemented by the library.
Returns true if the class is implemented by the library.
[ "Returns", "true", "if", "the", "class", "is", "implemented", "by", "the", "library", "." ]
def is_library_side(self): """ Returns true if the class is implemented by the library. """ return self.attribs['source'] == 'library'
[ "def", "is_library_side", "(", "self", ")", ":", "return", "self", ".", "attribs", "[", "'source'", "]", "==", "'library'" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/cef_parser.py#L1041-L1043
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py
python
GetAllIncludeDirectories
(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path)
return all_includes_list
Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options.
Calculate the set of include directories to be used.
[ "Calculate", "the", "set", "of", "include", "directories", "to", "be", "used", "." ]
def GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options. """ gyp_includes_set = set() compiler_includes_list = [] # Find compiler's default include dirs. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-xc++', '-v', '-']) proc = subprocess.Popen(args=command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate()[1] if PY3: output = output.decode('utf-8') # Extract the list of include dirs from the output, which has this format: # ... # #include "..." search starts here: # #include <...> search starts here: # /usr/include/c++/4.6 # /usr/local/include # End of search list. # ... in_include_list = False for line in output.splitlines(): if line.startswith('#include'): in_include_list = True continue if line.startswith('End of search list.'): break if in_include_list: include_dir = line.strip() if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if config_name in target['configurations']: config = target['configurations'][config_name] # Look for any include dirs that were explicitly added via cflags. This # may be done in gyp files to force certain includes to come at the end. # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and # remove this. if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) cflags = msvs_settings.GetCflags(config_name) else: cflags = config['cflags'] for cflag in cflags: if cflag.startswith('-I'): include_dir = cflag[2:] if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) # Find standard gyp include dirs. if 'include_dirs' in config: include_dirs = config['include_dirs'] for shared_intermediate_dir in shared_intermediate_dirs: for include_dir in include_dirs: include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR', shared_intermediate_dir) if not os.path.isabs(include_dir): base_dir = os.path.dirname(target_name) include_dir = base_dir + '/' + include_dir include_dir = os.path.abspath(include_dir) gyp_includes_set.add(include_dir) # Generate a list that has all the include dirs. all_includes_list = list(gyp_includes_set) all_includes_list.sort() for compiler_include in compiler_includes_list: if not compiler_include in gyp_includes_set: all_includes_list.append(compiler_include) # All done. return all_includes_list
[ "def", "GetAllIncludeDirectories", "(", "target_list", ",", "target_dicts", ",", "shared_intermediate_dirs", ",", "config_name", ",", "params", ",", "compiler_path", ")", ":", "gyp_includes_set", "=", "set", "(", ")", "compiler_includes_list", "=", "[", "]", "# Find...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py#L82-L170
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py
python
BucketizedColumn.num_buckets
(self)
return (len(self.boundaries) + 1) * self.source_column.shape[0]
See `CategoricalColumn` base class.
See `CategoricalColumn` base class.
[ "See", "CategoricalColumn", "base", "class", "." ]
def num_buckets(self): """See `CategoricalColumn` base class.""" # By construction, source_column is always one-dimensional. return (len(self.boundaries) + 1) * self.source_column.shape[0]
[ "def", "num_buckets", "(", "self", ")", ":", "# By construction, source_column is always one-dimensional.", "return", "(", "len", "(", "self", ".", "boundaries", ")", "+", "1", ")", "*", "self", ".", "source_column", ".", "shape", "[", "0", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L2948-L2951
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/context.py
python
Context.get_optimizer_experimental_options
(self)
return options
Get experimental options for the optimizer. Returns: Dictionary of current option values
Get experimental options for the optimizer.
[ "Get", "experimental", "options", "for", "the", "optimizer", "." ]
def get_optimizer_experimental_options(self): """Get experimental options for the optimizer. Returns: Dictionary of current option values """ rewrite_options = self.config.graph_options.rewrite_options options = {} def rewriter_toggle(option): attr = getattr(rewrite_options, option) if attr != 0: options[option] = (attr == rewriter_config_pb2.RewriterConfig.ON) def rewriter_bool(option): options[option] = getattr(rewrite_options, option) rewriter_toggle("layout_optimizer") rewriter_toggle("constant_folding") rewriter_toggle("shape_optimization") rewriter_toggle("remapping") rewriter_toggle("arithmetic_optimization") rewriter_toggle("dependency_optimization") rewriter_toggle("loop_optimization") rewriter_toggle("function_optimization") rewriter_toggle("debug_stripper") rewriter_bool("disable_model_pruning") rewriter_toggle("scoped_allocator_optimization") rewriter_toggle("pin_to_host_optimization") rewriter_toggle("implementation_selector") rewriter_toggle("auto_mixed_precision") rewriter_toggle("use_plugin_optimizers") rewriter_bool("disable_meta_optimizer") if rewrite_options.min_graph_nodes != 0: options["min_graph_nodes"] = rewrite_options.min_graph_nodes return options
[ "def", "get_optimizer_experimental_options", "(", "self", ")", ":", "rewrite_options", "=", "self", ".", "config", ".", "graph_options", ".", "rewrite_options", "options", "=", "{", "}", "def", "rewriter_toggle", "(", "option", ")", ":", "attr", "=", "getattr", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L1736-L1773
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_schema_compiler/h_generator.py
python
_Generator._GenerateFields
(self, props)
return c
Generates the field declarations when declaring a type.
Generates the field declarations when declaring a type.
[ "Generates", "the", "field", "declarations", "when", "declaring", "a", "type", "." ]
def _GenerateFields(self, props): """Generates the field declarations when declaring a type. """ c = Code() needs_blank_line = False for prop in props: if needs_blank_line: c.Append() needs_blank_line = True if prop.description: c.Comment(prop.description) # ANY is a base::Value which is abstract and cannot be a direct member, so # we always need to wrap it in a scoped_ptr. is_ptr = prop.optional or prop.type_.property_type == PropertyType.ANY (c.Append('%s %s;' % ( self._type_helper.GetCppType(prop.type_, is_ptr=is_ptr), prop.unix_name)) ) return c
[ "def", "_GenerateFields", "(", "self", ",", "props", ")", ":", "c", "=", "Code", "(", ")", "needs_blank_line", "=", "False", "for", "prop", "in", "props", ":", "if", "needs_blank_line", ":", "c", ".", "Append", "(", ")", "needs_blank_line", "=", "True", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/h_generator.py#L154-L172
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/google/protobuf/internal/decoder.py
python
MapDecoder
(field_descriptor, new_default, is_message_map)
return DecodeMap
Returns a decoder for a map field.
Returns a decoder for a map field.
[ "Returns", "a", "decoder", "for", "a", "map", "field", "." ]
def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field.""" key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarint # Can't read _concrete_class yet; might not be initialized. message_type = field_descriptor.message_type def DecodeMap(buffer, pos, end, message, field_dict): submsg = message_type._concrete_class() value = field_dict.get(key) if value is None: value = field_dict.setdefault(key, new_default(message)) while 1: # Read length. (size, pos) = local_DecodeVarint(buffer, pos) new_pos = pos + size if new_pos > end: raise _DecodeError('Truncated message.') # Read sub-message. submsg.Clear() if submsg._InternalParse(buffer, pos, new_pos) != new_pos: # The only reason _InternalParse would return early is if it # encountered an end-group tag. raise _DecodeError('Unexpected end-group tag.') if is_message_map: value[submsg.key].MergeFrom(submsg.value) else: value[submsg.key] = submsg.value # Predict that the next tag is another copy of the same repeated field. pos = new_pos + tag_len if buffer[new_pos:pos] != tag_bytes or new_pos == end: # Prediction failed. Return. return new_pos return DecodeMap
[ "def", "MapDecoder", "(", "field_descriptor", ",", "new_default", ",", "is_message_map", ")", ":", "key", "=", "field_descriptor", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_descriptor", ".", "number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMIT...
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/internal/decoder.py#L737-L777
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
Co-Simulation/PTV-Vissim/vissim_integration/carla_simulation.py
python
CarlaSimulation.tick
(self)
Tick to carla simulation.
Tick to carla simulation.
[ "Tick", "to", "carla", "simulation", "." ]
def tick(self): """ Tick to carla simulation. """ self.world.tick() # Update data structures for the current frame. current_actors = set( [vehicle.id for vehicle in self.world.get_actors().filter('vehicle.*')]) self.spawned_actors = current_actors.difference(self._active_actors) self.destroyed_actors = self._active_actors.difference(current_actors) self._active_actors = current_actors
[ "def", "tick", "(", "self", ")", ":", "self", ".", "world", ".", "tick", "(", ")", "# Update data structures for the current frame.", "current_actors", "=", "set", "(", "[", "vehicle", ".", "id", "for", "vehicle", "in", "self", ".", "world", ".", "get_actors...
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/Co-Simulation/PTV-Vissim/vissim_integration/carla_simulation.py#L103-L114
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/command/egg_info.py
python
FileList._remove_files
(self, predicate)
return found
Remove all files from the file list that match the predicate. Return True if any matching files were removed
Remove all files from the file list that match the predicate. Return True if any matching files were removed
[ "Remove", "all", "files", "from", "the", "file", "list", "that", "match", "the", "predicate", ".", "Return", "True", "if", "any", "matching", "files", "were", "removed" ]
def _remove_files(self, predicate): """ Remove all files from the file list that match the predicate. Return True if any matching files were removed """ found = False for i in range(len(self.files) - 1, -1, -1): if predicate(self.files[i]): self.debug_print(" removing " + self.files[i]) del self.files[i] found = True return found
[ "def", "_remove_files", "(", "self", ",", "predicate", ")", ":", "found", "=", "False", "for", "i", "in", "range", "(", "len", "(", "self", ".", "files", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "if", "predicate", "(", "self", "."...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/command/egg_info.py#L398-L409
moderngl/moderngl
32fe79927e02b0fa893b3603d677bdae39771e14
moderngl/mock.py
python
Implementation.create_context
(self, *args)
return (None, 0)
create_context
create_context
[ "create_context" ]
def create_context(self, *args) -> 'Context': ''' create_context ''' return (None, 0)
[ "def", "create_context", "(", "self", ",", "*", "args", ")", "->", "'Context'", ":", "return", "(", "None", ",", "0", ")" ]
https://github.com/moderngl/moderngl/blob/32fe79927e02b0fa893b3603d677bdae39771e14/moderngl/mock.py#L28-L33
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py
python
Complex.__pos__
(self)
+self
+self
[ "+", "self" ]
def __pos__(self): """+self""" raise NotImplementedError
[ "def", "__pos__", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/numbers.py#L88-L90
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/io/povray.py
python
render_to_animation
(properties,folder)
This will setup your properties dict to not call povray, but rather just generate a render script.
This will setup your properties dict to not call povray, but rather just generate a render script.
[ "This", "will", "setup", "your", "properties", "dict", "to", "not", "call", "povray", "but", "rather", "just", "generate", "a", "render", "script", "." ]
def render_to_animation(properties,folder): """This will setup your properties dict to not call povray, but rather just generate a render script. """ if not os.path.exists(folder): os.mkdir(folder) import re maxId=-1 for f in os.listdir(folder): if re.match('[0-9]+.pov',f): maxId=max(maxId,int(f[:len(f)-4])) maxId+=1 properties['tempfile']=folder+"/"+str(maxId)+".pov" properties['remove_temp']=False properties['outfile']=None
[ "def", "render_to_animation", "(", "properties", ",", "folder", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "folder", ")", ":", "os", ".", "mkdir", "(", "folder", ")", "import", "re", "maxId", "=", "-", "1", "for", "f", "in", "os"...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/io/povray.py#L391-L407
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/macosxSupport.py
python
setupApp
(root, flist)
Perform setup for the OSX application bundle.
Perform setup for the OSX application bundle.
[ "Perform", "setup", "for", "the", "OSX", "application", "bundle", "." ]
def setupApp(root, flist): """ Perform setup for the OSX application bundle. """ if not runningAsOSXApp(): return hideTkConsole(root) overrideRootMenu(root, flist) addOpenEventSupport(root, flist)
[ "def", "setupApp", "(", "root", ",", "flist", ")", ":", "if", "not", "runningAsOSXApp", "(", ")", ":", "return", "hideTkConsole", "(", "root", ")", "overrideRootMenu", "(", "root", ",", "flist", ")", "addOpenEventSupport", "(", "root", ",", "flist", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/idlelib/macosxSupport.py#L167-L175
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
tools/coreml/converter/_layers.py
python
convert_reshape
(net, node, module, builder)
Converts a reshape layer from mxnet to coreml. This doesn't currently handle the deprecated parameters for the reshape layer. Parameters ---------- network: net An mxnet network object. layer: node Node to convert. module: module A module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
Converts a reshape layer from mxnet to coreml.
[ "Converts", "a", "reshape", "layer", "from", "mxnet", "to", "coreml", "." ]
def convert_reshape(net, node, module, builder): """Converts a reshape layer from mxnet to coreml. This doesn't currently handle the deprecated parameters for the reshape layer. Parameters ---------- network: net An mxnet network object. layer: node Node to convert. module: module A module for MXNet builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output_name = _get_input_output_name(net, node) name = node['name'] target_shape = node['shape'] if any(item <= 0 for item in target_shape): raise NotImplementedError('Special dimensional values less than or equal to 0 are not supported yet.' 'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.') if 'reverse' in node and node['reverse'] == 'True': raise NotImplementedError('"reverse" parameter is not supported by yet.' 'Feel free to file an issue here: https://github.com/dmlc/mxnet/issues.') mode = 0 # CHANNEL_FIRST builder.add_reshape(name, input_name, output_name, target_shape, mode)
[ "def", "convert_reshape", "(", "net", ",", "node", ",", "module", ",", "builder", ")", ":", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'", "]", "target_shape", "=", "node",...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/tools/coreml/converter/_layers.py#L81-L113
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/frame_filters.py
python
_complete_frame_filter_name
(word, printer_dict)
return flist
Worker for frame filter name completion. Arguments: word: The most recent word of the command line. printer_dict: The frame filter dictionary to search for frame filter name completions. Returns: A list of suggested frame filter name completions from word analysis of the frame filter dictionary. This list can be empty when there are no suggestions for completion.
Worker for frame filter name completion.
[ "Worker", "for", "frame", "filter", "name", "completion", "." ]
def _complete_frame_filter_name(word, printer_dict): """Worker for frame filter name completion. Arguments: word: The most recent word of the command line. printer_dict: The frame filter dictionary to search for frame filter name completions. Returns: A list of suggested frame filter name completions from word analysis of the frame filter dictionary. This list can be empty when there are no suggestions for completion. """ printer_keys = printer_dict.keys() if (word == ""): return printer_keys flist = filter(lambda x,y=word:x.startswith(y), printer_keys) return flist
[ "def", "_complete_frame_filter_name", "(", "word", ",", "printer_dict", ")", ":", "printer_keys", "=", "printer_dict", ".", "keys", "(", ")", "if", "(", "word", "==", "\"\"", ")", ":", "return", "printer_keys", "flist", "=", "filter", "(", "lambda", "x", "...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/share/gdb/python/gdb/command/frame_filters.py#L195-L215
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicle.py
python
VehicleDomain.getLeftFollowers
(self, vehID, blockingOnly=False)
return self.getNeighbors(vehID, mode)
bool -> list(pair(string, double)) Convenience method, see getNeighbors()
bool -> list(pair(string, double)) Convenience method, see getNeighbors()
[ "bool", "-", ">", "list", "(", "pair", "(", "string", "double", "))", "Convenience", "method", "see", "getNeighbors", "()" ]
def getLeftFollowers(self, vehID, blockingOnly=False): """ bool -> list(pair(string, double)) Convenience method, see getNeighbors() """ if blockingOnly: mode = 4 else: mode = 0 return self.getNeighbors(vehID, mode)
[ "def", "getLeftFollowers", "(", "self", ",", "vehID", ",", "blockingOnly", "=", "False", ")", ":", "if", "blockingOnly", ":", "mode", "=", "4", "else", ":", "mode", "=", "0", "return", "self", ".", "getNeighbors", "(", "vehID", ",", "mode", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L749-L757
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py
python
find_eggs_in_zip
(importer, path_item, only=False)
Find eggs in zip files; possibly multiple nested eggs.
Find eggs in zip files; possibly multiple nested eggs.
[ "Find", "eggs", "in", "zip", "files", ";", "possibly", "multiple", "nested", "eggs", "." ]
def find_eggs_in_zip(importer, path_item, only=False): """ Find eggs in zip files; possibly multiple nested eggs. """ if importer.archive.endswith('.whl'): # wheels are not supported with this finder # they don't have PKG-INFO metadata, and won't ever contain eggs return metadata = EggMetadata(importer) if metadata.has_metadata('PKG-INFO'): yield Distribution.from_filename(path_item, metadata=metadata) if only: # don't yield nested distros return for subitem in metadata.resource_listdir(''): if _is_egg_path(subitem): subpath = os.path.join(path_item, subitem) dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath) for dist in dists: yield dist elif subitem.lower().endswith('.dist-info'): subpath = os.path.join(path_item, subitem) submeta = EggMetadata(zipimport.zipimporter(subpath)) submeta.egg_info = subpath yield Distribution.from_location(path_item, subitem, submeta)
[ "def", "find_eggs_in_zip", "(", "importer", ",", "path_item", ",", "only", "=", "False", ")", ":", "if", "importer", ".", "archive", ".", "endswith", "(", "'.whl'", ")", ":", "# wheels are not supported with this finder", "# they don't have PKG-INFO metadata, and won't ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py#L1985-L2009
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
scripts/cpp_lint.py
python
CheckStyle
(filename, clean_lines, linenum, file_extension, nesting_state, error)
Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. 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. 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++ style rules' section of cppguide.html.
[ "Checks", "rules", "from", "the", "C", "++", "style", "rules", "section", "of", "cppguide", ".", "html", "." ]
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. 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. 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. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw_lines = clean_lines.lines_without_raw_strings line = raw_lines[linenum] if line.find('\t') != -1: error(filename, linenum, 'whitespace/tab', 1, 'Tab found; better to use spaces') # One or three blank spaces at the beginning of the line is weird; it's # hard to reconcile that with 2-space indents. # NOTE: here are the conditions rob pike used for his tests. Mine aren't # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces # if(RLENGTH > 20) complain = 0; # if(match($0, " +(error|private|public|protected):")) complain = 0; # if(match(prev, "&& *$")) complain = 0; # if(match(prev, "\\|\\| *$")) complain = 0; # if(match(prev, "[\",=><] *$")) complain = 0; # if(match($0, " <<")) complain = 0; # if(match(prev, " +for \\(")) complain = 0; # if(prevodd && match(prevprev, " +for \\(")) complain = 0; initial_spaces = 0 cleansed_line = clean_lines.elided[linenum] while initial_spaces < len(line) and line[initial_spaces] == ' ': initial_spaces += 1 if line and line[-1].isspace(): error(filename, linenum, 'whitespace/end_of_line', 4, 'Line ends in whitespace. Consider deleting these extra spaces.') # There are certain situations we allow one space, notably for section labels elif ((initial_spaces == 1 or initial_spaces == 3) and not Match(r'\s*\w+\s*:\s*$', cleansed_line)): error(filename, linenum, 'whitespace/indent', 3, 'Weird number of spaces at line-start. ' 'Are you using a 2-space indent?') # Check if the line is a header guard. is_header_guard = False if file_extension == 'h': cppvar = GetHeaderGuardCPPVariable(filename) if (line.startswith('#ifndef %s' % cppvar) or line.startswith('#define %s' % cppvar) or line.startswith('#endif // %s' % cppvar)): is_header_guard = True # #include lines and header guards can be long, since there's no clean way to # split them. # # URLs can be long too. It's possible to split these, but it makes them # harder to cut&paste. # # The "$Id:...$" comment may also get very long without it being the # developers fault. if (not line.startswith('#include') and not is_header_guard and not Match(r'^\s*//.*http(s?)://\S*$', line) and not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): line_width = GetLineWidth(line) extended_length = int((_line_length * 1.25)) if line_width > extended_length: error(filename, linenum, 'whitespace/line_length', 4, 'Lines should very rarely be longer than %i characters' % extended_length) elif line_width > _line_length: error(filename, linenum, 'whitespace/line_length', 2, 'Lines should be <= %i characters long' % _line_length) if (cleansed_line.count(';') > 1 and # for loops are allowed two ;'s (and may run over two lines). cleansed_line.find('for') == -1 and (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and # It's ok to have many commands in a switch case that fits in 1 line not ((cleansed_line.find('case ') != -1 or cleansed_line.find('default:') != -1) and cleansed_line.find('break;') != -1)): error(filename, linenum, 'whitespace/newline', 0, 'More than one command on the same line') # Some more style checks CheckBraces(filename, clean_lines, linenum, error) CheckEmptyBlockBody(filename, clean_lines, linenum, error) CheckAccess(filename, clean_lines, linenum, nesting_state, error) CheckSpacing(filename, clean_lines, linenum, nesting_state, error) CheckCheck(filename, clean_lines, linenum, error) CheckAltTokens(filename, clean_lines, linenum, error) classinfo = nesting_state.InnermostClass() if classinfo: CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
[ "def", "CheckStyle", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "file_extension", ",", "nesting_state", ",", "error", ")", ":", "# Don't use \"elided\" lines here, otherwise we can't check commented lines.", "# Don't want to use \"raw\" either, because we don't want ...
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L3459-L3563
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/optimizer.py
python
optimize
(node, environment)
return optimizer.visit(node)
The context hint can be used to perform an static optimization based on the context given.
The context hint can be used to perform an static optimization based on the context given.
[ "The", "context", "hint", "can", "be", "used", "to", "perform", "an", "static", "optimization", "based", "on", "the", "context", "given", "." ]
def optimize(node, environment): """The context hint can be used to perform an static optimization based on the context given.""" optimizer = Optimizer(environment) return optimizer.visit(node)
[ "def", "optimize", "(", "node", ",", "environment", ")", ":", "optimizer", "=", "Optimizer", "(", "environment", ")", "return", "optimizer", ".", "visit", "(", "node", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/optimizer.py#L23-L27
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/pyasn1/pyasn1/type/base.py
python
Asn1ItemBase.isSuperTypeOf
(self, other)
return self._tagSet.isSuperTagSetOf(other.getTagSet()) and \ self._subtypeSpec.isSuperTypeOf(other.getSubtypeSpec())
Returns true if argument is a ASN1 subtype of ourselves
Returns true if argument is a ASN1 subtype of ourselves
[ "Returns", "true", "if", "argument", "is", "a", "ASN1", "subtype", "of", "ourselves" ]
def isSuperTypeOf(self, other): """Returns true if argument is a ASN1 subtype of ourselves""" return self._tagSet.isSuperTagSetOf(other.getTagSet()) and \ self._subtypeSpec.isSuperTypeOf(other.getSubtypeSpec())
[ "def", "isSuperTypeOf", "(", "self", ",", "other", ")", ":", "return", "self", ".", "_tagSet", ".", "isSuperTagSetOf", "(", "other", ".", "getTagSet", "(", ")", ")", "and", "self", ".", "_subtypeSpec", ".", "isSuperTypeOf", "(", "other", ".", "getSubtypeSp...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/pyasn1/pyasn1/type/base.py#L45-L48
kiwix/kiwix-xulrunner
38f4a10ae4b1585c16cb11730bb0dcc4924ae19f
android/update-play-store.py
python
download_remote_file
(url, path)
download url to path
download url to path
[ "download", "url", "to", "path" ]
def download_remote_file(url, path): ''' download url to path ''' syscall('wget -c -O {path} {url}'.format(path=path, url=url))
[ "def", "download_remote_file", "(", "url", ",", "path", ")", ":", "syscall", "(", "'wget -c -O {path} {url}'", ".", "format", "(", "path", "=", "path", ",", "url", "=", "url", ")", ")" ]
https://github.com/kiwix/kiwix-xulrunner/blob/38f4a10ae4b1585c16cb11730bb0dcc4924ae19f/android/update-play-store.py#L112-L114
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py
python
HtmlDiff.__init__
(self,tabsize=8,wrapcolumn=None,linejunk=None, charjunk=IS_CHARACTER_JUNK)
HtmlDiff instance initializer Arguments: tabsize -- tab stop spacing, defaults to 8. wrapcolumn -- column number where lines are broken and wrapped, defaults to None where lines are not wrapped. linejunk,charjunk -- keyword arguments passed into ndiff() (used by HtmlDiff() to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions.
HtmlDiff instance initializer
[ "HtmlDiff", "instance", "initializer" ]
def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None, charjunk=IS_CHARACTER_JUNK): """HtmlDiff instance initializer Arguments: tabsize -- tab stop spacing, defaults to 8. wrapcolumn -- column number where lines are broken and wrapped, defaults to None where lines are not wrapped. linejunk,charjunk -- keyword arguments passed into ndiff() (used by HtmlDiff() to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions. """ self._tabsize = tabsize self._wrapcolumn = wrapcolumn self._linejunk = linejunk self._charjunk = charjunk
[ "def", "__init__", "(", "self", ",", "tabsize", "=", "8", ",", "wrapcolumn", "=", "None", ",", "linejunk", "=", "None", ",", "charjunk", "=", "IS_CHARACTER_JUNK", ")", ":", "self", ".", "_tabsize", "=", "tabsize", "self", ".", "_wrapcolumn", "=", "wrapco...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/difflib.py#L1729-L1744
google/clif
cab24d6a105609a65c95a36a1712ae3c20c7b5df
clif/python/pyext.py
python
Module.WrapEnum
(self, e, unused_ln, cpp_namespace, unused_class_ns='')
Process AST.EnumDecl e.
Process AST.EnumDecl e.
[ "Process", "AST", ".", "EnumDecl", "e", "." ]
def WrapEnum(self, e, unused_ln, cpp_namespace, unused_class_ns=''): """Process AST.EnumDecl e.""" # Enum(pyname, ((name, value),...)) pytype = 'Enum' if e.enum_class else 'IntEnum' items = [] for m in e.members: if ':' in m.cpp_name: name = m.cpp_name # FQN populated by matcher. else: name = e.name.cpp_name + '::' + m.cpp_name items.append(( 'PyUnicode_FromString("%s")' % (m.native or Ident(m.cpp_name)), 'PyLong_FromLong(\n%s%s)' % ( 4*I, types.AsType(types.EnumIntType(e.name.cpp_name), name)))) assert items, 'matcher should populate enum members' wclass = '_'+e.name.native genw = 'wrap'+Ident(e.name.cpp_name) pyname = '.'.join([f.pyname for f in self.nested] + [e.name.native]) t = types.EnumType(e.name.cpp_name, pyname, pytype, self.CppName(wclass), cpp_namespace) self.types.append(t) self.dict.append((e.name.native, '(%s=%s())' % (self.CppName(wclass), self.CppName(genw)))) if not self.enums: self.enums = True self.init.extend([ '{PyObject* em = PyImport_ImportModule("enum");', ' if (em == nullptr) goto err;', ' _Enum = PyObject_GetAttrString(em, "Enum");', ' _IntEnum = PyObject_GetAttrString(em, "IntEnum");', ' Py_DECREF(em);}', 'if (!_Enum || !_IntEnum) {', I+'Py_XDECREF(_Enum);', I+'Py_XDECREF(_IntEnum);', I+'goto err;', '}']) yield '' for s in t.CreateEnum(genw, wclass, items): yield s
[ "def", "WrapEnum", "(", "self", ",", "e", ",", "unused_ln", ",", "cpp_namespace", ",", "unused_class_ns", "=", "''", ")", ":", "# Enum(pyname, ((name, value),...))", "pytype", "=", "'Enum'", "if", "e", ".", "enum_class", "else", "'IntEnum'", "items", "=", "[",...
https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/pyext.py#L613-L652
sailing-pmls/pmls-caffe
49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a
scripts/cpp_lint.py
python
CheckForNonStandardConstructs
(filename, clean_lines, linenum, nesting_state, error)
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
[ "r", "Logs", "an", "error", "if", "we", "see", "certain", "non", "-", "ANSI", "constructs", "ignored", "by", "gcc", "-", "2", "." ]
def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' % re.escape(base_classname), line) if (args and args.group(1) != 'void' and not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), args.group(1).strip())): error(filename, linenum, 'runtime/explicit', 5, 'Single-argument constructors should be marked explicit.')
[ "def", "CheckForNonStandardConstructs", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Remove comments from the line, but leave in strings for now.", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "i...
https://github.com/sailing-pmls/pmls-caffe/blob/49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a/scripts/cpp_lint.py#L2194-L2298
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/os.py
python
removedirs
(name)
removedirs(path) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. Errors during this latter phase are ignored -- they generally mean that a directory was not empty.
removedirs(path)
[ "removedirs", "(", "path", ")" ]
def removedirs(name): """removedirs(path) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. Errors during this latter phase are ignored -- they generally mean that a directory was not empty. """ rmdir(name) head, tail = path.split(name) if not tail: head, tail = path.split(head) while head and tail: try: rmdir(head) except error: break head, tail = path.split(head)
[ "def", "removedirs", "(", "name", ")", ":", "rmdir", "(", "name", ")", "head", ",", "tail", "=", "path", ".", "split", "(", "name", ")", "if", "not", "tail", ":", "head", ",", "tail", "=", "path", ".", "split", "(", "head", ")", "while", "head", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/os.py#L159-L179
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/vis/ipython/widgets.py
python
KlamptWidget.addTriangle
(self,name="Tri1",a=(0,0,0),b=(1,0,0),c=(0,1,0))
Adds a new triangle with vertices a,b,c. a,b, and c are 3-lists or 3-tuples.
Adds a new triangle with vertices a,b,c. a,b, and c are 3-lists or 3-tuples.
[ "Adds", "a", "new", "triangle", "with", "vertices", "a", "b", "c", ".", "a", "b", "and", "c", "are", "3", "-", "lists", "or", "3", "-", "tuples", "." ]
def addTriangle(self,name="Tri1",a=(0,0,0),b=(1,0,0),c=(0,1,0)): """Adds a new triangle with vertices a,b,c. a,b, and c are 3-lists or 3-tuples.""" verts = a+b+c self._extras[name] = ('Trilist',verts) self._do_rpc({'type':'add_trilist','name':name,'verts':verts})
[ "def", "addTriangle", "(", "self", ",", "name", "=", "\"Tri1\"", ",", "a", "=", "(", "0", ",", "0", ",", "0", ")", ",", "b", "=", "(", "1", ",", "0", ",", "0", ")", ",", "c", "=", "(", "0", ",", "1", ",", "0", ")", ")", ":", "verts", ...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/ipython/widgets.py#L492-L496
mitsuba-renderer/mitsuba2
4e7628c6eed365904ca2ba536b795d1b03410344
docs/docs_api/conf.py
python
generate_list_api_callback
(app)
Generate a RST file listing all the python members (classes or functions) to be parsed and extracted. This function will recursively explore submodules and packages.
Generate a RST file listing all the python members (classes or functions) to be parsed and extracted. This function will recursively explore submodules and packages.
[ "Generate", "a", "RST", "file", "listing", "all", "the", "python", "members", "(", "classes", "or", "functions", ")", "to", "be", "parsed", "and", "extracted", ".", "This", "function", "will", "recursively", "explore", "submodules", "and", "packages", "." ]
def generate_list_api_callback(app): """Generate a RST file listing all the python members (classes or functions) to be parsed and extracted. This function will recursively explore submodules and packages.""" import importlib from inspect import isclass, isfunction, ismodule, ismethod def process(f, obj, lib, name): if re.match(r'__[a-zA-Z\_0-9]+__', name): return if ismodule(obj): # 'python' is a package, so it needs to be treated differently if name == 'python': # Iterate recursively on all the python files for root, dirs, files in os.walk(obj.__path__[0]): root = root.replace(obj.__path__[0], '').replace('/', '.') if root.endswith('__pycache__'): continue for f_name in files: if not f_name == '__init__.py' and f_name.endswith('.py'): module = importlib.import_module( 'mitsuba.python%s.%s' % (root, f_name[:-3])) for x in dir(module): obj2 = getattr(module, x) # Skip the imported modules (e.g. enoki) if not ismodule(obj2): process(f, obj2, '.python%s.%s' % (root, f_name[:-3]), x) else: for x in dir(obj): process(f, getattr(obj, x), '%s.%s' % (lib, name), x) else: full_name = 'mitsuba%s.%s' % (lib, name) # Check if this block should be excluded from the API documentation for pattern in excluded_api: if re.fullmatch(pattern, full_name): return f.write('.. auto%s:: %s\n\n' % ('class' if isclass(obj) else 'function', full_name)) with open(list_api_filename, 'w') as f: print('Generate API list file: %s' % list_api_filename) for lib in ['core', 'render', 'python']: module = importlib.import_module('mitsuba.%s' % lib) process(f, module, '', lib)
[ "def", "generate_list_api_callback", "(", "app", ")", ":", "import", "importlib", "from", "inspect", "import", "isclass", ",", "isfunction", ",", "ismodule", ",", "ismethod", "def", "process", "(", "f", ",", "obj", ",", "lib", ",", "name", ")", ":", "if", ...
https://github.com/mitsuba-renderer/mitsuba2/blob/4e7628c6eed365904ca2ba536b795d1b03410344/docs/docs_api/conf.py#L681-L730
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/mailbox.py
python
Babyl._pre_mailbox_hook
(self, f)
Called before writing the mailbox to file f.
Called before writing the mailbox to file f.
[ "Called", "before", "writing", "the", "mailbox", "to", "file", "f", "." ]
def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" babyl = b'BABYL OPTIONS:' + linesep babyl += b'Version: 5' + linesep labels = self.get_labels() labels = (label.encode() for label in labels) babyl += b'Labels:' + b','.join(labels) + linesep babyl += b'\037' f.write(babyl)
[ "def", "_pre_mailbox_hook", "(", "self", ",", "f", ")", ":", "babyl", "=", "b'BABYL OPTIONS:'", "+", "linesep", "babyl", "+=", "b'Version: 5'", "+", "linesep", "labels", "=", "self", ".", "get_labels", "(", ")", "labels", "=", "(", "label", ".", "encode", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mailbox.py#L1360-L1368
ideawu/ssdb
f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4
deps/cpy/antlr3/recognizers.py
python
TokenSource.next
(self)
return token
Return next token or raise StopIteration. Note that this will raise StopIteration when hitting the EOF token, so EOF will not be part of the iteration.
Return next token or raise StopIteration.
[ "Return", "next", "token", "or", "raise", "StopIteration", "." ]
def next(self): """Return next token or raise StopIteration. Note that this will raise StopIteration when hitting the EOF token, so EOF will not be part of the iteration. """ token = self.nextToken() if token is None or token.type == EOF: raise StopIteration return token
[ "def", "next", "(", "self", ")", ":", "token", "=", "self", ".", "nextToken", "(", ")", "if", "token", "is", "None", "or", "token", ".", "type", "==", "EOF", ":", "raise", "StopIteration", "return", "token" ]
https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/recognizers.py#L1073-L1084
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/contrib/onnx/mx2onnx/_op_translations.py
python
get_inputs
(node, kwargs)
return name, input_nodes, attrs
Helper function to get inputs
Helper function to get inputs
[ "Helper", "function", "to", "get", "inputs" ]
def get_inputs(node, kwargs): """Helper function to get inputs""" name = node["name"] proc_nodes = kwargs["proc_nodes"] index_lookup = kwargs["index_lookup"] inputs = node["inputs"] attrs = node.get("attrs", {}) input_nodes = [] for ip in inputs: input_node_id = index_lookup[ip[0]] input_nodes.append(proc_nodes[input_node_id].name) return name, input_nodes, attrs
[ "def", "get_inputs", "(", "node", ",", "kwargs", ")", ":", "name", "=", "node", "[", "\"name\"", "]", "proc_nodes", "=", "kwargs", "[", "\"proc_nodes\"", "]", "index_lookup", "=", "kwargs", "[", "\"index_lookup\"", "]", "inputs", "=", "node", "[", "\"input...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L133-L146
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/json/_json.py
python
FrameParser._process_converter
(self, f, filt=None)
Take a conversion function and possibly recreate the frame.
Take a conversion function and possibly recreate the frame.
[ "Take", "a", "conversion", "function", "and", "possibly", "recreate", "the", "frame", "." ]
def _process_converter(self, f, filt=None): """ Take a conversion function and possibly recreate the frame. """ if filt is None: filt = lambda col, c: True needs_new_obj = False new_obj = dict() for i, (col, c) in enumerate(self.obj.items()): if filt(col, c): new_data, result = f(col, c) if result: c = new_data needs_new_obj = True new_obj[i] = c if needs_new_obj: # possibly handle dup columns new_obj = DataFrame(new_obj, index=self.obj.index) new_obj.columns = self.obj.columns self.obj = new_obj
[ "def", "_process_converter", "(", "self", ",", "f", ",", "filt", "=", "None", ")", ":", "if", "filt", "is", "None", ":", "filt", "=", "lambda", "col", ",", "c", ":", "True", "needs_new_obj", "=", "False", "new_obj", "=", "dict", "(", ")", "for", "i...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/json/_json.py#L1111-L1134
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
is_distinct
(a)
return is_app_of(a, Z3_OP_DISTINCT)
Return `True` if `a` is a Z3 distinct expression. >>> x, y, z = Ints('x y z') >>> is_distinct(x == y) False >>> is_distinct(Distinct(x, y, z)) True
Return `True` if `a` is a Z3 distinct expression.
[ "Return", "True", "if", "a", "is", "a", "Z3", "distinct", "expression", "." ]
def is_distinct(a): """Return `True` if `a` is a Z3 distinct expression. >>> x, y, z = Ints('x y z') >>> is_distinct(x == y) False >>> is_distinct(Distinct(x, y, z)) True """ return is_app_of(a, Z3_OP_DISTINCT)
[ "def", "is_distinct", "(", "a", ")", ":", "return", "is_app_of", "(", "a", ",", "Z3_OP_DISTINCT", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L1647-L1656
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/generator/ninja.py
python
ComputeOutputDir
(params)
return os.path.normpath(os.path.join(generator_dir, output_dir))
Returns the path from the toplevel_dir to the build output directory.
Returns the path from the toplevel_dir to the build output directory.
[ "Returns", "the", "path", "from", "the", "toplevel_dir", "to", "the", "build", "output", "directory", "." ]
def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = params.get('generator_flags', {}).get('output_dir', 'out') # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir))
[ "def", "ComputeOutputDir", "(", "params", ")", ":", "# generator_dir: relative path from pwd to where make puts build files.", "# Makes migrating from make to ninja easier, ninja doesn't put anything here.", "generator_dir", "=", "os", ".", "path", ".", "relpath", "(", "params", "[...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/generator/ninja.py#L71-L81
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/extras.py
python
intersect1d
(ar1, ar2, assume_unique=False)
return aux[:-1][aux[1:] == aux[:-1]]
Returns the unique elements common to both arrays. Masked values are considered equal one to the other. The output is always a masked array. See `numpy.intersect1d` for more details. See Also -------- numpy.intersect1d : Equivalent function for ndarrays. Examples -------- >>> x = array([1, 3, 3, 3], mask=[0, 0, 0, 1]) >>> y = array([3, 1, 1, 1], mask=[0, 0, 0, 1]) >>> intersect1d(x, y) masked_array(data = [1 3 --], mask = [False False True], fill_value = 999999)
Returns the unique elements common to both arrays.
[ "Returns", "the", "unique", "elements", "common", "to", "both", "arrays", "." ]
def intersect1d(ar1, ar2, assume_unique=False): """ Returns the unique elements common to both arrays. Masked values are considered equal one to the other. The output is always a masked array. See `numpy.intersect1d` for more details. See Also -------- numpy.intersect1d : Equivalent function for ndarrays. Examples -------- >>> x = array([1, 3, 3, 3], mask=[0, 0, 0, 1]) >>> y = array([3, 1, 1, 1], mask=[0, 0, 0, 1]) >>> intersect1d(x, y) masked_array(data = [1 3 --], mask = [False False True], fill_value = 999999) """ if assume_unique: aux = ma.concatenate((ar1, ar2)) else: # Might be faster than unique( intersect1d( ar1, ar2 ) )? aux = ma.concatenate((unique(ar1), unique(ar2))) aux.sort() return aux[:-1][aux[1:] == aux[:-1]]
[ "def", "intersect1d", "(", "ar1", ",", "ar2", ",", "assume_unique", "=", "False", ")", ":", "if", "assume_unique", ":", "aux", "=", "ma", ".", "concatenate", "(", "(", "ar1", ",", "ar2", ")", ")", "else", ":", "# Might be faster than unique( intersect1d( ar1...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/extras.py#L1066-L1095
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
Argument.GetValidClientSideArg
(self, func, offset, index)
return str(offset + 1)
Gets a valid value for this argument.
Gets a valid value for this argument.
[ "Gets", "a", "valid", "value", "for", "this", "argument", "." ]
def GetValidClientSideArg(self, func, offset, index): """Gets a valid value for this argument.""" return str(offset + 1)
[ "def", "GetValidClientSideArg", "(", "self", ",", "func", ",", "offset", ",", "index", ")", ":", "return", "str", "(", "offset", "+", "1", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5789-L5791
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/rcnn/rcnn/pycocotools/cocoeval.py
python
COCOeval.evaluate
(self)
Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None
Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None
[ "Run", "per", "image", "evaluation", "on", "given", "images", "and", "store", "results", "(", "a", "list", "of", "dict", ")", "in", "self", ".", "evalImgs", ":", "return", ":", "None" ]
def evaluate(self): ''' Run per image evaluation on given images and store results (a list of dict) in self.evalImgs :return: None ''' tic = time.time() print('Running per image evaluation...') p = self.params # add backward compatibility if useSegm is specified in params if not p.useSegm is None: p.iouType = 'segm' if p.useSegm == 1 else 'bbox' print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType)) print('Evaluate annotation type *{}*'.format(p.iouType)) p.imgIds = list(np.unique(p.imgIds)) if p.useCats: p.catIds = list(np.unique(p.catIds)) p.maxDets = sorted(p.maxDets) self.params=p self._prepare() # loop through images, area range, max detection number catIds = p.catIds if p.useCats else [-1] if p.iouType == 'segm' or p.iouType == 'bbox': computeIoU = self.computeIoU elif p.iouType == 'keypoints': computeIoU = self.computeOks self.ious = {(imgId, catId): computeIoU(imgId, catId) \ for imgId in p.imgIds for catId in catIds} evaluateImg = self.evaluateImg maxDet = p.maxDets[-1] self.evalImgs = [evaluateImg(imgId, catId, areaRng, maxDet) for catId in catIds for areaRng in p.areaRng for imgId in p.imgIds ] self._paramsEval = copy.deepcopy(self.params) toc = time.time() print('DONE (t={:0.2f}s).'.format(toc-tic))
[ "def", "evaluate", "(", "self", ")", ":", "tic", "=", "time", ".", "time", "(", ")", "print", "(", "'Running per image evaluation...'", ")", "p", "=", "self", ".", "params", "# add backward compatibility if useSegm is specified in params", "if", "not", "p", ".", ...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/rcnn/rcnn/pycocotools/cocoeval.py#L139-L179
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/fx/_convert_do_not_use.py
python
_convert_do_not_use
( model: GraphModule, is_reference: bool = False, convert_custom_config_dict: Dict[str, Any] = None, is_standalone_module: bool = False, _remove_qconfig_flag: bool = True, backend_config_dict: Optional[Dict[str, Any]] = None)
return model
We will convert an observed model (a module with observer calls) to a reference quantized model, the rule is simple: 1. for each observer module call in the graph, we'll convert it to calls to quantize and dequantize functions based on the observer instance 2. for weighted operations like linear/conv, we need to convert them to reference quantized module, this requires us to know whether the dtype configured for the weight is supported in the backend, this is done in prepare step and the result is stored in observed_node_names, we can decide whether we need to swap the module based on this set standalone_module means it a submodule that is not inlined in parent module, and will be quantized separately as one unit. Returns a quantized standalone module, whether input/output is quantized is specified by prepare_custom_config_dict, with input_quantized_idxs, output_quantized_idxs, please see docs for prepare_fx for details
We will convert an observed model (a module with observer calls) to a reference quantized model, the rule is simple: 1. for each observer module call in the graph, we'll convert it to calls to quantize and dequantize functions based on the observer instance 2. for weighted operations like linear/conv, we need to convert them to reference quantized module, this requires us to know whether the dtype configured for the weight is supported in the backend, this is done in prepare step and the result is stored in observed_node_names, we can decide whether we need to swap the module based on this set
[ "We", "will", "convert", "an", "observed", "model", "(", "a", "module", "with", "observer", "calls", ")", "to", "a", "reference", "quantized", "model", "the", "rule", "is", "simple", ":", "1", ".", "for", "each", "observer", "module", "call", "in", "the"...
def _convert_do_not_use( model: GraphModule, is_reference: bool = False, convert_custom_config_dict: Dict[str, Any] = None, is_standalone_module: bool = False, _remove_qconfig_flag: bool = True, backend_config_dict: Optional[Dict[str, Any]] = None) -> torch.nn.Module: """ We will convert an observed model (a module with observer calls) to a reference quantized model, the rule is simple: 1. for each observer module call in the graph, we'll convert it to calls to quantize and dequantize functions based on the observer instance 2. for weighted operations like linear/conv, we need to convert them to reference quantized module, this requires us to know whether the dtype configured for the weight is supported in the backend, this is done in prepare step and the result is stored in observed_node_names, we can decide whether we need to swap the module based on this set standalone_module means it a submodule that is not inlined in parent module, and will be quantized separately as one unit. Returns a quantized standalone module, whether input/output is quantized is specified by prepare_custom_config_dict, with input_quantized_idxs, output_quantized_idxs, please see docs for prepare_fx for details """ if convert_custom_config_dict is None: convert_custom_config_dict = {} patterns, node_name_to_scope, prepare_custom_config_dict, observed_node_names = restore_state(model) qconfig_map: Dict[str, QConfigAny] = model._qconfig_map # type: ignore[assignment] assert is_reference, "_convert_do_not_use only supports reference option" # mapping from fully qualified module name to module instance # for example, # { # '': Model(...), # 'linear': Linear(...), # 'linear.weight_fake_quant': PerChannelMinMaxObserver(...), # } # We use remove_duplicate=False here because torch.cat uses # the same activation_post_process module instance but different names modules = dict(model.named_modules(remove_duplicate=False)) custom_module_classes = get_custom_module_class_keys( convert_custom_config_dict, "observed_to_quantized_custom_module_class") if model._equalization_qconfig_map is not None: # If we want to do equalization then do the following: # Calculate the equalization scale, update the observers with the scaled # inputs, and scale the weight weight_eq_obs_dict = update_obs_for_equalization(model, modules) convert_eq_obs(model, modules, weight_eq_obs_dict) graph_inputs: List[str] = [] for node in model.graph.nodes: if node.op == 'placeholder': graph_inputs.append(node.name) def replace_observer_with_quantize_dequantize_node(graph: Graph, node: Node, modules: Dict[str, torch.nn.Module]) -> None: """ Replace activation_post_process module call node with quantize and dequantize node Before: ... -> observer_0(x) -> ... After: ... -> torch.quantize_per_tensor(x, ...) -> x.dequantize() -> ... """ assert modules is not None assert isinstance(node.target, str) observer_module = modules[node.target] root_module = modules[""] if observer_module.dtype == torch.float32: # remove the node for now # TODO: support dynamic quant with graph.inserting_before(node): node.replace_all_uses_with(node.args[0]) graph.erase_node(node) elif observer_module.dtype in [torch.quint8, torch.qint8, torch.float16]: node_type, quantize_op, qparams = get_quantize_node_info(observer_module) # replace observer node with quant - dequant node with graph.inserting_before(node): input_node = node.args[0] inputs = [input_node] for key, value in qparams.items(): if key in ['_scale_', '_zero_point_']: # For scale and zero_point values we register them as buffers in the root module. # TODO: maybe need more complex attr name here qparam_node = create_getattr_from_value(root_module, graph, key, value) inputs.append(qparam_node) else: # for qparams that are not scale/zero_point (like axis, dtype) we store them as literals in the graph. inputs.append(value) quantized_node = graph.create_node(node_type, quantize_op, tuple(inputs), {}) dequantized_node = graph.call_method("dequantize", args=(quantized_node,)) node.replace_all_uses_with(dequantized_node) graph.erase_node(node) # additional state to override inputs to be quantized, if specified # by the user placeholder_node_seen_cnt = 0 output_node_seen_cnt = 0 input_quantized_idxs: List[int] = prepare_custom_config_dict.get( "input_quantized_idxs", []) output_quantized_idxs: List[int] = prepare_custom_config_dict.get( "output_quantized_idxs", []) if backend_config_dict is None: backend_config_dict = {} quantized_reference_module_mapping = get_quantized_reference_module_mapping(backend_config_dict) # convert tuples so that it can work with isinstance(module, tuple_of_classes) weighted_module_classes = tuple(quantized_reference_module_mapping.keys()) for node in list(model.graph.nodes): if node.op == 'placeholder': cur_placeholder_node_idx = placeholder_node_seen_cnt placeholder_node_seen_cnt += 1 if cur_placeholder_node_idx in input_quantized_idxs: # Inputs are assumed to be quantized if the user specifid the # input_quantized_idxs override. # we need to dequantize the inputs since all operators took # floating point inputs in reference quantized models insert_dequantize_node(node, model.graph) elif node.op == "output": cur_output_node_idx = output_node_seen_cnt output_node_seen_cnt += 1 if cur_output_node_idx in output_quantized_idxs: # Result are kept quantized if the user specified the # output_quantized_idxs override. # Remove the dequantize operator in the end maybe_dequantize_node = node.args[0] if isinstance(maybe_dequantize_node, Node) and \ maybe_dequantize_node.op == "call_method" and \ maybe_dequantize_node.target == "dequantize": quantize_node = maybe_dequantize_node.args[0] maybe_dequantize_node.replace_all_uses_with(quantize_node) model.graph.erase_node(maybe_dequantize_node) elif node.op == "call_module": if is_activation_post_process(modules[node.target]): replace_observer_with_quantize_dequantize_node(model.graph, node, modules) elif is_observed_standalone_module(modules[node.target]): # TODO: move this to a separate function convert = torch.ao.quantization._quantize_fx_do_not_use._convert_do_not_use # type: ignore[attr-defined] # We know that observed standalone module is a GraphModule since # it's produced by us observed_standalone_module : GraphModule = modules[str(node.target)] # type: ignore[assignment] sm_input_quantized_idxs = \ observed_standalone_module \ ._standalone_module_input_quantized_idxs\ .tolist() # type: ignore[operator] # remove the dequantize nodes for inputs args = list(node.args) for idx in range(len(args)): if idx in sm_input_quantized_idxs: arg = args[idx] if arg.op == "call_method" and arg.target == "dequantize": quantize_node = arg.args[0] node.replace_input_with(arg, quantize_node) if len(arg.users) == 0: model.graph.erase_node(arg) # add dequantize node for output sm_output_quantized_idxs = \ observed_standalone_module \ ._standalone_module_output_quantized_idxs \ .tolist() # type: ignore[operator] if len(sm_output_quantized_idxs) > 0: assert sm_output_quantized_idxs[0] == 0, "Currently only quantized" "output idxs = [0] is supported" # if it's non-empty, then it means the output is kept in quantized form # we'll just add a dequantize node after this node insert_dequantize_node(node, model.graph) # TODO: allow convert_custom_config_dict to override backend_config_dict # for standalone module quantized_standalone_module = convert( observed_standalone_module, is_reference=True, backend_config_dict=backend_config_dict) parent_name, name = _parent_name(node.target) # update the modules dict setattr(modules[parent_name], name, quantized_standalone_module) modules[str(node.target)] = quantized_standalone_module elif type(modules[node.target]) in set( weighted_module_classes).union(QAT_MODULE_CLASSES).union(FUSED_MODULE_CLASSES): # TODO: refactor this part to a function original_module = modules[node.target] qconfig = original_module.qconfig is_observed = node.name in observed_node_names is_activation_quantized = activation_is_int8_quantized(qconfig) is_weight_quantized = weight_is_statically_quantized(qconfig) # TODO: rename weight_is_statically_quantized to weight_is_int8_quantized if qconfig is None or \ not is_observed or \ not is_weight_quantized or \ not is_activation_quantized: continue float_module = original_module fused_module = None if isinstance( original_module, QAT_MODULE_CLASSES): # case 1. converting qat module to # a float module, we need to attch # weight fake_quant to the module, # weight fake_quant is assumed to be run during # QAT so we don't need to run it again here float_module = original_module.to_float() # type: ignore[operator] # change qat conv to conv parent_name, name = _parent_name(node.target) setattr(modules[parent_name], name, float_module) if isinstance(float_module, torch.nn.intrinsic._FusedModule): fused_module = float_module float_module = fused_module[0] weight_post_process = original_module.weight_fake_quant else: # case 2. converting a float module/fused float module # to float module, we need to attach # weight observer to the conv module and run it # with conv weight if isinstance(original_module, torch.nn.intrinsic._FusedModule): fused_module = original_module float_module = fused_module[0] # type: ignore[index] assert qconfig is not None weight_post_process = qconfig.weight() # run weight observer weight_post_process(float_module.weight) # type: ignore[operator] weight_qparams = get_qparam_dict(weight_post_process) # TODO: may need to change the mapping when we support dynamic quantization ref_qmodule_cls = quantized_reference_module_mapping.get(type(float_module), None) assert ref_qmodule_cls is not None, f"No reference quantized module class configured for {type(float_module)}" ref_qmodule = ref_qmodule_cls.from_float(float_module, weight_qparams) # type: ignore[attr-defined] if fused_module is not None: fused_module[0] = ref_qmodule else: parent_name, name = _parent_name(node.target) setattr(modules[parent_name], name, ref_qmodule) # removes qconfig and activation_post_process modules if _remove_qconfig_flag: _remove_qconfig(model) preserved_attributes = set(convert_custom_config_dict.get("preserved_attributes", [])) model = QuantizedGraphModule(model, model.graph, preserved_attributes) return model
[ "def", "_convert_do_not_use", "(", "model", ":", "GraphModule", ",", "is_reference", ":", "bool", "=", "False", ",", "convert_custom_config_dict", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "is_standalone_module", ":", "bool", "=", "False", ...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/_convert_do_not_use.py#L69-L316
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
libcxx/utils/libcxx/sym_check/extract.py
python
extract_symbols
(lib_file, static_lib=None)
return extractor.extract(lib_file)
Extract and return a list of symbols extracted from a static or dynamic library. The symbols are extracted using NM or readelf. They are then filtered and formated. Finally they symbols are made unique.
Extract and return a list of symbols extracted from a static or dynamic library. The symbols are extracted using NM or readelf. They are then filtered and formated. Finally they symbols are made unique.
[ "Extract", "and", "return", "a", "list", "of", "symbols", "extracted", "from", "a", "static", "or", "dynamic", "library", ".", "The", "symbols", "are", "extracted", "using", "NM", "or", "readelf", ".", "They", "are", "then", "filtered", "and", "formated", ...
def extract_symbols(lib_file, static_lib=None): """ Extract and return a list of symbols extracted from a static or dynamic library. The symbols are extracted using NM or readelf. They are then filtered and formated. Finally they symbols are made unique. """ if static_lib is None: _, ext = os.path.splitext(lib_file) static_lib = True if ext in ['.a'] else False if ReadElfExtractor.find_tool() and not static_lib: extractor = ReadElfExtractor(static_lib=static_lib) else: extractor = NMExtractor(static_lib=static_lib) return extractor.extract(lib_file)
[ "def", "extract_symbols", "(", "lib_file", ",", "static_lib", "=", "None", ")", ":", "if", "static_lib", "is", "None", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "lib_file", ")", "static_lib", "=", "True", "if", "ext", "in", ...
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/libcxx/utils/libcxx/sym_check/extract.py#L188-L201
gabyx/ApproxMVBB
838f3ff7690a938f1e4199a5f41b6feefc32a603
example/kdTreeFiltering/python/Tools/Transformations/Transformations.py
python
concatenate_matrices
(*matrices)
return M
Return concatenation of series of transformation matrices. >>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5 >>> numpy.allclose(M, concatenate_matrices(M)) True >>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T)) True
Return concatenation of series of transformation matrices.
[ "Return", "concatenation", "of", "series", "of", "transformation", "matrices", "." ]
def concatenate_matrices(*matrices): """Return concatenation of series of transformation matrices. >>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5 >>> numpy.allclose(M, concatenate_matrices(M)) True >>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T)) True """ M = numpy.identity(4) for i in matrices: M = numpy.dot(M, i) return M
[ "def", "concatenate_matrices", "(", "*", "matrices", ")", ":", "M", "=", "numpy", ".", "identity", "(", "4", ")", "for", "i", "in", "matrices", ":", "M", "=", "numpy", ".", "dot", "(", "M", ",", "i", ")", "return", "M" ]
https://github.com/gabyx/ApproxMVBB/blob/838f3ff7690a938f1e4199a5f41b6feefc32a603/example/kdTreeFiltering/python/Tools/Transformations/Transformations.py#L1840-L1853
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/cpu.py
python
remove_refct_calls
(func)
Remove redundant incref/decref within on a per block basis
Remove redundant incref/decref within on a per block basis
[ "Remove", "redundant", "incref", "/", "decref", "within", "on", "a", "per", "block", "basis" ]
def remove_refct_calls(func): """ Remove redundant incref/decref within on a per block basis """ for bb in func.basic_blocks: remove_null_refct_call(bb) remove_refct_pairs(bb)
[ "def", "remove_refct_calls", "(", "func", ")", ":", "for", "bb", "in", "func", ".", "basic_blocks", ":", "remove_null_refct_call", "(", "bb", ")", "remove_refct_pairs", "(", "bb", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/cpu.py#L226-L232
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pdb.py
python
Pdb.displayhook
(self, obj)
Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins.
Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins.
[ "Custom", "displayhook", "for", "the", "exec", "in", "default", "()", "which", "prevents", "assignment", "of", "the", "_", "variable", "in", "the", "builtins", "." ]
def displayhook(self, obj): """Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins. """ # reproduce the behavior of the standard displayhook, not printing None if obj is not None: print repr(obj)
[ "def", "displayhook", "(", "self", ",", "obj", ")", ":", "# reproduce the behavior of the standard displayhook, not printing None", "if", "obj", "is", "not", "None", ":", "print", "repr", "(", "obj", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/pdb.py#L213-L219
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/sharedctypes.py
python
RawValue
(typecode_or_type, *args)
return obj
Returns a ctypes object allocated from shared memory
Returns a ctypes object allocated from shared memory
[ "Returns", "a", "ctypes", "object", "allocated", "from", "shared", "memory" ]
def RawValue(typecode_or_type, *args): ''' Returns a ctypes object allocated from shared memory ''' type_ = typecode_to_type.get(typecode_or_type, typecode_or_type) obj = _new_value(type_) ctypes.memset(ctypes.addressof(obj), 0, ctypes.sizeof(obj)) obj.__init__(*args) return obj
[ "def", "RawValue", "(", "typecode_or_type", ",", "*", "args", ")", ":", "type_", "=", "typecode_to_type", ".", "get", "(", "typecode_or_type", ",", "typecode_or_type", ")", "obj", "=", "_new_value", "(", "type_", ")", "ctypes", ".", "memset", "(", "ctypes", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/sharedctypes.py#L66-L74
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/nn/quantized/_reference/modules/linear.py
python
Linear.forward
(self, x: torch.Tensor)
return result
we have: w(float) -- quant - dequant \ x(float) ------------- F.linear --- In the full model, we will see w(float) -- quant - *dequant \ x -- quant --- *dequant -- *F.linear --- *quant - dequant and the backend should be able to fuse the ops with `*` into a quantized linear
we have: w(float) -- quant - dequant \ x(float) ------------- F.linear ---
[ "we", "have", ":", "w", "(", "float", ")", "--", "quant", "-", "dequant", "\\", "x", "(", "float", ")", "-------------", "F", ".", "linear", "---" ]
def forward(self, x: torch.Tensor) -> torch.Tensor: """ we have: w(float) -- quant - dequant \ x(float) ------------- F.linear --- In the full model, we will see w(float) -- quant - *dequant \ x -- quant --- *dequant -- *F.linear --- *quant - dequant and the backend should be able to fuse the ops with `*` into a quantized linear """ weight_dequant = self.get_weight() result = F.linear(x, weight_dequant, self.bias) return result
[ "def", "forward", "(", "self", ",", "x", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "weight_dequant", "=", "self", ".", "get_weight", "(", ")", "result", "=", "F", ".", "linear", "(", "x", ",", "weight_dequant", ",", "self",...
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/quantized/_reference/modules/linear.py#L84-L97
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
Mass.__init__
(self)
r"""
r"""
[ "r" ]
def __init__(self): r""" """ _robotsim.Mass_swiginit(self, _robotsim.new_Mass())
[ "def", "__init__", "(", "self", ")", ":", "_robotsim", ".", "Mass_swiginit", "(", "self", ",", "_robotsim", ".", "new_Mass", "(", ")", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L3771-L3774
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/process.py
python
Process.authkey
(self, authkey)
Set authorization key of process
Set authorization key of process
[ "Set", "authorization", "key", "of", "process" ]
def authkey(self, authkey): ''' Set authorization key of process ''' self._authkey = AuthenticationString(authkey)
[ "def", "authkey", "(", "self", ",", "authkey", ")", ":", "self", ".", "_authkey", "=", "AuthenticationString", "(", "authkey", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/multiprocessing/process.py#L190-L194
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/_inner_ops.py
python
MatrixDiag.__init__
(self)
Initialize MatrixDiag
Initialize MatrixDiag
[ "Initialize", "MatrixDiag" ]
def __init__(self): """Initialize MatrixDiag"""
[ "def", "__init__", "(", "self", ")", ":" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_inner_ops.py#L312-L313
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py
python
Set.remove
(self, element)
Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError.
Remove an element from a set; it must be a member.
[ "Remove", "an", "element", "from", "a", "set", ";", "it", "must", "be", "a", "member", "." ]
def remove(self, element): """Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ try: del self._data[element] except TypeError: transform = getattr(element, "__as_temporarily_immutable__", None) if transform is None: raise # re-raise the TypeError exception we caught del self._data[transform()]
[ "def", "remove", "(", "self", ",", "element", ")", ":", "try", ":", "del", "self", ".", "_data", "[", "element", "]", "except", "TypeError", ":", "transform", "=", "getattr", "(", "element", ",", "\"__as_temporarily_immutable__\"", ",", "None", ")", "if", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/sets.py#L512-L523
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_grad.py
python
_PolygammaGrad
(op, grad)
Returns gradient of psi(n, x) with respect to n and x.
Returns gradient of psi(n, x) with respect to n and x.
[ "Returns", "gradient", "of", "psi", "(", "n", "x", ")", "with", "respect", "to", "n", "and", "x", "." ]
def _PolygammaGrad(op, grad): """Returns gradient of psi(n, x) with respect to n and x.""" # TODO(tillahoffmann): Add derivative with respect to n n = op.inputs[0] x = op.inputs[1] # Broadcast gradients sn = array_ops.shape(n) sx = array_ops.shape(x) unused_rn, rx = gen_array_ops.broadcast_gradient_args(sn, sx) # Evaluate gradient with ops.control_dependencies([grad]): n = math_ops.conj(n) x = math_ops.conj(x) partial_x = math_ops.polygamma(n + 1, x) return (None, array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx))
[ "def", "_PolygammaGrad", "(", "op", ",", "grad", ")", ":", "# TODO(tillahoffmann): Add derivative with respect to n", "n", "=", "op", ".", "inputs", "[", "0", "]", "x", "=", "op", ".", "inputs", "[", "1", "]", "# Broadcast gradients", "sn", "=", "array_ops", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L1146-L1161
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
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/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/saver.py#L880-L908
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/announcement.py
python
Announcement.to_str
(self)
return pprint.pformat(self.to_dict())
Returns the string representation of the model
Returns the string representation of the model
[ "Returns", "the", "string", "representation", "of", "the", "model" ]
def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
[ "def", "to_str", "(", "self", ")", ":", "return", "pprint", ".", "pformat", "(", "self", ".", "to_dict", "(", ")", ")" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/announcement.py#L203-L205
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/MSVSProject.py
python
Writer._GetSpecForConfiguration
(self, config_type, config_name, attrs, tools)
return specification
Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns:
Returns the specification for a configuration.
[ "Returns", "the", "specification", "for", "a", "configuration", "." ]
def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): """Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns: """ # Handle defaults if not attrs: attrs = {} if not tools: tools = [] # Add configuration node and its attributes node_attrs = attrs.copy() node_attrs['Name'] = config_name specification = [config_type, node_attrs] # Add tool nodes and their attributes if tools: for t in tools: if isinstance(t, Tool): specification.append(t._GetSpecification()) else: specification.append(Tool(t)._GetSpecification()) return specification
[ "def", "_GetSpecForConfiguration", "(", "self", ",", "config_type", ",", "config_name", ",", "attrs", ",", "tools", ")", ":", "# Handle defaults", "if", "not", "attrs", ":", "attrs", "=", "{", "}", "if", "not", "tools", ":", "tools", "=", "[", "]", "# Ad...
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/MSVSProject.py#L92-L120
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/slim/python/slim/nets/resnet_utils.py
python
resnet_arg_scope
(is_training=True, weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True)
Defines the default ResNet arg scope. TODO(gpapan): The batch-normalization related default values above are appropriate for use in conjunction with the reference ResNet models released at https://github.com/KaimingHe/deep-residual-networks. When training ResNets from scratch, they might need to be tuned. Args: is_training: Whether or not we are training the parameters in the batch normalization layers of the model. (deprecated) weight_decay: The weight decay to use for regularizing the model. batch_norm_decay: The moving average decay when estimating layer activation statistics in batch normalization. batch_norm_epsilon: Small constant to prevent division by zero when normalizing activations by their variance in batch normalization. batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the activations in the batch normalization layer. Returns: An `arg_scope` to use for the resnet models.
Defines the default ResNet arg scope.
[ "Defines", "the", "default", "ResNet", "arg", "scope", "." ]
def resnet_arg_scope(is_training=True, weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True): """Defines the default ResNet arg scope. TODO(gpapan): The batch-normalization related default values above are appropriate for use in conjunction with the reference ResNet models released at https://github.com/KaimingHe/deep-residual-networks. When training ResNets from scratch, they might need to be tuned. Args: is_training: Whether or not we are training the parameters in the batch normalization layers of the model. (deprecated) weight_decay: The weight decay to use for regularizing the model. batch_norm_decay: The moving average decay when estimating layer activation statistics in batch normalization. batch_norm_epsilon: Small constant to prevent division by zero when normalizing activations by their variance in batch normalization. batch_norm_scale: If True, uses an explicit `gamma` multiplier to scale the activations in the batch normalization layer. Returns: An `arg_scope` to use for the resnet models. """ batch_norm_params = { 'is_training': is_training, 'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': batch_norm_scale, 'updates_collections': ops.GraphKeys.UPDATE_OPS, } with arg_scope( [layers_lib.conv2d], weights_regularizer=regularizers.l2_regularizer(weight_decay), weights_initializer=initializers.variance_scaling_initializer(), activation_fn=nn_ops.relu, normalizer_fn=layers.batch_norm): with arg_scope([layers.batch_norm], **batch_norm_params): # The following implies padding='SAME' for pool1, which makes feature # alignment easier for dense prediction tasks. This is also used in # https://github.com/facebook/fb.resnet.torch. However the accompanying # code of 'Deep Residual Learning for Image Recognition' uses # padding='VALID' for pool1. You can switch to that choice by setting # tf.contrib.framework.arg_scope([tf.contrib.layers.max_pool2d], padding='VALID'). with arg_scope([layers.max_pool2d], padding='SAME') as arg_sc: return arg_sc
[ "def", "resnet_arg_scope", "(", "is_training", "=", "True", ",", "weight_decay", "=", "0.0001", ",", "batch_norm_decay", "=", "0.997", ",", "batch_norm_epsilon", "=", "1e-5", ",", "batch_norm_scale", "=", "True", ")", ":", "batch_norm_params", "=", "{", "'is_tra...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/slim/python/slim/nets/resnet_utils.py#L230-L278
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Entry.delete
(self, first, last=None)
Delete text from FIRST to LAST (not included).
Delete text from FIRST to LAST (not included).
[ "Delete", "text", "from", "FIRST", "to", "LAST", "(", "not", "included", ")", "." ]
def delete(self, first, last=None): """Delete text from FIRST to LAST (not included).""" self.tk.call(self._w, 'delete', first, last)
[ "def", "delete", "(", "self", ",", "first", ",", "last", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'delete'", ",", "first", ",", "last", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L2677-L2679
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/random.py
python
SystemRandom._stub
(self, *args, **kwds)
return None
Stub method. Not used for a system random number generator.
Stub method. Not used for a system random number generator.
[ "Stub", "method", ".", "Not", "used", "for", "a", "system", "random", "number", "generator", "." ]
def _stub(self, *args, **kwds): "Stub method. Not used for a system random number generator." return None
[ "def", "_stub", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "return", "None" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/random.py#L815-L817
pirobot/rbx2
2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a
rbx2_msgs/src/rbx2_msgs/srv/_SetBatteryLevel.py
python
SetBatteryLevelResponse._get_types
(self)
return self._slot_types
internal API method
internal API method
[ "internal", "API", "method" ]
def _get_types(self): """ internal API method """ return self._slot_types
[ "def", "_get_types", "(", "self", ")", ":", "return", "self", ".", "_slot_types" ]
https://github.com/pirobot/rbx2/blob/2a6544799fcf062e7b6bd5cf2981b2a84c0c7d2a/rbx2_msgs/src/rbx2_msgs/srv/_SetBatteryLevel.py#L133-L137
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/threading.py
python
BoundedSemaphore
(*args, **kwargs)
return _BoundedSemaphore(*args, **kwargs)
A factory function that returns a new bounded semaphore. A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity. If the semaphore is released too many times it's a sign of a bug. If not given, value defaults to 1. Like regular semaphores, bounded semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1.
A factory function that returns a new bounded semaphore.
[ "A", "factory", "function", "that", "returns", "a", "new", "bounded", "semaphore", "." ]
def BoundedSemaphore(*args, **kwargs): """A factory function that returns a new bounded semaphore. A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity. If the semaphore is released too many times it's a sign of a bug. If not given, value defaults to 1. Like regular semaphores, bounded semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ return _BoundedSemaphore(*args, **kwargs)
[ "def", "BoundedSemaphore", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_BoundedSemaphore", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/threading.py#L496-L512
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
SystemSettings.GetScreenType
(*args, **kwargs)
return _misc_.SystemSettings_GetScreenType(*args, **kwargs)
GetScreenType() -> int
GetScreenType() -> int
[ "GetScreenType", "()", "-", ">", "int" ]
def GetScreenType(*args, **kwargs): """GetScreenType() -> int""" return _misc_.SystemSettings_GetScreenType(*args, **kwargs)
[ "def", "GetScreenType", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "SystemSettings_GetScreenType", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L178-L180
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/codecs.py
python
IncrementalDecoder.setstate
(self, state)
Set the current state of the decoder. state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset().
Set the current state of the decoder.
[ "Set", "the", "current", "state", "of", "the", "decoder", "." ]
def setstate(self, state): """ Set the current state of the decoder. state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset(). """
[ "def", "setstate", "(", "self", ",", "state", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/codecs.py#L295-L301
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py
python
CodeGenerator.push_assign_tracking
(self)
Pushes a new layer for assignment tracking.
Pushes a new layer for assignment tracking.
[ "Pushes", "a", "new", "layer", "for", "assignment", "tracking", "." ]
def push_assign_tracking(self): """Pushes a new layer for assignment tracking.""" self._assign_stack.append(set())
[ "def", "push_assign_tracking", "(", "self", ")", ":", "self", ".", "_assign_stack", ".", "append", "(", "set", "(", ")", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py#L661-L663
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_edit.py
python
Edit.getObjsFromSelection
(self)
return self.edited_objects
Evaluate selection and return a valid object to edit. #to be used for app link support for selobj in Gui.Selection.getSelectionEx('', 0): for sub in selobj.SubElementNames: obj = selobj.Object obj_matrix = selobj.Object.getSubObject(sub, retType=4)
Evaluate selection and return a valid object to edit.
[ "Evaluate", "selection", "and", "return", "a", "valid", "object", "to", "edit", "." ]
def getObjsFromSelection(self): """Evaluate selection and return a valid object to edit. #to be used for app link support for selobj in Gui.Selection.getSelectionEx('', 0): for sub in selobj.SubElementNames: obj = selobj.Object obj_matrix = selobj.Object.getSubObject(sub, retType=4) """ selection = Gui.Selection.getSelection() self.edited_objects = [] if len(selection) > self.maxObjects: _err = translate("draft", "Too many objects selected, max number set to:") App.Console.PrintMessage(_err + " " + str(self.maxObjects) + "\n") return None for obj in selection: if self.has_obj_gui_tools(obj): self.edited_objects.append(obj) else: _wrn = translate("draft", ": this object is not editable") App.Console.PrintWarning(obj.Name + _wrn + "\n") return self.edited_objects
[ "def", "getObjsFromSelection", "(", "self", ")", ":", "selection", "=", "Gui", ".", "Selection", ".", "getSelection", "(", ")", "self", ".", "edited_objects", "=", "[", "]", "if", "len", "(", "selection", ")", ">", "self", ".", "maxObjects", ":", "_err",...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_edit.py#L797-L820
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/httplib.py
python
HTTPMessage.addheader
(self, key, value)
Add header for field key handling repeats.
Add header for field key handling repeats.
[ "Add", "header", "for", "field", "key", "handling", "repeats", "." ]
def addheader(self, key, value): """Add header for field key handling repeats.""" prev = self.dict.get(key) if prev is None: self.dict[key] = value else: combined = ", ".join((prev, value)) self.dict[key] = combined
[ "def", "addheader", "(", "self", ",", "key", ",", "value", ")", ":", "prev", "=", "self", ".", "dict", ".", "get", "(", "key", ")", "if", "prev", "is", "None", ":", "self", ".", "dict", "[", "key", "]", "=", "value", "else", ":", "combined", "=...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/httplib.py#L220-L227
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
GBSpan.SetRowspan
(*args, **kwargs)
return _core_.GBSpan_SetRowspan(*args, **kwargs)
SetRowspan(self, int rowspan)
SetRowspan(self, int rowspan)
[ "SetRowspan", "(", "self", "int", "rowspan", ")" ]
def SetRowspan(*args, **kwargs): """SetRowspan(self, int rowspan)""" return _core_.GBSpan_SetRowspan(*args, **kwargs)
[ "def", "SetRowspan", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "GBSpan_SetRowspan", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L15660-L15662
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/extract_volume_patches.py
python
_extract_volume_patches_tbe
()
return
ExtractVolumePatches TBE register
ExtractVolumePatches TBE register
[ "ExtractVolumePatches", "TBE", "register" ]
def _extract_volume_patches_tbe(): """ExtractVolumePatches TBE register""" return
[ "def", "_extract_volume_patches_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/extract_volume_patches.py#L37-L39
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/polynomial/legendre.py
python
legadd
(c1, c2)
return pu.trimseq(ret)
Add one Legendre series to another. Returns the sum of two Legendre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Legendre series of their sum. See Also -------- legsub, legmulx, legmul, legdiv, legpow Notes ----- Unlike multiplication, division, etc., the sum of two Legendre series is a Legendre series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> L.legadd(c1,c2) array([ 4., 4., 4.])
Add one Legendre series to another.
[ "Add", "one", "Legendre", "series", "to", "another", "." ]
def legadd(c1, c2): """ Add one Legendre series to another. Returns the sum of two Legendre series `c1` + `c2`. The arguments are sequences of coefficients ordered from lowest order term to highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- out : ndarray Array representing the Legendre series of their sum. See Also -------- legsub, legmulx, legmul, legdiv, legpow Notes ----- Unlike multiplication, division, etc., the sum of two Legendre series is a Legendre series (without having to "reproject" the result onto the basis set) so addition, just like that of "standard" polynomials, is simply "component-wise." Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> L.legadd(c1,c2) array([ 4., 4., 4.]) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c1[:c2.size] += c2 ret = c1 else: c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret)
[ "def", "legadd", "(", "c1", ",", "c2", ")", ":", "# c1, c2 are trimmed copies", "[", "c1", ",", "c2", "]", "=", "pu", ".", "as_series", "(", "[", "c1", ",", "c2", "]", ")", "if", "len", "(", "c1", ")", ">", "len", "(", "c2", ")", ":", "c1", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/legendre.py#L333-L380
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/swagger_spec_validator/ref_validators.py
python
in_scope
(resolver, ref_dict)
Context manager to assume the given scope for the passed in resolver. The resolver's original scope is restored when exiting the context manager. :type resolver: :class:`jsonschema.RefResolver :type ref_dict: dict
Context manager to assume the given scope for the passed in resolver.
[ "Context", "manager", "to", "assume", "the", "given", "scope", "for", "the", "passed", "in", "resolver", "." ]
def in_scope(resolver, ref_dict): """Context manager to assume the given scope for the passed in resolver. The resolver's original scope is restored when exiting the context manager. :type resolver: :class:`jsonschema.RefResolver :type ref_dict: dict """ if 'x-scope' not in ref_dict: yield else: saved_scope_stack = resolver._scopes_stack try: resolver._scopes_stack = ref_dict['x-scope'] yield finally: resolver._scopes_stack = saved_scope_stack
[ "def", "in_scope", "(", "resolver", ",", "ref_dict", ")", ":", "if", "'x-scope'", "not", "in", "ref_dict", ":", "yield", "else", ":", "saved_scope_stack", "=", "resolver", ".", "_scopes_stack", "try", ":", "resolver", ".", "_scopes_stack", "=", "ref_dict", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/swagger_spec_validator/ref_validators.py#L206-L222
MtnViewJohn/context-free
757d7bde9742f201cec61bd195dda98093edd1e8
src-scintilla/scripts/FileGenerator.py
python
UpdateLineInPlistFile
(path, key, value)
Replace a single string value preceded by 'key' in an XML plist file.
Replace a single string value preceded by 'key' in an XML plist file.
[ "Replace", "a", "single", "string", "value", "preceded", "by", "key", "in", "an", "XML", "plist", "file", "." ]
def UpdateLineInPlistFile(path, key, value): """Replace a single string value preceded by 'key' in an XML plist file. """ lines = [] keyCurrent = "" with codecs.open(path, "rb", "utf-8") as f: for l in f.readlines(): ls = l.strip() if ls.startswith("<key>"): keyCurrent = ls.replace("<key>", "").replace("</key>", "") elif ls.startswith("<string>"): if keyCurrent == key: start, tag, rest = l.partition("<string>") val, etag, end = rest.partition("</string>") l = start + tag + value + etag + end lines.append(l) contents = "".join(lines) UpdateFile(path, contents)
[ "def", "UpdateLineInPlistFile", "(", "path", ",", "key", ",", "value", ")", ":", "lines", "=", "[", "]", "keyCurrent", "=", "\"\"", "with", "codecs", ".", "open", "(", "path", ",", "\"rb\"", ",", "\"utf-8\"", ")", "as", "f", ":", "for", "l", "in", ...
https://github.com/MtnViewJohn/context-free/blob/757d7bde9742f201cec61bd195dda98093edd1e8/src-scintilla/scripts/FileGenerator.py#L140-L157
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/plugin.py
python
FileReporter.translate_arcs
(self, arcs)
return arcs
Translate recorded arcs into reported arcs. Similar to :meth:`translate_lines`, but for arcs. `arcs` is a set of line number pairs. Returns a set of line number pairs. The default implementation returns `arcs` unchanged.
Translate recorded arcs into reported arcs.
[ "Translate", "recorded", "arcs", "into", "reported", "arcs", "." ]
def translate_arcs(self, arcs): """Translate recorded arcs into reported arcs. Similar to :meth:`translate_lines`, but for arcs. `arcs` is a set of line number pairs. Returns a set of line number pairs. The default implementation returns `arcs` unchanged. """ return arcs
[ "def", "translate_arcs", "(", "self", ",", "arcs", ")", ":", "return", "arcs" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/plugin.py#L306-L317
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/math/symbolic.py
python
Function.setArgType
(self,arg,type)
Sets an argument type specifier. Args: arg (int or str): an index or string naming an argument. type (Type or str): a :class:`Type` object or character type specifier for the specified argument.
Sets an argument type specifier.
[ "Sets", "an", "argument", "type", "specifier", "." ]
def setArgType(self,arg,type): """Sets an argument type specifier. Args: arg (int or str): an index or string naming an argument. type (Type or str): a :class:`Type` object or character type specifier for the specified argument. """ if self.argTypes is None: self.argTypes = [None]*len(self.argNames) index,name = self.checkArg(arg) self.argTypes[index] = Type(type)
[ "def", "setArgType", "(", "self", ",", "arg", ",", "type", ")", ":", "if", "self", ".", "argTypes", "is", "None", ":", "self", ".", "argTypes", "=", "[", "None", "]", "*", "len", "(", "self", ".", "argNames", ")", "index", ",", "name", "=", "self...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/symbolic.py#L2121-L2132
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
Decimal._round_ceiling
(self, prec)
Rounds up (not away from 0 if negative.)
Rounds up (not away from 0 if negative.)
[ "Rounds", "up", "(", "not", "away", "from", "0", "if", "negative", ".", ")" ]
def _round_ceiling(self, prec): """Rounds up (not away from 0 if negative.)""" if self._sign: return self._round_down(prec) else: return -self._round_down(prec)
[ "def", "_round_ceiling", "(", "self", ",", "prec", ")", ":", "if", "self", ".", "_sign", ":", "return", "self", ".", "_round_down", "(", "prec", ")", "else", ":", "return", "-", "self", ".", "_round_down", "(", "prec", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L1775-L1780
google/shaka-player-embedded
dabbeb5b47cc257b37b9a254661546352aaf0afe
shaka/tools/webidl/webidl/parser.py
python
IdlParser.p_DictionaryMember
(self, p)
return p[2]._replace(doc=p[1], docDebug=docDebug)
r"""DictionaryMember : MaybeDoc DictionaryMemberRest
r"""DictionaryMember : MaybeDoc DictionaryMemberRest
[ "r", "DictionaryMember", ":", "MaybeDoc", "DictionaryMemberRest" ]
def p_DictionaryMember(self, p): r"""DictionaryMember : MaybeDoc DictionaryMemberRest""" docDebug = self._get_debug(p, 1) if p[1] else None return p[2]._replace(doc=p[1], docDebug=docDebug)
[ "def", "p_DictionaryMember", "(", "self", ",", "p", ")", ":", "docDebug", "=", "self", ".", "_get_debug", "(", "p", ",", "1", ")", "if", "p", "[", "1", "]", "else", "None", "return", "p", "[", "2", "]", ".", "_replace", "(", "doc", "=", "p", "[...
https://github.com/google/shaka-player-embedded/blob/dabbeb5b47cc257b37b9a254661546352aaf0afe/shaka/tools/webidl/webidl/parser.py#L315-L318
zlgopen/awtk
2c49e854a78749d9092907c027a7fba9062be549
3rd/mbedtls/scripts/config.py
python
ConfigFile._format_template
(self, name, indent, middle)
return ''.join([indent, '' if setting.active else '//', middle, value]).rstrip()
Build a line for config.h for the given setting. The line has the form "<indent>#define <name> <value>" where <middle> is "#define <name> ".
Build a line for config.h for the given setting.
[ "Build", "a", "line", "for", "config", ".", "h", "for", "the", "given", "setting", "." ]
def _format_template(self, name, indent, middle): """Build a line for config.h for the given setting. The line has the form "<indent>#define <name> <value>" where <middle> is "#define <name> ". """ setting = self.settings[name] value = setting.value if value is None: value = '' # Normally the whitespace to separte the symbol name from the # value is part of middle, and there's no whitespace for a symbol # with no value. But if a symbol has been changed from having a # value to not having one, the whitespace is wrong, so fix it. if value: if middle[-1] not in '\t ': middle += ' ' else: middle = middle.rstrip() return ''.join([indent, '' if setting.active else '//', middle, value]).rstrip()
[ "def", "_format_template", "(", "self", ",", "name", ",", "indent", ",", "middle", ")", ":", "setting", "=", "self", ".", "settings", "[", "name", "]", "value", "=", "setting", ".", "value", "if", "value", "is", "None", ":", "value", "=", "''", "# No...
https://github.com/zlgopen/awtk/blob/2c49e854a78749d9092907c027a7fba9062be549/3rd/mbedtls/scripts/config.py#L395-L417
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py
python
_ExtensionDict._FindExtensionByName
(self, name)
return self._extended_message._extensions_by_name.get(name, None)
Tries to find a known extension with the specified name. Args: name: Extension full name. Returns: Extension field descriptor.
Tries to find a known extension with the specified name.
[ "Tries", "to", "find", "a", "known", "extension", "with", "the", "specified", "name", "." ]
def _FindExtensionByName(self, name): """Tries to find a known extension with the specified name. Args: name: Extension full name. Returns: Extension field descriptor. """ return self._extended_message._extensions_by_name.get(name, None)
[ "def", "_FindExtensionByName", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_extended_message", ".", "_extensions_by_name", ".", "get", "(", "name", ",", "None", ")" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L1141-L1150
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/service.py
python
RpcController.NotifyOnCancel
(self, callback)
Sets a callback to invoke on cancel. Asks that the given callback be called when the RPC is canceled. The callback will always be called exactly once. If the RPC completes without being canceled, the callback will be called after completion. If the RPC has already been canceled when NotifyOnCancel() is called, the callback will be called immediately. NotifyOnCancel() must be called no more than once per request.
Sets a callback to invoke on cancel.
[ "Sets", "a", "callback", "to", "invoke", "on", "cancel", "." ]
def NotifyOnCancel(self, callback): """Sets a callback to invoke on cancel. Asks that the given callback be called when the RPC is canceled. The callback will always be called exactly once. If the RPC completes without being canceled, the callback will be called after completion. If the RPC has already been canceled when NotifyOnCancel() is called, the callback will be called immediately. NotifyOnCancel() must be called no more than once per request. """ raise NotImplementedError
[ "def", "NotifyOnCancel", "(", "self", ",", "callback", ")", ":", "raise", "NotImplementedError" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/service.py#L187-L198
sailing-pmls/pmls-caffe
49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a
scripts/cpp_lint.py
python
_CppLintState.PrintErrorCounts
(self)
Print a summary of errors by category, and the total.
Print a summary of errors by category, and the total.
[ "Print", "a", "summary", "of", "errors", "by", "category", "and", "the", "total", "." ]
def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count)
[ "def", "PrintErrorCounts", "(", "self", ")", ":", "for", "category", ",", "count", "in", "self", ".", "errors_by_category", ".", "iteritems", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Category \\'%s\\' errors found: %d\\n'", "%", "(", "category...
https://github.com/sailing-pmls/pmls-caffe/blob/49e98bced9c6d5af7cd701d18ab235b5fd0e4b3a/scripts/cpp_lint.py#L757-L762
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/mailbox.py
python
BabylMessage.set_visible
(self, visible)
Set the Message representation of visible headers.
Set the Message representation of visible headers.
[ "Set", "the", "Message", "representation", "of", "visible", "headers", "." ]
def set_visible(self, visible): """Set the Message representation of visible headers.""" self._visible = Message(visible)
[ "def", "set_visible", "(", "self", ",", "visible", ")", ":", "self", ".", "_visible", "=", "Message", "(", "visible", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/mailbox.py#L1862-L1864
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/common/Bline.py
python
Bline.get
(self)
return self.bline
Returns the original param
Returns the original param
[ "Returns", "the", "original", "param" ]
def get(self): """ Returns the original param """ return self.bline
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "bline" ]
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Bline.py#L34-L38
stan-dev/math
5fd79f89933269a4ca4d8dd1fde2a36d53d4768c
lib/boost_1.75.0/libs/metaparse/tools/benchmark/benchmark.py
python
main
()
The main function of the script
The main function of the script
[ "The", "main", "function", "of", "the", "script" ]
def main(): """The main function of the script""" desc = 'Benchmark the files generated by generate.py' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='generated', help='The directory containing the sources to benchmark' ) parser.add_argument( '--out', dest='out_dir', default='../../doc', help='The output directory' ) parser.add_argument( '--include', dest='include', default='include', help='The directory containing the headeres for the benchmark' ) parser.add_argument( '--boost_headers', dest='boost_headers', default='../../../..', help='The directory containing the Boost headers (the boost directory)' ) parser.add_argument( '--compiler', dest='compiler', default='g++', help='The compiler to do the benchmark with' ) parser.add_argument( '--repeat_count', dest='repeat_count', type=int, default=5, help='How many times a measurement should be repeated.' ) args = parser.parse_args() compiler = compiler_info(args.compiler) results = benchmark( args.src_dir, args.compiler, [args.include, args.boost_headers], args.repeat_count ) plot_diagrams(results, configs_in(args.src_dir), compiler, args.out_dir)
[ "def", "main", "(", ")", ":", "desc", "=", "'Benchmark the files generated by generate.py'", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "desc", ")", "parser", ".", "add_argument", "(", "'--src'", ",", "dest", "=", "'src_dir'", ","...
https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/libs/metaparse/tools/benchmark/benchmark.py#L298-L350
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/inspect.py
python
isgeneratorfunction
(obj)
return _has_code_flag(obj, CO_GENERATOR)
Return true if the object is a user-defined generator function. Generator function objects provide the same attributes as functions. See help(isfunction) for a list of attributes.
Return true if the object is a user-defined generator function.
[ "Return", "true", "if", "the", "object", "is", "a", "user", "-", "defined", "generator", "function", "." ]
def isgeneratorfunction(obj): """Return true if the object is a user-defined generator function. Generator function objects provide the same attributes as functions. See help(isfunction) for a list of attributes.""" return _has_code_flag(obj, CO_GENERATOR)
[ "def", "isgeneratorfunction", "(", "obj", ")", ":", "return", "_has_code_flag", "(", "obj", ",", "CO_GENERATOR", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/inspect.py#L183-L188
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/math_ops.py
python
reduce_max
(input_tensor, reduction_indices=None, keep_dims=False, name=None)
return gen_math_ops._max(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
Computes the maximum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor.
Computes the maximum of elements across dimensions of a tensor.
[ "Computes", "the", "maximum", "of", "elements", "across", "dimensions", "of", "a", "tensor", "." ]
def reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the maximum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the default), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._max(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name)
[ "def", "reduce_max", "(", "input_tensor", ",", "reduction_indices", "=", "None", ",", "keep_dims", "=", "False", ",", "name", "=", "None", ")", ":", "return", "gen_math_ops", ".", "_max", "(", "input_tensor", ",", "_ReductionDims", "(", "input_tensor", ",", ...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/math_ops.py#L1152-L1176
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/_grad_ops.py
python
Conv2DBackpropFilter.__init__
(self, out_channel, kernel_size, pad_mode="valid", pad=0, pad_list=(0, 0, 0, 0), mode=1, stride=(1, 1), dilation=(1, 1, 1, 1), group=1, data_format="NCHW")
Initialize Convolution
Initialize Convolution
[ "Initialize", "Convolution" ]
def __init__(self, out_channel, kernel_size, pad_mode="valid", pad=0, pad_list=(0, 0, 0, 0), mode=1, stride=(1, 1), dilation=(1, 1, 1, 1), group=1, data_format="NCHW"): """Initialize Convolution""" self.init_prim_io_names(inputs=['out_backprop', 'input', 'filter_sizes'], outputs=['output']) self.out_channel = out_channel self.kernel_size = kernel_size self.mode = mode pad_mode = pad_mode.upper() self.add_prim_attr('pad_mode', pad_mode) if isinstance(pad, int): pad = (pad,) * 4 else: validator.check_equal_int(len(pad), 4, 'pad size', self.name) self.add_prim_attr("pad", pad) if isinstance(stride, tuple) and len(stride) == 4: self.stride = (stride[2], stride[3]) self.add_prim_attr('stride', self.stride) self.dilation = dilation self.group = group self.add_prim_attr('groups', group) self.format = validator.check_string(data_format, ['NCHW', 'NHWC'], 'format', self.name) if context.get_context("device_target") != "GPU" and self.format == "NHWC": raise ValueError("NHWC format only support in GPU target.") self.add_prim_attr('data_format', self.format)
[ "def", "__init__", "(", "self", ",", "out_channel", ",", "kernel_size", ",", "pad_mode", "=", "\"valid\"", ",", "pad", "=", "0", ",", "pad_list", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "mode", "=", "1", ",", "stride", "=", "(", ...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/_grad_ops.py#L410-L442
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeArchsDefault._VariableMapping
(self, sdkroot)
Returns the dictionary of variable mapping depending on the SDKROOT.
Returns the dictionary of variable mapping depending on the SDKROOT.
[ "Returns", "the", "dictionary", "of", "variable", "mapping", "depending", "on", "the", "SDKROOT", "." ]
def _VariableMapping(self, sdkroot): """Returns the dictionary of variable mapping depending on the SDKROOT.""" sdkroot = sdkroot.lower() if 'iphoneos' in sdkroot: return self._archs['ios'] elif 'iphonesimulator' in sdkroot: return self._archs['iossim'] else: return self._archs['mac']
[ "def", "_VariableMapping", "(", "self", ",", "sdkroot", ")", ":", "sdkroot", "=", "sdkroot", ".", "lower", "(", ")", "if", "'iphoneos'", "in", "sdkroot", ":", "return", "self", ".", "_archs", "[", "'ios'", "]", "elif", "'iphonesimulator'", "in", "sdkroot",...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L53-L61
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/third_party/six/six.py
python
_SixMetaPathImporter.is_package
(self, fullname)
return hasattr(self.__get_module(fullname), "__path__")
Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)
Return true, if the named module is a package.
[ "Return", "true", "if", "the", "named", "module", "is", "a", "package", "." ]
def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__")
[ "def", "is_package", "(", "self", ",", "fullname", ")", ":", "return", "hasattr", "(", "self", ".", "__get_module", "(", "fullname", ")", ",", "\"__path__\"", ")" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/third_party/six/six.py#L209-L216
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/portable_server.py
python
CompositeQueryHandler.get
(self, layer_id)
Handle GET request for JSON file for plugin.
Handle GET request for JSON file for plugin.
[ "Handle", "GET", "request", "for", "JSON", "file", "for", "plugin", "." ]
def get(self, layer_id): """Handle GET request for JSON file for plugin.""" if self.request.arguments["request"][0] == "Json": self.set_header("Content-Type", "text/plain; charset=utf-8") if ("is2d" in self.request.arguments.keys() and self.request.arguments["is2d"][0] == "t"): tornado.web.local_server_.LocalJsonHandler(self, True) else: tornado.web.local_server_.LocalJsonHandler(self, False) elif self.request.arguments["request"][0] == "ImageryMaps": if tornado.web.globe_.IsMbtiles(): self.set_header("Content-Type", "image/png") tornado.web.local_server_.LocalMapTileHandler( self, True, portable_globe.COMPOSITE_BASE_LAYER) else: self.set_header("Content-Type", "image/jpeg") tornado.web.local_server_.LocalMapTileHandler( self, True, int(layer_id)) elif self.request.arguments["request"][0] == "VectorMapsRaster": self.set_header("Content-Type", "image/png") tornado.web.local_server_.LocalMapTileHandler( self, False, int(layer_id)) elif self.request.arguments["request"][0] == "Icon": self.set_header("Content-Type", "image/png") (icon_path, use_layer, use_local) = ( tornado.web.local_server_.ConvertIconPath( self.request.arguments["icon_path"][0])) layer_id = int(layer_id) if not use_layer: layer_id = portable_globe.NON_COMPOSITE_LAYER tornado.web.local_server_.LocalIconHandler( self, icon_path, layer_id, use_local) else: self.set_header("Content-Type", "text/plain") print "Unknown query request: ", self.request.uri self.finish()
[ "def", "get", "(", "self", ",", "layer_id", ")", ":", "if", "self", ".", "request", ".", "arguments", "[", "\"request\"", "]", "[", "0", "]", "==", "\"Json\"", ":", "self", ".", "set_header", "(", "\"Content-Type\"", ",", "\"text/plain; charset=utf-8\"", "...
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/portable_server.py#L247-L287
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/grid.py
python
GridCellAttrProvider.UpdateAttrCols
(*args, **kwargs)
return _grid.GridCellAttrProvider_UpdateAttrCols(*args, **kwargs)
UpdateAttrCols(self, size_t pos, int numCols)
UpdateAttrCols(self, size_t pos, int numCols)
[ "UpdateAttrCols", "(", "self", "size_t", "pos", "int", "numCols", ")" ]
def UpdateAttrCols(*args, **kwargs): """UpdateAttrCols(self, size_t pos, int numCols)""" return _grid.GridCellAttrProvider_UpdateAttrCols(*args, **kwargs)
[ "def", "UpdateAttrCols", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellAttrProvider_UpdateAttrCols", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L706-L708
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGridPopulator.SetGrid
(*args, **kwargs)
return _propgrid.PropertyGridPopulator_SetGrid(*args, **kwargs)
SetGrid(self, PropertyGrid pg)
SetGrid(self, PropertyGrid pg)
[ "SetGrid", "(", "self", "PropertyGrid", "pg", ")" ]
def SetGrid(*args, **kwargs): """SetGrid(self, PropertyGrid pg)""" return _propgrid.PropertyGridPopulator_SetGrid(*args, **kwargs)
[ "def", "SetGrid", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridPopulator_SetGrid", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L2581-L2583
Cisco-Talos/moflow
ed71dfb0540d9e0d7a4c72f0881b58958d573728
BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py
python
SameElementsAs.__init__
(self, expected_seq)
Initialize. Args: expected_seq: a sequence
Initialize.
[ "Initialize", "." ]
def __init__(self, expected_seq): """Initialize. Args: expected_seq: a sequence """ self._expected_seq = expected_seq
[ "def", "__init__", "(", "self", ",", "expected_seq", ")", ":", "self", ".", "_expected_seq", "=", "expected_seq" ]
https://github.com/Cisco-Talos/moflow/blob/ed71dfb0540d9e0d7a4c72f0881b58958d573728/BAP-0.7-moflow/libtracewrap/libtrace/protobuf/python/mox.py#L1012-L1019
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py
python
get_selected_frame
(target)
return (frame, "")
Returns a tuple with (frame, error) where frame == None if error occurs
Returns a tuple with (frame, error) where frame == None if error occurs
[ "Returns", "a", "tuple", "with", "(", "frame", "error", ")", "where", "frame", "==", "None", "if", "error", "occurs" ]
def get_selected_frame(target): """ Returns a tuple with (frame, error) where frame == None if error occurs """ (thread, error) = get_selected_thread(target) if thread is None: return (None, error) frame = thread.GetSelectedFrame() if frame is None or not frame.IsValid(): return (None, VimPane.MSG_NO_FRAME) return (frame, "")
[ "def", "get_selected_frame", "(", "target", ")", ":", "(", "thread", ",", "error", ")", "=", "get_selected_thread", "(", "target", ")", "if", "thread", "is", "None", ":", "return", "(", "None", ",", "error", ")", "frame", "=", "thread", ".", "GetSelected...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L89-L98