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
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/compile_settings_gcc.py
python
load_gcc_common_settings
(conf)
Setup all compiler/linker flags with are shared over all targets using the gcc compiler !!! But not the actual compiler, since the compiler depends on the target !!!
Setup all compiler/linker flags with are shared over all targets using the gcc compiler !!! But not the actual compiler, since the compiler depends on the target !!!
[ "Setup", "all", "compiler", "/", "linker", "flags", "with", "are", "shared", "over", "all", "targets", "using", "the", "gcc", "compiler", "!!!", "But", "not", "the", "actual", "compiler", "since", "the", "compiler", "depends", "on", "the", "target", "!!!" ]
def load_gcc_common_settings(conf): """ Setup all compiler/linker flags with are shared over all targets using the gcc compiler !!! But not the actual compiler, since the compiler depends on the target !!! """ v = conf.env # Figure out GCC compiler version try: conf.get_cc_version( [ v['CC'] ], gcc=True) except: # Can happen if we don't have an GCC installed (code drop stripped of GCC cross compiler) conf.env.CC_VERSION = (0,0,0) # AR Tools v['ARFLAGS'] = 'rcs' v['AR_TGT_F'] = '' # CC/CXX Compiler v['CC_NAME'] = v['CXX_NAME'] = 'gcc' v['CC_SRC_F'] = v['CXX_SRC_F'] = [] v['CC_TGT_F'] = v['CXX_TGT_F'] = ['-c', '-o'] v['CPPPATH_SYSTEM_ST'] = '-isystem%s' v['CPPPATH_ST'] = '-I%s' v['DEFINES_ST'] = '-D%s' # Linker v['CCLNK_SRC_F'] = v['CXXLNK_SRC_F'] = [] v['CCLNK_TGT_F'] = v['CXXLNK_TGT_F'] = '-o' v['LIB_ST'] = '-l%s' v['LIBPATH_ST'] = '-L%s' v['STLIB_ST'] = '-l%s' v['STLIBPATH_ST'] = '-L%s' # shared library settings v['CFLAGS_cshlib'] = v['CFLAGS_cxxshlib'] = ['-fpic'] v['CXXFLAGS_cshlib'] = v['CXXFLAGS_cxxshlib'] = ['-fpic'] v['LINKFLAGS_cshlib'] = ['-shared'] v['LINKFLAGS_cxxshlib'] = ['-shared'] # static library settings v['CFLAGS_cstlib'] = v['CFLAGS_cxxstlib'] = ['-fpic'] v['CXXFLAGS_cstlib'] = v['CXXFLAGS_cxxstlib'] = ['-fpic'] v['LINKFLAGS_cxxstlib'] = ['-Wl,-Bstatic'] v['LINKFLAGS_cxxshtib'] = ['-Wl,-Bstatic'] # Set common compiler flags COMMON_COMPILER_FLAGS = [ '-Wall', # Generate more warnings '-Werror', # Tread Warnings as Errors '-ffast-math', # Enable fast math '-flax-vector-conversions', # Enable automatic casting between SIMD vector types '-fvisibility=hidden', # Disable some warnings '-Wno-char-subscripts', '-Wno-unknown-pragmas', '-Wno-unused-variable', '-Wno-unused-value', '-Wno-parentheses', '-Wno-switch', '-Wno-unused-function', '-Wno-unused-result', '-Wno-multichar', '-Wno-format-security', '-Wno-empty-body', '-Wno-comment', '-Wno-char-subscripts', '-Wno-sign-compare', '-Wno-narrowing', '-Wno-write-strings', '-Wno-format', '-Wno-strict-aliasing', '-Wno-unused-but-set-variable', '-Wno-maybe-uninitialized', '-Wno-strict-overflow', '-Wno-uninitialized', '-Wno-unused-local-typedefs', '-Wno-deprecated', ] if conf.env.CC_VERSION[0] >= '4' and conf.env.CC_VERSION[1] >= '8' and conf.env.CC_VERSION[2] >= '0': COMMON_COMPILER_FLAGS += [ '-Wno-unused-result', '-Wno-sizeof-pointer-memaccess', '-Wno-array-bounds', ] # Copy common flags to prevent modifing references v['CFLAGS'] += COMMON_COMPILER_FLAGS[:] v['CXXFLAGS'] += COMMON_COMPILER_FLAGS[:] + [ '-fno-rtti', # Disable RTTI '-fno-exceptions', # Disable Exceptions '-fvisibility-inlines-hidden', '-std=c++14', # Enable c++14 features # Disable some C++ specific warnings '-Wno-invalid-offsetof', '-Wno-reorder', '-Wno-conversion-null', '-Wno-overloaded-virtual', ] # Linker Flags v['LINKFLAGS'] += ['-Wl,--rpath=$ORIGIN'] v['SHLIB_MARKER'] = '-Wl,-Bdynamic' v['SONAME_ST'] = '-Wl,-h,%s' v['STLIB_MARKER'] = '-Wl,-Bstatic' # Compile options appended if compiler optimization is disabled v['COMPILER_FLAGS_DisableOptimization'] = [ '-O0', '-fno-inline' ] # Compile options appended if debug symbols are generated v['COMPILER_FLAGS_DebugSymbols'] = [ '-g2', '-gdwarf-2' ] # Linker flags when building with debug symbols v['LINKFLAGS_DebugSymbols'] = [] # Store settings for show includes option v['SHOWINCLUDES_cflags'] = ['-H'] v['SHOWINCLUDES_cxxflags'] = ['-H'] # Store settings for preprocess to file option v['PREPROCESS_cflags'] = ['-E', '-dD'] v['PREPROCESS_cxxflags'] = ['-E', '-dD'] v['PREPROCESS_cc_tgt_f'] = ['-o'] v['PREPROCESS_cxx_tgt_f'] = ['-o'] # Store settings for preprocess to file option v['DISASSEMBLY_cflags'] = ['-S', '-fverbose-asm'] v['DISASSEMBLY_cxxflags'] = ['-S', '-fverbose-asm'] v['DISASSEMBLY_cc_tgt_f'] = ['-o'] v['DISASSEMBLY_cxx_tgt_f'] = ['-o'] # Store setting for static code analyzer always_disabled_flags = ['-Wno-unknown-pragmas'] disabled_flags = [ '-Wno-unused-variable' , '-Wno-unused-value' , '-Wno-unused-function' , '-Wno-multichar' , '-Wno-parentheses' , '-Wno-switch' , '-Wno-comment' # '-Wno-subscripts', #, '-Wno-address' #, '-Wno-self-assign' #, '-Wno-unneeded-internal-declaration' , '-Wno-strict-aliasing' ] force_enable_flags = [] cxx_only_flag = ['-Wno-overloaded-virtual', '-Wno-reorder'] analyzer_flags = ['-Wall'] + always_disabled_flags + disabled_flags + force_enable_flags v['STATIC_CODE_ANALYZE_cflags'] = list(analyzer_flags) v['STATIC_CODE_ANALYZE_cxxflags'] = list(analyzer_flags + cxx_only_flag)
[ "def", "load_gcc_common_settings", "(", "conf", ")", ":", "v", "=", "conf", ".", "env", "# Figure out GCC compiler version", "try", ":", "conf", ".", "get_cc_version", "(", "[", "v", "[", "'CC'", "]", "]", ",", "gcc", "=", "True", ")", "except", ":", "# Can happen if we don't have an GCC installed (code drop stripped of GCC cross compiler)", "conf", ".", "env", ".", "CC_VERSION", "=", "(", "0", ",", "0", ",", "0", ")", "# AR Tools", "v", "[", "'ARFLAGS'", "]", "=", "'rcs'", "v", "[", "'AR_TGT_F'", "]", "=", "''", "# CC/CXX Compiler\t", "v", "[", "'CC_NAME'", "]", "=", "v", "[", "'CXX_NAME'", "]", "=", "'gcc'", "v", "[", "'CC_SRC_F'", "]", "=", "v", "[", "'CXX_SRC_F'", "]", "=", "[", "]", "v", "[", "'CC_TGT_F'", "]", "=", "v", "[", "'CXX_TGT_F'", "]", "=", "[", "'-c'", ",", "'-o'", "]", "v", "[", "'CPPPATH_SYSTEM_ST'", "]", "=", "'-isystem%s'", "v", "[", "'CPPPATH_ST'", "]", "=", "'-I%s'", "v", "[", "'DEFINES_ST'", "]", "=", "'-D%s'", "# Linker", "v", "[", "'CCLNK_SRC_F'", "]", "=", "v", "[", "'CXXLNK_SRC_F'", "]", "=", "[", "]", "v", "[", "'CCLNK_TGT_F'", "]", "=", "v", "[", "'CXXLNK_TGT_F'", "]", "=", "'-o'", "v", "[", "'LIB_ST'", "]", "=", "'-l%s'", "v", "[", "'LIBPATH_ST'", "]", "=", "'-L%s'", "v", "[", "'STLIB_ST'", "]", "=", "'-l%s'", "v", "[", "'STLIBPATH_ST'", "]", "=", "'-L%s'", "# shared library settings\t", "v", "[", "'CFLAGS_cshlib'", "]", "=", "v", "[", "'CFLAGS_cxxshlib'", "]", "=", "[", "'-fpic'", "]", "v", "[", "'CXXFLAGS_cshlib'", "]", "=", "v", "[", "'CXXFLAGS_cxxshlib'", "]", "=", "[", "'-fpic'", "]", "v", "[", "'LINKFLAGS_cshlib'", "]", "=", "[", "'-shared'", "]", "v", "[", "'LINKFLAGS_cxxshlib'", "]", "=", "[", "'-shared'", "]", "# static library settings\t", "v", "[", "'CFLAGS_cstlib'", "]", "=", "v", "[", "'CFLAGS_cxxstlib'", "]", "=", "[", "'-fpic'", "]", "v", "[", "'CXXFLAGS_cstlib'", "]", "=", "v", "[", "'CXXFLAGS_cxxstlib'", "]", "=", "[", "'-fpic'", "]", "v", "[", "'LINKFLAGS_cxxstlib'", "]", "=", "[", "'-Wl,-Bstatic'", "]", "v", "[", "'LINKFLAGS_cxxshtib'", "]", "=", "[", "'-Wl,-Bstatic'", "]", "# Set common compiler flags\t", "COMMON_COMPILER_FLAGS", "=", "[", "'-Wall'", ",", "# Generate more warnings", "'-Werror'", ",", "# Tread Warnings as Errors", "'-ffast-math'", ",", "# Enable fast math", "'-flax-vector-conversions'", ",", "# Enable automatic casting between SIMD vector types", "'-fvisibility=hidden'", ",", "# Disable some warnings\t\t", "'-Wno-char-subscripts'", ",", "'-Wno-unknown-pragmas'", ",", "'-Wno-unused-variable'", ",", "'-Wno-unused-value'", ",", "'-Wno-parentheses'", ",", "'-Wno-switch'", ",", "'-Wno-unused-function'", ",", "'-Wno-unused-result'", ",", "'-Wno-multichar'", ",", "'-Wno-format-security'", ",", "'-Wno-empty-body'", ",", "'-Wno-comment'", ",", "'-Wno-char-subscripts'", ",", "'-Wno-sign-compare'", ",", "'-Wno-narrowing'", ",", "'-Wno-write-strings'", ",", "'-Wno-format'", ",", "'-Wno-strict-aliasing'", ",", "'-Wno-unused-but-set-variable'", ",", "'-Wno-maybe-uninitialized'", ",", "'-Wno-strict-overflow'", ",", "'-Wno-uninitialized'", ",", "'-Wno-unused-local-typedefs'", ",", "'-Wno-deprecated'", ",", "]", "if", "conf", ".", "env", ".", "CC_VERSION", "[", "0", "]", ">=", "'4'", "and", "conf", ".", "env", ".", "CC_VERSION", "[", "1", "]", ">=", "'8'", "and", "conf", ".", "env", ".", "CC_VERSION", "[", "2", "]", ">=", "'0'", ":", "COMMON_COMPILER_FLAGS", "+=", "[", "'-Wno-unused-result'", ",", "'-Wno-sizeof-pointer-memaccess'", ",", "'-Wno-array-bounds'", ",", "]", "# Copy common flags to prevent modifing references", "v", "[", "'CFLAGS'", "]", "+=", "COMMON_COMPILER_FLAGS", "[", ":", "]", "v", "[", "'CXXFLAGS'", "]", "+=", "COMMON_COMPILER_FLAGS", "[", ":", "]", "+", "[", "'-fno-rtti'", ",", "# Disable RTTI", "'-fno-exceptions'", ",", "# Disable Exceptions\t", "'-fvisibility-inlines-hidden'", ",", "'-std=c++14'", ",", "# Enable c++14 features", "# Disable some C++ specific warnings\t", "'-Wno-invalid-offsetof'", ",", "'-Wno-reorder'", ",", "'-Wno-conversion-null'", ",", "'-Wno-overloaded-virtual'", ",", "]", "# Linker Flags", "v", "[", "'LINKFLAGS'", "]", "+=", "[", "'-Wl,--rpath=$ORIGIN'", "]", "v", "[", "'SHLIB_MARKER'", "]", "=", "'-Wl,-Bdynamic'", "v", "[", "'SONAME_ST'", "]", "=", "'-Wl,-h,%s'", "v", "[", "'STLIB_MARKER'", "]", "=", "'-Wl,-Bstatic'", "# Compile options appended if compiler optimization is disabled", "v", "[", "'COMPILER_FLAGS_DisableOptimization'", "]", "=", "[", "'-O0'", ",", "'-fno-inline'", "]", "# Compile options appended if debug symbols are generated\t", "v", "[", "'COMPILER_FLAGS_DebugSymbols'", "]", "=", "[", "'-g2'", ",", "'-gdwarf-2'", "]", "# Linker flags when building with debug symbols", "v", "[", "'LINKFLAGS_DebugSymbols'", "]", "=", "[", "]", "# Store settings for show includes option", "v", "[", "'SHOWINCLUDES_cflags'", "]", "=", "[", "'-H'", "]", "v", "[", "'SHOWINCLUDES_cxxflags'", "]", "=", "[", "'-H'", "]", "# Store settings for preprocess to file option", "v", "[", "'PREPROCESS_cflags'", "]", "=", "[", "'-E'", ",", "'-dD'", "]", "v", "[", "'PREPROCESS_cxxflags'", "]", "=", "[", "'-E'", ",", "'-dD'", "]", "v", "[", "'PREPROCESS_cc_tgt_f'", "]", "=", "[", "'-o'", "]", "v", "[", "'PREPROCESS_cxx_tgt_f'", "]", "=", "[", "'-o'", "]", "# Store settings for preprocess to file option", "v", "[", "'DISASSEMBLY_cflags'", "]", "=", "[", "'-S'", ",", "'-fverbose-asm'", "]", "v", "[", "'DISASSEMBLY_cxxflags'", "]", "=", "[", "'-S'", ",", "'-fverbose-asm'", "]", "v", "[", "'DISASSEMBLY_cc_tgt_f'", "]", "=", "[", "'-o'", "]", "v", "[", "'DISASSEMBLY_cxx_tgt_f'", "]", "=", "[", "'-o'", "]", "# Store setting for static code analyzer", "always_disabled_flags", "=", "[", "'-Wno-unknown-pragmas'", "]", "disabled_flags", "=", "[", "'-Wno-unused-variable'", ",", "'-Wno-unused-value'", ",", "'-Wno-unused-function'", ",", "'-Wno-multichar'", ",", "'-Wno-parentheses'", ",", "'-Wno-switch'", ",", "'-Wno-comment'", "# '-Wno-subscripts',", "#, '-Wno-address'", "#, '-Wno-self-assign'", "#, '-Wno-unneeded-internal-declaration'", ",", "'-Wno-strict-aliasing'", "]", "force_enable_flags", "=", "[", "]", "cxx_only_flag", "=", "[", "'-Wno-overloaded-virtual'", ",", "'-Wno-reorder'", "]", "analyzer_flags", "=", "[", "'-Wall'", "]", "+", "always_disabled_flags", "+", "disabled_flags", "+", "force_enable_flags", "v", "[", "'STATIC_CODE_ANALYZE_cflags'", "]", "=", "list", "(", "analyzer_flags", ")", "v", "[", "'STATIC_CODE_ANALYZE_cxxflags'", "]", "=", "list", "(", "analyzer_flags", "+", "cxx_only_flag", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/compile_settings_gcc.py#L6-L171
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__getslice__
(self, start, stop)
return self._values[start:stop]
Retrieves the subset of items from between the specified indices.
Retrieves the subset of items from between the specified indices.
[ "Retrieves", "the", "subset", "of", "items", "from", "between", "the", "specified", "indices", "." ]
def __getslice__(self, start, stop): """Retrieves the subset of items from between the specified indices.""" return self._values[start:stop]
[ "def", "__getslice__", "(", "self", ",", "start", ",", "stop", ")", ":", "return", "self", ".", "_values", "[", "start", ":", "stop", "]" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/containers.py#L308-L310
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py
python
ParseFlags
(resp)
return tuple(mo.group('flags').split())
Convert IMAP4 flags response to python tuple.
Convert IMAP4 flags response to python tuple.
[ "Convert", "IMAP4", "flags", "response", "to", "python", "tuple", "." ]
def ParseFlags(resp): """Convert IMAP4 flags response to python tuple.""" mo = Flags.match(resp) if not mo: return () return tuple(mo.group('flags').split())
[ "def", "ParseFlags", "(", "resp", ")", ":", "mo", "=", "Flags", ".", "match", "(", "resp", ")", "if", "not", "mo", ":", "return", "(", ")", "return", "tuple", "(", "mo", ".", "group", "(", "'flags'", ")", ".", "split", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/imaplib.py#L1458-L1466
wujixiu/helmet-detection
8eff5c59ddfba5a29e0b76aeb48babcb49246178
hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py
python
_IsTestFilename
(filename)
Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise.
Determines if the given filename has a suffix that identifies it as a test.
[ "Determines", "if", "the", "given", "filename", "has", "a", "suffix", "that", "identifies", "it", "as", "a", "test", "." ]
def _IsTestFilename(filename): """Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise. """ if (filename.endswith('_test.cc') or filename.endswith('_unittest.cc') or filename.endswith('_regtest.cc')): return True else: return False
[ "def", "_IsTestFilename", "(", "filename", ")", ":", "if", "(", "filename", ".", "endswith", "(", "'_test.cc'", ")", "or", "filename", ".", "endswith", "(", "'_unittest.cc'", ")", "or", "filename", ".", "endswith", "(", "'_regtest.cc'", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
https://github.com/wujixiu/helmet-detection/blob/8eff5c59ddfba5a29e0b76aeb48babcb49246178/hardhat-wearing-detection/SSD-RPA/scripts/cpp_lint.py#L3607-L3621
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
caffe2/python/task.py
python
Task.__init__
( self, step=None, outputs=None, workspace_type=None, group=None, node=None, name=None, num_instances=None)
Instantiate a Task and add it to the current TaskGroup and Node. Args: step: If provided, this task will run this ExecutionStep. outputs: If provided, the task will return the provided outputs to the client at completion time. node: If provided, force task execution on the given node. name: Name of the Task. num_instances: If provided, this task will be cloned num_instances times at runtime, and all instances will run concurrently.
Instantiate a Task and add it to the current TaskGroup and Node.
[ "Instantiate", "a", "Task", "and", "add", "it", "to", "the", "current", "TaskGroup", "and", "Node", "." ]
def __init__( self, step=None, outputs=None, workspace_type=None, group=None, node=None, name=None, num_instances=None): """ Instantiate a Task and add it to the current TaskGroup and Node. Args: step: If provided, this task will run this ExecutionStep. outputs: If provided, the task will return the provided outputs to the client at completion time. node: If provided, force task execution on the given node. name: Name of the Task. num_instances: If provided, this task will be cloned num_instances times at runtime, and all instances will run concurrently. """ if not name and isinstance(step, core.ExecutionStep): name = step.Proto().name if not name: name = 'task' # register this node name with active context self.node = str(Node.current(None if node is None else Node(node))) self.group = TaskGroup.current(group, required=False) self.name = Task._get_next_name(self.node, self.group, name) # may need to be temporarily removed later if Task used as a context if self.group is not None: self.group._tasks_to_add.append(self) self._already_used = False self._step = None self._step_with_setup = None self._outputs = [] if step is not None: self.set_step(step) if outputs is not None: self.add_outputs(outputs) self._pipeline = None self._is_pipeline_context = False self._workspace_type = workspace_type self._report_net = None self._num_instances = num_instances
[ "def", "__init__", "(", "self", ",", "step", "=", "None", ",", "outputs", "=", "None", ",", "workspace_type", "=", "None", ",", "group", "=", "None", ",", "node", "=", "None", ",", "name", "=", "None", ",", "num_instances", "=", "None", ")", ":", "if", "not", "name", "and", "isinstance", "(", "step", ",", "core", ".", "ExecutionStep", ")", ":", "name", "=", "step", ".", "Proto", "(", ")", ".", "name", "if", "not", "name", ":", "name", "=", "'task'", "# register this node name with active context", "self", ".", "node", "=", "str", "(", "Node", ".", "current", "(", "None", "if", "node", "is", "None", "else", "Node", "(", "node", ")", ")", ")", "self", ".", "group", "=", "TaskGroup", ".", "current", "(", "group", ",", "required", "=", "False", ")", "self", ".", "name", "=", "Task", ".", "_get_next_name", "(", "self", ".", "node", ",", "self", ".", "group", ",", "name", ")", "# may need to be temporarily removed later if Task used as a context", "if", "self", ".", "group", "is", "not", "None", ":", "self", ".", "group", ".", "_tasks_to_add", ".", "append", "(", "self", ")", "self", ".", "_already_used", "=", "False", "self", ".", "_step", "=", "None", "self", ".", "_step_with_setup", "=", "None", "self", ".", "_outputs", "=", "[", "]", "if", "step", "is", "not", "None", ":", "self", ".", "set_step", "(", "step", ")", "if", "outputs", "is", "not", "None", ":", "self", ".", "add_outputs", "(", "outputs", ")", "self", ".", "_pipeline", "=", "None", "self", ".", "_is_pipeline_context", "=", "False", "self", ".", "_workspace_type", "=", "workspace_type", "self", ".", "_report_net", "=", "None", "self", ".", "_num_instances", "=", "num_instances" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/caffe2/python/task.py#L492-L536
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/fractions.py
python
Fraction.__trunc__
(a)
trunc(a)
trunc(a)
[ "trunc", "(", "a", ")" ]
def __trunc__(a): """trunc(a)""" if a._numerator < 0: return -(-a._numerator // a._denominator) else: return a._numerator // a._denominator
[ "def", "__trunc__", "(", "a", ")", ":", "if", "a", ".", "_numerator", "<", "0", ":", "return", "-", "(", "-", "a", ".", "_numerator", "//", "a", ".", "_denominator", ")", "else", ":", "return", "a", ".", "_numerator", "//", "a", ".", "_denominator" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/fractions.py#L504-L509
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/urlhandler/protocol_alt.py
python
serial_class_for_url
(url)
return (''.join([parts.netloc, parts.path]), cls)
extract host and port from an URL string
extract host and port from an URL string
[ "extract", "host", "and", "port", "from", "an", "URL", "string" ]
def serial_class_for_url(url): """extract host and port from an URL string""" parts = urlparse.urlsplit(url) if parts.scheme != 'alt': raise serial.SerialException( 'expected a string in the form "alt://port[?option[=value][&option[=value]]]": ' 'not starting with alt:// ({!r})'.format(parts.scheme)) class_name = 'Serial' try: for option, values in urlparse.parse_qs(parts.query, True).items(): if option == 'class': class_name = values[0] else: raise ValueError('unknown option: {!r}'.format(option)) except ValueError as e: raise serial.SerialException( 'expected a string in the form ' '"alt://port[?option[=value][&option[=value]]]": {!r}'.format(e)) if not hasattr(serial, class_name): raise ValueError('unknown class: {!r}'.format(class_name)) cls = getattr(serial, class_name) if not issubclass(cls, serial.Serial): raise ValueError('class {!r} is not an instance of Serial'.format(class_name)) return (''.join([parts.netloc, parts.path]), cls)
[ "def", "serial_class_for_url", "(", "url", ")", ":", "parts", "=", "urlparse", ".", "urlsplit", "(", "url", ")", "if", "parts", ".", "scheme", "!=", "'alt'", ":", "raise", "serial", ".", "SerialException", "(", "'expected a string in the form \"alt://port[?option[=value][&option[=value]]]\": '", "'not starting with alt:// ({!r})'", ".", "format", "(", "parts", ".", "scheme", ")", ")", "class_name", "=", "'Serial'", "try", ":", "for", "option", ",", "values", "in", "urlparse", ".", "parse_qs", "(", "parts", ".", "query", ",", "True", ")", ".", "items", "(", ")", ":", "if", "option", "==", "'class'", ":", "class_name", "=", "values", "[", "0", "]", "else", ":", "raise", "ValueError", "(", "'unknown option: {!r}'", ".", "format", "(", "option", ")", ")", "except", "ValueError", "as", "e", ":", "raise", "serial", ".", "SerialException", "(", "'expected a string in the form '", "'\"alt://port[?option[=value][&option[=value]]]\": {!r}'", ".", "format", "(", "e", ")", ")", "if", "not", "hasattr", "(", "serial", ",", "class_name", ")", ":", "raise", "ValueError", "(", "'unknown class: {!r}'", ".", "format", "(", "class_name", ")", ")", "cls", "=", "getattr", "(", "serial", ",", "class_name", ")", "if", "not", "issubclass", "(", "cls", ",", "serial", ".", "Serial", ")", ":", "raise", "ValueError", "(", "'class {!r} is not an instance of Serial'", ".", "format", "(", "class_name", ")", ")", "return", "(", "''", ".", "join", "(", "[", "parts", ".", "netloc", ",", "parts", ".", "path", "]", ")", ",", "cls", ")" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/urlhandler/protocol_alt.py#L27-L50
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/control-examples/baxterserialrelay.py
python
mainRosControllerToKlamptRobot
(klampt_robot_model_fn,klampt_serial_port)
Relays ROS Baxter controller messages to and from Klamp't simulated robot
Relays ROS Baxter controller messages to and from Klamp't simulated robot
[ "Relays", "ROS", "Baxter", "controller", "messages", "to", "and", "from", "Klamp", "t", "simulated", "robot" ]
def mainRosControllerToKlamptRobot(klampt_robot_model_fn,klampt_serial_port): """Relays ROS Baxter controller messages to and from Klamp't simulated robot""" rospy.init_node('klampt_sim') #load robot file world = WorldModel() world.enableGeometryLoading(False) res = world.readFile(klampt_robot_model_fn) if not res: print 'Error, could not load klampt model from',klampt_robot_model_fn exit(1) if world.numRobots()==0: print 'Error, klampt model',klampt_robot_model_fn,'did not contain a robot' exit(1) klampt_robot_model = world.robot(0) print "Load successful" #print some info robotName = klampt_robot_model.getName() linkNames = [klampt_robot_model.link(i).getName() for i in range(klampt_robot_model.numLinks())] print "Running controller listening on topic /%s/limb/right/joint_command and"%(robotName,) print "and /%s/limb/left/joint_command andd publishing on topic"%(robotName,) print "/%s/joint_states"%(robotName,) print "Klamp't link names are:",linkNames #advertise version 1.0.0 of the Baxter software print "Emulating ROS Baxter API version 1.0.0" rospy.set_param('/rethink/software_version', '1.0.0') #create the ROS controller c = rosbaxtercontroller.make(klampt_robot_model) #launch the serial client to connect to a given host and relay messages from the socket to/from ROS host = 'localhost' port = klampt_serial_port s = ControllerClient((host,port),c) print "Running Baxter controller -> Klamp't robot relay..." try: asyncore.loop() except KeyboardInterrupt: print "Ctrl+C pressed, exiting..."
[ "def", "mainRosControllerToKlamptRobot", "(", "klampt_robot_model_fn", ",", "klampt_serial_port", ")", ":", "rospy", ".", "init_node", "(", "'klampt_sim'", ")", "#load robot file", "world", "=", "WorldModel", "(", ")", "world", ".", "enableGeometryLoading", "(", "False", ")", "res", "=", "world", ".", "readFile", "(", "klampt_robot_model_fn", ")", "if", "not", "res", ":", "print", "'Error, could not load klampt model from'", ",", "klampt_robot_model_fn", "exit", "(", "1", ")", "if", "world", ".", "numRobots", "(", ")", "==", "0", ":", "print", "'Error, klampt model'", ",", "klampt_robot_model_fn", ",", "'did not contain a robot'", "exit", "(", "1", ")", "klampt_robot_model", "=", "world", ".", "robot", "(", "0", ")", "print", "\"Load successful\"", "#print some info", "robotName", "=", "klampt_robot_model", ".", "getName", "(", ")", "linkNames", "=", "[", "klampt_robot_model", ".", "link", "(", "i", ")", ".", "getName", "(", ")", "for", "i", "in", "range", "(", "klampt_robot_model", ".", "numLinks", "(", ")", ")", "]", "print", "\"Running controller listening on topic /%s/limb/right/joint_command and\"", "%", "(", "robotName", ",", ")", "print", "\"and /%s/limb/left/joint_command andd publishing on topic\"", "%", "(", "robotName", ",", ")", "print", "\"/%s/joint_states\"", "%", "(", "robotName", ",", ")", "print", "\"Klamp't link names are:\"", ",", "linkNames", "#advertise version 1.0.0 of the Baxter software", "print", "\"Emulating ROS Baxter API version 1.0.0\"", "rospy", ".", "set_param", "(", "'/rethink/software_version'", ",", "'1.0.0'", ")", "#create the ROS controller", "c", "=", "rosbaxtercontroller", ".", "make", "(", "klampt_robot_model", ")", "#launch the serial client to connect to a given host and relay messages from the socket to/from ROS", "host", "=", "'localhost'", "port", "=", "klampt_serial_port", "s", "=", "ControllerClient", "(", "(", "host", ",", "port", ")", ",", "c", ")", "print", "\"Running Baxter controller -> Klamp't robot relay...\"", "try", ":", "asyncore", ".", "loop", "(", ")", "except", "KeyboardInterrupt", ":", "print", "\"Ctrl+C pressed, exiting...\"" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/control-examples/baxterserialrelay.py#L33-L74
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/tools/grc_yaml_generator.py
python
dict_constructor
(loader, node)
return OrderedDict(loader.construct_pairs(node))
Construct an OrderedDict for dumping
Construct an OrderedDict for dumping
[ "Construct", "an", "OrderedDict", "for", "dumping" ]
def dict_constructor(loader, node): """ Construct an OrderedDict for dumping """ return OrderedDict(loader.construct_pairs(node))
[ "def", "dict_constructor", "(", "loader", ",", "node", ")", ":", "return", "OrderedDict", "(", "loader", ".", "construct_pairs", "(", "node", ")", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/tools/grc_yaml_generator.py#L32-L34
Ewenwan/MVision
97b394dfa48cb21c82cd003b1a952745e413a17f
vSLAM/矩阵变换python函数.py
python
superimposition_matrix
(v0, v1, scaling=False, usesvd=True)
return M
Return matrix to transform given vector set into second vector set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors. If usesvd is True, the weighted sum of squared deviations (RMSD) is minimized according to the algorithm by W. Kabsch [8]. Otherwise the quaternion based algorithm by B. Horn [9] is used (slower when using this Python implementation). The returned matrix performs rotation, translation and uniform scaling (if specified). >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = ((1,0,0), (0,1,0), (0,0,1), (1,1,1)) >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20.0 >>> v0[3] = 1.0 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0.0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scaling=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3), dtype=numpy.float64) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True
Return matrix to transform given vector set into second vector set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors. If usesvd is True, the weighted sum of squared deviations (RMSD) is minimized according to the algorithm by W. Kabsch [8]. Otherwise the quaternion based algorithm by B. Horn [9] is used (slower when using this Python implementation). The returned matrix performs rotation, translation and uniform scaling (if specified). >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = ((1,0,0), (0,1,0), (0,0,1), (1,1,1)) >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20.0 >>> v0[3] = 1.0 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0.0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scaling=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3), dtype=numpy.float64) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True
[ "Return", "matrix", "to", "transform", "given", "vector", "set", "into", "second", "vector", "set", ".", "v0", "and", "v1", "are", "shape", "(", "3", "\\", "*", ")", "or", "(", "4", "\\", "*", ")", "arrays", "of", "at", "least", "3", "vectors", ".", "If", "usesvd", "is", "True", "the", "weighted", "sum", "of", "squared", "deviations", "(", "RMSD", ")", "is", "minimized", "according", "to", "the", "algorithm", "by", "W", ".", "Kabsch", "[", "8", "]", ".", "Otherwise", "the", "quaternion", "based", "algorithm", "by", "B", ".", "Horn", "[", "9", "]", "is", "used", "(", "slower", "when", "using", "this", "Python", "implementation", ")", ".", "The", "returned", "matrix", "performs", "rotation", "translation", "and", "uniform", "scaling", "(", "if", "specified", ")", ".", ">>>", "v0", "=", "numpy", ".", "random", ".", "rand", "(", "3", "10", ")", ">>>", "M", "=", "superimposition_matrix", "(", "v0", "v0", ")", ">>>", "numpy", ".", "allclose", "(", "M", "numpy", ".", "identity", "(", "4", "))", "True", ">>>", "R", "=", "random_rotation_matrix", "(", "numpy", ".", "random", ".", "random", "(", "3", "))", ">>>", "v0", "=", "((", "1", "0", "0", ")", "(", "0", "1", "0", ")", "(", "0", "0", "1", ")", "(", "1", "1", "1", "))", ">>>", "v1", "=", "numpy", ".", "dot", "(", "R", "v0", ")", ">>>", "M", "=", "superimposition_matrix", "(", "v0", "v1", ")", ">>>", "numpy", ".", "allclose", "(", "v1", "numpy", ".", "dot", "(", "M", "v0", "))", "True", ">>>", "v0", "=", "(", "numpy", ".", "random", ".", "rand", "(", "4", "100", ")", "-", "0", ".", "5", ")", "*", "20", ".", "0", ">>>", "v0", "[", "3", "]", "=", "1", ".", "0", ">>>", "v1", "=", "numpy", ".", "dot", "(", "R", "v0", ")", ">>>", "M", "=", "superimposition_matrix", "(", "v0", "v1", ")", ">>>", "numpy", ".", "allclose", "(", "v1", "numpy", ".", "dot", "(", "M", "v0", "))", "True", ">>>", "S", "=", "scale_matrix", "(", "random", ".", "random", "()", ")", ">>>", "T", "=", "translation_matrix", "(", "numpy", ".", "random", ".", "random", "(", "3", ")", "-", "0", ".", "5", ")", ">>>", "M", "=", "concatenate_matrices", "(", "T", "R", "S", ")", ">>>", "v1", "=", "numpy", ".", "dot", "(", "M", "v0", ")", ">>>", "v0", "[", ":", "3", "]", "+", "=", "numpy", ".", "random", ".", "normal", "(", "0", ".", "0", "1e", "-", "9", "300", ")", ".", "reshape", "(", "3", "-", "1", ")", ">>>", "M", "=", "superimposition_matrix", "(", "v0", "v1", "scaling", "=", "True", ")", ">>>", "numpy", ".", "allclose", "(", "v1", "numpy", ".", "dot", "(", "M", "v0", "))", "True", ">>>", "M", "=", "superimposition_matrix", "(", "v0", "v1", "scaling", "=", "True", "usesvd", "=", "False", ")", ">>>", "numpy", ".", "allclose", "(", "v1", "numpy", ".", "dot", "(", "M", "v0", "))", "True", ">>>", "v", "=", "numpy", ".", "empty", "((", "4", "100", "3", ")", "dtype", "=", "numpy", ".", "float64", ")", ">>>", "v", "[", ":", ":", "0", "]", "=", "v0", ">>>", "M", "=", "superimposition_matrix", "(", "v0", "v1", "scaling", "=", "True", "usesvd", "=", "False", ")", ">>>", "numpy", ".", "allclose", "(", "v1", "numpy", ".", "dot", "(", "M", "v", "[", ":", ":", "0", "]", "))", "True" ]
def superimposition_matrix(v0, v1, scaling=False, usesvd=True): """Return matrix to transform given vector set into second vector set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors. If usesvd is True, the weighted sum of squared deviations (RMSD) is minimized according to the algorithm by W. Kabsch [8]. Otherwise the quaternion based algorithm by B. Horn [9] is used (slower when using this Python implementation). The returned matrix performs rotation, translation and uniform scaling (if specified). >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = ((1,0,0), (0,1,0), (0,0,1), (1,1,1)) >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20.0 >>> v0[3] = 1.0 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0.0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scaling=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3), dtype=numpy.float64) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3] v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3] if v0.shape != v1.shape or v0.shape[1] < 3: raise ValueError("Vector sets are of wrong shape or type.") # move centroids to origin t0 = numpy.mean(v0, axis=1) t1 = numpy.mean(v1, axis=1) v0 = v0 - t0.reshape(3, 1) v1 = v1 - t1.reshape(3, 1) if usesvd: # Singular Value Decomposition of covariance matrix u, s, vh = numpy.linalg.svd(numpy.dot(v1, v0.T)) # rotation matrix from SVD orthonormal bases R = numpy.dot(u, vh) if numpy.linalg.det(R) < 0.0: # R does not constitute right handed system R -= numpy.outer(u[:, 2], vh[2, :]*2.0) s[-1] *= -1.0 # homogeneous transformation matrix M = numpy.identity(4) M[:3, :3] = R else: # compute symmetric matrix N xx, yy, zz = numpy.sum(v0 * v1, axis=1) xy, yz, zx = numpy.sum(v0 * numpy.roll(v1, -1, axis=0), axis=1) xz, yx, zy = numpy.sum(v0 * numpy.roll(v1, -2, axis=0), axis=1) N = ((xx+yy+zz, yz-zy, zx-xz, xy-yx), (yz-zy, xx-yy-zz, xy+yx, zx+xz), (zx-xz, xy+yx, -xx+yy-zz, yz+zy), (xy-yx, zx+xz, yz+zy, -xx-yy+zz)) # quaternion: eigenvector corresponding to most positive eigenvalue l, V = numpy.linalg.eig(N) q = V[:, numpy.argmax(l)] q /= vector_norm(q) # unit quaternion q = numpy.roll(q, -1) # move w component to end # homogeneous transformation matrix M = quaternion_matrix(q) # scale: ratio of rms deviations from centroid if scaling: v0 *= v0 v1 *= v1 M[:3, :3] *= math.sqrt(numpy.sum(v1) / numpy.sum(v0)) # translation M[:3, 3] = t1 T = numpy.identity(4) T[:3, 3] = -t0 M = numpy.dot(M, T) return M
[ "def", "superimposition_matrix", "(", "v0", ",", "v1", ",", "scaling", "=", "False", ",", "usesvd", "=", "True", ")", ":", "v0", "=", "numpy", ".", "array", "(", "v0", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "[", ":", "3", "]", "v1", "=", "numpy", ".", "array", "(", "v1", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "[", ":", "3", "]", "if", "v0", ".", "shape", "!=", "v1", ".", "shape", "or", "v0", ".", "shape", "[", "1", "]", "<", "3", ":", "raise", "ValueError", "(", "\"Vector sets are of wrong shape or type.\"", ")", "# move centroids to origin", "t0", "=", "numpy", ".", "mean", "(", "v0", ",", "axis", "=", "1", ")", "t1", "=", "numpy", ".", "mean", "(", "v1", ",", "axis", "=", "1", ")", "v0", "=", "v0", "-", "t0", ".", "reshape", "(", "3", ",", "1", ")", "v1", "=", "v1", "-", "t1", ".", "reshape", "(", "3", ",", "1", ")", "if", "usesvd", ":", "# Singular Value Decomposition of covariance matrix", "u", ",", "s", ",", "vh", "=", "numpy", ".", "linalg", ".", "svd", "(", "numpy", ".", "dot", "(", "v1", ",", "v0", ".", "T", ")", ")", "# rotation matrix from SVD orthonormal bases", "R", "=", "numpy", ".", "dot", "(", "u", ",", "vh", ")", "if", "numpy", ".", "linalg", ".", "det", "(", "R", ")", "<", "0.0", ":", "# R does not constitute right handed system", "R", "-=", "numpy", ".", "outer", "(", "u", "[", ":", ",", "2", "]", ",", "vh", "[", "2", ",", ":", "]", "*", "2.0", ")", "s", "[", "-", "1", "]", "*=", "-", "1.0", "# homogeneous transformation matrix", "M", "=", "numpy", ".", "identity", "(", "4", ")", "M", "[", ":", "3", ",", ":", "3", "]", "=", "R", "else", ":", "# compute symmetric matrix N", "xx", ",", "yy", ",", "zz", "=", "numpy", ".", "sum", "(", "v0", "*", "v1", ",", "axis", "=", "1", ")", "xy", ",", "yz", ",", "zx", "=", "numpy", ".", "sum", "(", "v0", "*", "numpy", ".", "roll", "(", "v1", ",", "-", "1", ",", "axis", "=", "0", ")", ",", "axis", "=", "1", ")", "xz", ",", "yx", ",", "zy", "=", "numpy", ".", "sum", "(", "v0", "*", "numpy", ".", "roll", "(", "v1", ",", "-", "2", ",", "axis", "=", "0", ")", ",", "axis", "=", "1", ")", "N", "=", "(", "(", "xx", "+", "yy", "+", "zz", ",", "yz", "-", "zy", ",", "zx", "-", "xz", ",", "xy", "-", "yx", ")", ",", "(", "yz", "-", "zy", ",", "xx", "-", "yy", "-", "zz", ",", "xy", "+", "yx", ",", "zx", "+", "xz", ")", ",", "(", "zx", "-", "xz", ",", "xy", "+", "yx", ",", "-", "xx", "+", "yy", "-", "zz", ",", "yz", "+", "zy", ")", ",", "(", "xy", "-", "yx", ",", "zx", "+", "xz", ",", "yz", "+", "zy", ",", "-", "xx", "-", "yy", "+", "zz", ")", ")", "# quaternion: eigenvector corresponding to most positive eigenvalue", "l", ",", "V", "=", "numpy", ".", "linalg", ".", "eig", "(", "N", ")", "q", "=", "V", "[", ":", ",", "numpy", ".", "argmax", "(", "l", ")", "]", "q", "/=", "vector_norm", "(", "q", ")", "# unit quaternion", "q", "=", "numpy", ".", "roll", "(", "q", ",", "-", "1", ")", "# move w component to end", "# homogeneous transformation matrix", "M", "=", "quaternion_matrix", "(", "q", ")", "# scale: ratio of rms deviations from centroid", "if", "scaling", ":", "v0", "*=", "v0", "v1", "*=", "v1", "M", "[", ":", "3", ",", ":", "3", "]", "*=", "math", ".", "sqrt", "(", "numpy", ".", "sum", "(", "v1", ")", "/", "numpy", ".", "sum", "(", "v0", ")", ")", "# translation", "M", "[", ":", "3", ",", "3", "]", "=", "t1", "T", "=", "numpy", ".", "identity", "(", "4", ")", "T", "[", ":", "3", ",", "3", "]", "=", "-", "t0", "M", "=", "numpy", ".", "dot", "(", "M", ",", "T", ")", "return", "M" ]
https://github.com/Ewenwan/MVision/blob/97b394dfa48cb21c82cd003b1a952745e413a17f/vSLAM/矩阵变换python函数.py#L794-L888
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/images/layer_rasters.py
python
LayerRasters.addToBaseQuery
(self, query)
add queries that together define the layer
add queries that together define the layer
[ "add", "queries", "that", "together", "define", "the", "layer" ]
def addToBaseQuery(self, query): """ add queries that together define the layer """ self.dict.update(query)
[ "def", "addToBaseQuery", "(", "self", ",", "query", ")", ":", "self", ".", "dict", ".", "update", "(", "query", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/images/layer_rasters.py#L19-L21
cluebotng/cluebotng
2ed38a518c1019f6b7b03e33b487f96f8df617b0
fabfile.py
python
_update_utils
()
Clone or pull the utils git repo into the apps path
Clone or pull the utils git repo into the apps path
[ "Clone", "or", "pull", "the", "utils", "git", "repo", "into", "the", "apps", "path" ]
def _update_utils(): ''' Clone or pull the utils git repo into the apps path ''' print('Resetting local changes') sudo('cd "%(dir)s" && git reset --hard && git clean -fd' % {'dir': os.path.join(TOOL_DIR, 'apps', 'utils')}) print('Updating code') sudo('cd "%(dir)s" && git pull origin master' % {'dir': os.path.join(TOOL_DIR, 'apps', 'utils')})
[ "def", "_update_utils", "(", ")", ":", "print", "(", "'Resetting local changes'", ")", "sudo", "(", "'cd \"%(dir)s\" && git reset --hard && git clean -fd'", "%", "{", "'dir'", ":", "os", ".", "path", ".", "join", "(", "TOOL_DIR", ",", "'apps'", ",", "'utils'", ")", "}", ")", "print", "(", "'Updating code'", ")", "sudo", "(", "'cd \"%(dir)s\" && git pull origin master'", "%", "{", "'dir'", ":", "os", ".", "path", ".", "join", "(", "TOOL_DIR", ",", "'apps'", ",", "'utils'", ")", "}", ")" ]
https://github.com/cluebotng/cluebotng/blob/2ed38a518c1019f6b7b03e33b487f96f8df617b0/fabfile.py#L126-L135
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
CheckForNonConstReference
(filename, clean_lines, linenum, nesting_state, error)
Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. 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: The function to call with any errors found.
Check for non-const references.
[ "Check", "for", "non", "-", "const", "references", "." ]
def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. 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: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # If a function is inherited, current function doesn't have much of # a choice, so any non-const references should not be blamed on # derived function. if IsDerivedFunction(clean_lines, linenum): return # Don't warn on out-of-line method definitions, as we would warn on the # in-line declaration, if it isn't marked with 'override'. if IsOutOfLineMethodDefinition(clean_lines, linenum): return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. if (nesting_state.previous_stack_top and not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): # Not at toplevel, not within a class, and not within a namespace return # Avoid initializer lists. We only need to scan back from the # current line for something that starts with ':'. # # We don't need to check the current line, since the '&' would # appear inside the second set of parentheses on the current line as # opposed to the first set. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 10), -1): previous_line = clean_lines.elided[i] if not Search(r'[),]\s*$', previous_line): break if Match(r'^\s*:\s+\S', previous_line): return # Avoid preprocessors if Search(r'\\\s*$', line): return # Avoid constructor initializer lists if IsInitializerList(clean_lines, linenum): return # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. allowed_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(allowed_functions, line): return elif not Search(r'\S+\([^)]*$', line): # Don't see an allowed function entry on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(allowed_functions, clean_lines.elided[linenum - i - 1])): return decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter))
[ "def", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "nesting_state", ",", "error", ")", ":", "# Do nothing if there is no '&' on current line.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "'&'", "not", "in", "line", ":", "return", "# If a function is inherited, current function doesn't have much of", "# a choice, so any non-const references should not be blamed on", "# derived function.", "if", "IsDerivedFunction", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# Don't warn on out-of-line method definitions, as we would warn on the", "# in-line declaration, if it isn't marked with 'override'.", "if", "IsOutOfLineMethodDefinition", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# Long type names may be broken across multiple lines, usually in one", "# of these forms:", "# LongType", "# ::LongTypeContinued &identifier", "# LongType::", "# LongTypeContinued &identifier", "# LongType<", "# ...>::LongTypeContinued &identifier", "#", "# If we detected a type split across two lines, join the previous", "# line to current line so that we can match const references", "# accordingly.", "#", "# Note that this only scans back one line, since scanning back", "# arbitrary number of lines would be expensive. If you have a type", "# that spans more than 2 lines, please use a typedef.", "if", "linenum", ">", "1", ":", "previous", "=", "None", "if", "Match", "(", "r'\\s*::(?:[\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line\\n + ::current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+[\\w<>])\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "elif", "Match", "(", "r'\\s*[a-zA-Z_]([\\w<>]|::)+\\s*&\\s*\\S'", ",", "line", ")", ":", "# previous_line::\\n + current_line", "previous", "=", "Search", "(", "r'\\b((?:const\\s*)?(?:[\\w<>]|::)+::)\\s*$'", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "1", "]", ")", "if", "previous", ":", "line", "=", "previous", ".", "group", "(", "1", ")", "+", "line", ".", "lstrip", "(", ")", "else", ":", "# Check for templated parameter that is split across multiple lines", "endpos", "=", "line", ".", "rfind", "(", "'>'", ")", "if", "endpos", ">", "-", "1", ":", "(", "_", ",", "startline", ",", "startpos", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "endpos", ")", "if", "startpos", ">", "-", "1", "and", "startline", "<", "linenum", ":", "# Found the matching < on an earlier line, collect all", "# pieces up to current line.", "line", "=", "''", "for", "i", "in", "xrange", "(", "startline", ",", "linenum", "+", "1", ")", ":", "line", "+=", "clean_lines", ".", "elided", "[", "i", "]", ".", "strip", "(", ")", "# Check for non-const references in function parameters. A single '&' may", "# found in the following places:", "# inside expression: binary & for bitwise AND", "# inside expression: unary & for taking the address of something", "# inside declarators: reference parameter", "# We will exclude the first two cases by checking that we are not inside a", "# function body, including one that was just introduced by a trailing '{'.", "# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].", "if", "(", "nesting_state", ".", "previous_stack_top", "and", "not", "(", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_ClassInfo", ")", "or", "isinstance", "(", "nesting_state", ".", "previous_stack_top", ",", "_NamespaceInfo", ")", ")", ")", ":", "# Not at toplevel, not within a class, and not within a namespace", "return", "# Avoid initializer lists. We only need to scan back from the", "# current line for something that starts with ':'.", "#", "# We don't need to check the current line, since the '&' would", "# appear inside the second set of parentheses on the current line as", "# opposed to the first set.", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "10", ")", ",", "-", "1", ")", ":", "previous_line", "=", "clean_lines", ".", "elided", "[", "i", "]", "if", "not", "Search", "(", "r'[),]\\s*$'", ",", "previous_line", ")", ":", "break", "if", "Match", "(", "r'^\\s*:\\s+\\S'", ",", "previous_line", ")", ":", "return", "# Avoid preprocessors", "if", "Search", "(", "r'\\\\\\s*$'", ",", "line", ")", ":", "return", "# Avoid constructor initializer lists", "if", "IsInitializerList", "(", "clean_lines", ",", "linenum", ")", ":", "return", "# We allow non-const references in a few standard places, like functions", "# called \"swap()\" or iostream operators like \"<<\" or \">>\". Do not check", "# those function parameters.", "#", "# We also accept & in static_assert, which looks like a function but", "# it's actually a declaration expression.", "allowed_functions", "=", "(", "r'(?:[sS]wap(?:<\\w:+>)?|'", "r'operator\\s*[<>][<>]|'", "r'static_assert|COMPILE_ASSERT'", "r')\\s*\\('", ")", "if", "Search", "(", "allowed_functions", ",", "line", ")", ":", "return", "elif", "not", "Search", "(", "r'\\S+\\([^)]*$'", ",", "line", ")", ":", "# Don't see an allowed function entry on this line. Actually we", "# didn't see any function name on this line, so this is likely a", "# multi-line parameter list. Try a bit harder to catch this case.", "for", "i", "in", "xrange", "(", "2", ")", ":", "if", "(", "linenum", ">", "i", "and", "Search", "(", "allowed_functions", ",", "clean_lines", ".", "elided", "[", "linenum", "-", "i", "-", "1", "]", ")", ")", ":", "return", "decls", "=", "ReplaceAll", "(", "r'{[^}]*}'", ",", "' '", ",", "line", ")", "# exclude function body", "for", "parameter", "in", "re", ".", "findall", "(", "_RE_PATTERN_REF_PARAM", ",", "decls", ")", ":", "if", "(", "not", "Match", "(", "_RE_PATTERN_CONST_REF_PARAM", ",", "parameter", ")", "and", "not", "Match", "(", "_RE_PATTERN_REF_STREAM_PARAM", ",", "parameter", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'runtime/references'", ",", "2", ",", "'Is this a non-const reference? '", "'If so, make const or use a pointer: '", "+", "ReplaceAll", "(", "' *<'", ",", "'<'", ",", "parameter", ")", ")" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L5013-L5149
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.__reversed__
(self)
od.__reversed__() <==> reversed(od)
od.__reversed__() <==> reversed(od)
[ "od", ".", "__reversed__", "()", "<", "==", ">", "reversed", "(", "od", ")" ]
def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0]
[ "def", "__reversed__", "(", "self", ")", ":", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "0", "]", "while", "curr", "is", "not", "root", ":", "yield", "curr", "[", "2", "]", "curr", "=", "curr", "[", "0", "]" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/ordered_dict.py#L98-L104
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/physics/ert/ves.py
python
VESModelling.drawData
(self, ax, data, error=None, label=None, **kwargs)
r"""Draw modeled apparent resistivity data. Parameters ---------- ax: axes Matplotlib axes object to draw into. data: iterable Apparent resistivity values to draw. error: iterable [None] Adds an error bar if you have error values. label: str ['$\varrho_a$'] Set legend label for the amplitude. Other parameters ---------------- ab2: iterable Override ab2 that fits data size. mn2: iterable Override mn2 that fits data size. plot: function name Matplotlib plot function, e.g., plot, loglog, semilogx or semilogy
r"""Draw modeled apparent resistivity data.
[ "r", "Draw", "modeled", "apparent", "resistivity", "data", "." ]
def drawData(self, ax, data, error=None, label=None, **kwargs): r"""Draw modeled apparent resistivity data. Parameters ---------- ax: axes Matplotlib axes object to draw into. data: iterable Apparent resistivity values to draw. error: iterable [None] Adds an error bar if you have error values. label: str ['$\varrho_a$'] Set legend label for the amplitude. Other parameters ---------------- ab2: iterable Override ab2 that fits data size. mn2: iterable Override mn2 that fits data size. plot: function name Matplotlib plot function, e.g., plot, loglog, semilogx or semilogy """ ab2 = kwargs.pop('ab2', self.ab2) # mn2 = kwargs.pop('mn2', self.mn2) plot = kwargs.pop('plot', 'loglog') ra = data raE = error style = dict(pg.frameworks.modelling.DEFAULT_STYLES.get( label, pg.frameworks.modelling.DEFAULT_STYLES['Default'])) style.update(kwargs) a1 = ax plot = getattr(a1, plot) if label is None: label = r'$\varrho_a$' del style["linestyle"] # to remove mpl warning plot(ra, ab2, 'x-', label=label, **style) if raE is not None: raErr = np.array(ra * raE) if pg.isArray(raErr, len(ra)): a1.errorbar(ra, ab2, xerr=raErr, barsabove=True, **pg.frameworks.modelling.DEFAULT_STYLES.get('Error', pg.frameworks.modelling.DEFAULT_STYLES['Default']), label='_nolegend_') a1.set_ylim(max(ab2), min(ab2)) a1.set_xlabel(r'Apparent resistivity ($\Omega$m)') a1.set_ylabel(r'AB/2 (m)') a1.grid(True) a1.legend()
[ "def", "drawData", "(", "self", ",", "ax", ",", "data", ",", "error", "=", "None", ",", "label", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ab2", "=", "kwargs", ".", "pop", "(", "'ab2'", ",", "self", ".", "ab2", ")", "# mn2 = kwargs.pop('mn2', self.mn2)", "plot", "=", "kwargs", ".", "pop", "(", "'plot'", ",", "'loglog'", ")", "ra", "=", "data", "raE", "=", "error", "style", "=", "dict", "(", "pg", ".", "frameworks", ".", "modelling", ".", "DEFAULT_STYLES", ".", "get", "(", "label", ",", "pg", ".", "frameworks", ".", "modelling", ".", "DEFAULT_STYLES", "[", "'Default'", "]", ")", ")", "style", ".", "update", "(", "kwargs", ")", "a1", "=", "ax", "plot", "=", "getattr", "(", "a1", ",", "plot", ")", "if", "label", "is", "None", ":", "label", "=", "r'$\\varrho_a$'", "del", "style", "[", "\"linestyle\"", "]", "# to remove mpl warning", "plot", "(", "ra", ",", "ab2", ",", "'x-'", ",", "label", "=", "label", ",", "*", "*", "style", ")", "if", "raE", "is", "not", "None", ":", "raErr", "=", "np", ".", "array", "(", "ra", "*", "raE", ")", "if", "pg", ".", "isArray", "(", "raErr", ",", "len", "(", "ra", ")", ")", ":", "a1", ".", "errorbar", "(", "ra", ",", "ab2", ",", "xerr", "=", "raErr", ",", "barsabove", "=", "True", ",", "*", "*", "pg", ".", "frameworks", ".", "modelling", ".", "DEFAULT_STYLES", ".", "get", "(", "'Error'", ",", "pg", ".", "frameworks", ".", "modelling", ".", "DEFAULT_STYLES", "[", "'Default'", "]", ")", ",", "label", "=", "'_nolegend_'", ")", "a1", ".", "set_ylim", "(", "max", "(", "ab2", ")", ",", "min", "(", "ab2", ")", ")", "a1", ".", "set_xlabel", "(", "r'Apparent resistivity ($\\Omega$m)'", ")", "a1", ".", "set_ylabel", "(", "r'AB/2 (m)'", ")", "a1", ".", "grid", "(", "True", ")", "a1", ".", "legend", "(", ")" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/physics/ert/ves.py#L142-L200
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xmlDoc.isRef
(self, elem, attr)
return ret
Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase).
Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase).
[ "Determine", "whether", "an", "attribute", "is", "of", "type", "Ref", ".", "In", "case", "we", "have", "DTD", "(", "s", ")", "then", "this", "is", "simple", "otherwise", "we", "use", "an", "heuristic", ":", "name", "Ref", "(", "upper", "or", "lowercase", ")", "." ]
def isRef(self, elem, attr): """Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase). """ if elem is None: elem__o = None else: elem__o = elem._o if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlIsRef(self._o, elem__o, attr__o) return ret
[ "def", "isRef", "(", "self", ",", "elem", ",", "attr", ")", ":", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "else", ":", "elem__o", "=", "elem", ".", "_o", "if", "attr", "is", "None", ":", "attr__o", "=", "None", "else", ":", "attr__o", "=", "attr", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlIsRef", "(", "self", ".", "_o", ",", "elem__o", ",", "attr__o", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4622-L4631
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/cpy/antlr3/treewizard.py
python
TreeWizard._index
(self, t, m)
Do the work for index
Do the work for index
[ "Do", "the", "work", "for", "index" ]
def _index(self, t, m): """Do the work for index""" if t is None: return ttype = self.adaptor.getType(t) elements = m.get(ttype) if elements is None: m[ttype] = elements = [] elements.append(t) for i in range(self.adaptor.getChildCount(t)): child = self.adaptor.getChild(t, i) self._index(child, m)
[ "def", "_index", "(", "self", ",", "t", ",", "m", ")", ":", "if", "t", "is", "None", ":", "return", "ttype", "=", "self", ".", "adaptor", ".", "getType", "(", "t", ")", "elements", "=", "m", ".", "get", "(", "ttype", ")", "if", "elements", "is", "None", ":", "m", "[", "ttype", "]", "=", "elements", "=", "[", "]", "elements", ".", "append", "(", "t", ")", "for", "i", "in", "range", "(", "self", ".", "adaptor", ".", "getChildCount", "(", "t", ")", ")", ":", "child", "=", "self", ".", "adaptor", ".", "getChild", "(", "t", ",", "i", ")", "self", ".", "_index", "(", "child", ",", "m", ")" ]
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/treewizard.py#L377-L391
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/util.py
python
convert_path
(pathname)
return os.path.join(*paths)
Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash.
Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash.
[ "Return", "pathname", "as", "a", "name", "that", "will", "work", "on", "the", "native", "filesystem", "i", ".", "e", ".", "split", "it", "on", "/", "and", "put", "it", "back", "together", "again", "using", "the", "current", "directory", "separator", ".", "Needed", "because", "filenames", "in", "the", "setup", "script", "are", "always", "supplied", "in", "Unix", "style", "and", "have", "to", "be", "converted", "to", "the", "local", "convention", "before", "we", "can", "actually", "use", "them", "in", "the", "filesystem", ".", "Raises", "ValueError", "on", "non", "-", "Unix", "-", "ish", "systems", "if", "pathname", "either", "starts", "or", "ends", "with", "a", "slash", "." ]
def convert_path (pathname): """Return 'pathname' as a name that will work on the native filesystem, i.e. split it on '/' and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if 'pathname' either starts or ends with a slash. """ if os.sep == '/': return pathname if not pathname: return pathname if pathname[0] == '/': raise ValueError("path '%s' cannot be absolute" % pathname) if pathname[-1] == '/': raise ValueError("path '%s' cannot end with '/'" % pathname) paths = pathname.split('/') while '.' in paths: paths.remove('.') if not paths: return os.curdir return os.path.join(*paths)
[ "def", "convert_path", "(", "pathname", ")", ":", "if", "os", ".", "sep", "==", "'/'", ":", "return", "pathname", "if", "not", "pathname", ":", "return", "pathname", "if", "pathname", "[", "0", "]", "==", "'/'", ":", "raise", "ValueError", "(", "\"path '%s' cannot be absolute\"", "%", "pathname", ")", "if", "pathname", "[", "-", "1", "]", "==", "'/'", ":", "raise", "ValueError", "(", "\"path '%s' cannot end with '/'\"", "%", "pathname", ")", "paths", "=", "pathname", ".", "split", "(", "'/'", ")", "while", "'.'", "in", "paths", ":", "paths", ".", "remove", "(", "'.'", ")", "if", "not", "paths", ":", "return", "os", ".", "curdir", "return", "os", ".", "path", ".", "join", "(", "*", "paths", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/util.py#L109-L132
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/mavlink_px4.py
python
MAVLink.param_value_encode
(self, param_id, param_value, param_type, param_count, param_index)
return msg
Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_value : Onboard parameter value (float) param_type : Onboard parameter type: see the MAV_PARAM_TYPE enum for supported data types. (uint8_t) param_count : Total number of onboard parameters (uint16_t) param_index : Index of this onboard parameter (uint16_t)
Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout.
[ "Emit", "the", "value", "of", "a", "onboard", "parameter", ".", "The", "inclusion", "of", "param_count", "and", "param_index", "in", "the", "message", "allows", "the", "recipient", "to", "keep", "track", "of", "received", "parameters", "and", "allows", "him", "to", "re", "-", "request", "missing", "parameters", "after", "a", "loss", "or", "timeout", "." ]
def param_value_encode(self, param_id, param_value, param_type, param_count, param_index): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char) param_value : Onboard parameter value (float) param_type : Onboard parameter type: see the MAV_PARAM_TYPE enum for supported data types. (uint8_t) param_count : Total number of onboard parameters (uint16_t) param_index : Index of this onboard parameter (uint16_t) ''' msg = MAVLink_param_value_message(param_id, param_value, param_type, param_count, param_index) msg.pack(self) return msg
[ "def", "param_value_encode", "(", "self", ",", "param_id", ",", "param_value", ",", "param_type", ",", "param_count", ",", "param_index", ")", ":", "msg", "=", "MAVLink_param_value_message", "(", "param_id", ",", "param_value", ",", "param_type", ",", "param_count", ",", "param_index", ")", "msg", ".", "pack", "(", "self", ")", "return", "msg" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L2731-L2747
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/methodDefs_xmcAlgorithm/checkInitialisation.py
python
checkInitialisationMLMC
(XMCAlgorithm)
Method checking all attributes of different classes are correctly set to run Multilevel Monte Carlo algorithm (both standard and asynchronous).
Method checking all attributes of different classes are correctly set to run Multilevel Monte Carlo algorithm (both standard and asynchronous).
[ "Method", "checking", "all", "attributes", "of", "different", "classes", "are", "correctly", "set", "to", "run", "Multilevel", "Monte", "Carlo", "algorithm", "(", "both", "standard", "and", "asynchronous", ")", "." ]
def checkInitialisationMLMC(XMCAlgorithm): """ Method checking all attributes of different classes are correctly set to run Multilevel Monte Carlo algorithm (both standard and asynchronous). """ solverWrapperDictionary = XMCAlgorithm.monteCarloSampler.indexConstructorDictionary[ "samplerInputDictionary"]["solverWrapperInputDictionary"] positionMaxNumberIterationsCriterion=XMCAlgorithm.positionMaxNumberIterationsCriterion tolerances=XMCAlgorithm.stoppingCriterion.tolerances() # perform checks checkInitialisationSolverWrapper(solverWrapperDictionary) if ("asynchronous" in solverWrapperDictionary): if (solverWrapperDictionary["asynchronous"] is True): checkMaxNumberIterationsCriterion(positionMaxNumberIterationsCriterion,tolerances)
[ "def", "checkInitialisationMLMC", "(", "XMCAlgorithm", ")", ":", "solverWrapperDictionary", "=", "XMCAlgorithm", ".", "monteCarloSampler", ".", "indexConstructorDictionary", "[", "\"samplerInputDictionary\"", "]", "[", "\"solverWrapperInputDictionary\"", "]", "positionMaxNumberIterationsCriterion", "=", "XMCAlgorithm", ".", "positionMaxNumberIterationsCriterion", "tolerances", "=", "XMCAlgorithm", ".", "stoppingCriterion", ".", "tolerances", "(", ")", "# perform checks", "checkInitialisationSolverWrapper", "(", "solverWrapperDictionary", ")", "if", "(", "\"asynchronous\"", "in", "solverWrapperDictionary", ")", ":", "if", "(", "solverWrapperDictionary", "[", "\"asynchronous\"", "]", "is", "True", ")", ":", "checkMaxNumberIterationsCriterion", "(", "positionMaxNumberIterationsCriterion", ",", "tolerances", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/methodDefs_xmcAlgorithm/checkInitialisation.py#L24-L37
lukasmonk/lucaschess
13e2e5cb13b38a720ccf897af649054a64bcb914
Code/QT/Grid.py
python
Grid.__init__
(self, wParent, oColumnas, dicVideo=None, altoFila=20, siSelecFilas=False, siSeleccionMultiple=False, siLineas=True, siEditable=False, siCabeceraMovible=True, xid=None, background="", siCabeceraVisible=True, altoCabecera=None)
@param wParent: ventana propietaria @param oColumnas: configuracion de las columnas. @param altoFila: altura de todas las filas.
[]
def __init__(self, wParent, oColumnas, dicVideo=None, altoFila=20, siSelecFilas=False, siSeleccionMultiple=False, siLineas=True, siEditable=False, siCabeceraMovible=True, xid=None, background="", siCabeceraVisible=True, altoCabecera=None): """ @param wParent: ventana propietaria @param oColumnas: configuracion de las columnas. @param altoFila: altura de todas las filas. """ assert wParent is not None QtGui.QTableView.__init__(self) if VarGen.configuracion.tablaSelBackground: p = self.palette() p.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight, QtGui.QBrush(QtGui.QColor(VarGen.configuracion.tablaSelBackground))) p.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Highlight, QtGui.QBrush(QtGui.QColor(VarGen.configuracion.tablaSelBackground))) self.setPalette(p) self.wParent = wParent self.id = xid self.oColumnas = oColumnas if dicVideo: self.recuperarVideo(dicVideo) self.oColumnasR = self.oColumnas.columnasMostrables() # Necesario tras recuperar video self.cg = ControlGrid(self, wParent, self.oColumnasR) self.setModel(self.cg) self.setShowGrid(siLineas) if background == "": self.setStyleSheet("QTableView {background: %s;}" % QTUtil.backgroundGUI()) elif background is not None: self.setStyleSheet("QTableView {background: %s;}" % background) self.coloresAlternados() if altoCabecera: hh = CabeceraHeight(self, siCabeceraMovible, altoCabecera) else: hh = Cabecera(self, siCabeceraMovible) self.setHorizontalHeader(hh) if not siCabeceraVisible: hh.setVisible(False) vh = self.verticalHeader() vh.setResizeMode(QtGui.QHeaderView.Fixed) vh.setDefaultSectionSize(altoFila) vh.setVisible(False) self.seleccionaFilas(siSelecFilas, siSeleccionMultiple) self.ponAnchosColumnas() # es necesario llamarlo desde aqui self.siEditable = siEditable
[ "def", "__init__", "(", "self", ",", "wParent", ",", "oColumnas", ",", "dicVideo", "=", "None", ",", "altoFila", "=", "20", ",", "siSelecFilas", "=", "False", ",", "siSeleccionMultiple", "=", "False", ",", "siLineas", "=", "True", ",", "siEditable", "=", "False", ",", "siCabeceraMovible", "=", "True", ",", "xid", "=", "None", ",", "background", "=", "\"\"", ",", "siCabeceraVisible", "=", "True", ",", "altoCabecera", "=", "None", ")", ":", "assert", "wParent", "is", "not", "None", "QtGui", ".", "QTableView", ".", "__init__", "(", "self", ")", "if", "VarGen", ".", "configuracion", ".", "tablaSelBackground", ":", "p", "=", "self", ".", "palette", "(", ")", "p", ".", "setBrush", "(", "QtGui", ".", "QPalette", ".", "Inactive", ",", "QtGui", ".", "QPalette", ".", "Highlight", ",", "QtGui", ".", "QBrush", "(", "QtGui", ".", "QColor", "(", "VarGen", ".", "configuracion", ".", "tablaSelBackground", ")", ")", ")", "p", ".", "setBrush", "(", "QtGui", ".", "QPalette", ".", "Active", ",", "QtGui", ".", "QPalette", ".", "Highlight", ",", "QtGui", ".", "QBrush", "(", "QtGui", ".", "QColor", "(", "VarGen", ".", "configuracion", ".", "tablaSelBackground", ")", ")", ")", "self", ".", "setPalette", "(", "p", ")", "self", ".", "wParent", "=", "wParent", "self", ".", "id", "=", "xid", "self", ".", "oColumnas", "=", "oColumnas", "if", "dicVideo", ":", "self", ".", "recuperarVideo", "(", "dicVideo", ")", "self", ".", "oColumnasR", "=", "self", ".", "oColumnas", ".", "columnasMostrables", "(", ")", "# Necesario tras recuperar video", "self", ".", "cg", "=", "ControlGrid", "(", "self", ",", "wParent", ",", "self", ".", "oColumnasR", ")", "self", ".", "setModel", "(", "self", ".", "cg", ")", "self", ".", "setShowGrid", "(", "siLineas", ")", "if", "background", "==", "\"\"", ":", "self", ".", "setStyleSheet", "(", "\"QTableView {background: %s;}\"", "%", "QTUtil", ".", "backgroundGUI", "(", ")", ")", "elif", "background", "is", "not", "None", ":", "self", ".", "setStyleSheet", "(", "\"QTableView {background: %s;}\"", "%", "background", ")", "self", ".", "coloresAlternados", "(", ")", "if", "altoCabecera", ":", "hh", "=", "CabeceraHeight", "(", "self", ",", "siCabeceraMovible", ",", "altoCabecera", ")", "else", ":", "hh", "=", "Cabecera", "(", "self", ",", "siCabeceraMovible", ")", "self", ".", "setHorizontalHeader", "(", "hh", ")", "if", "not", "siCabeceraVisible", ":", "hh", ".", "setVisible", "(", "False", ")", "vh", "=", "self", ".", "verticalHeader", "(", ")", "vh", ".", "setResizeMode", "(", "QtGui", ".", "QHeaderView", ".", "Fixed", ")", "vh", ".", "setDefaultSectionSize", "(", "altoFila", ")", "vh", ".", "setVisible", "(", "False", ")", "self", ".", "seleccionaFilas", "(", "siSelecFilas", ",", "siSeleccionMultiple", ")", "self", ".", "ponAnchosColumnas", "(", ")", "# es necesario llamarlo desde aqui", "self", ".", "siEditable", "=", "siEditable" ]
https://github.com/lukasmonk/lucaschess/blob/13e2e5cb13b38a720ccf897af649054a64bcb914/Code/QT/Grid.py#L217-L273
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
StatusBar.GetFields
(self)
return [self.GetStatusText(i) for i in range(self.GetFieldsCount())]
Return a list of field values in the status bar.
Return a list of field values in the status bar.
[ "Return", "a", "list", "of", "field", "values", "in", "the", "status", "bar", "." ]
def GetFields(self): """Return a list of field values in the status bar. """ return [self.GetStatusText(i) for i in range(self.GetFieldsCount())]
[ "def", "GetFields", "(", "self", ")", ":", "return", "[", "self", ".", "GetStatusText", "(", "i", ")", "for", "i", "in", "range", "(", "self", ".", "GetFieldsCount", "(", ")", ")", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L1321-L1323
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItemData.GetY
(self)
return self._rect.y
Returns the item `y` position.
Returns the item `y` position.
[ "Returns", "the", "item", "y", "position", "." ]
def GetY(self): """ Returns the item `y` position. """ return self._rect.y
[ "def", "GetY", "(", "self", ")", ":", "return", "self", ".", "_rect", ".", "y" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L3100-L3103
rampageX/firmware-mod-kit
c94cd6aeee50d92ec5280a6dba6d74828fd3606b
src/binwalk-2.1.1/src/binwalk/modules/hashmatch.py
python
HashMatch.run
(self)
return True
Main module method.
Main module method.
[ "Main", "module", "method", "." ]
def run(self): ''' Main module method. ''' # Access the raw self.config.files list directly here, since we accept both # files and directories and self.next_file only works for files. needle = self.config.files[0] haystack = self.config.files[1:] self.header() if os.path.isfile(needle): if os.path.isfile(haystack[0]): self.hash_files(needle, haystack) else: self.hash_file(needle, haystack) else: self.hash_directories(needle, haystack) self.footer() return True
[ "def", "run", "(", "self", ")", ":", "# Access the raw self.config.files list directly here, since we accept both", "# files and directories and self.next_file only works for files.", "needle", "=", "self", ".", "config", ".", "files", "[", "0", "]", "haystack", "=", "self", ".", "config", ".", "files", "[", "1", ":", "]", "self", ".", "header", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "needle", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "haystack", "[", "0", "]", ")", ":", "self", ".", "hash_files", "(", "needle", ",", "haystack", ")", "else", ":", "self", ".", "hash_file", "(", "needle", ",", "haystack", ")", "else", ":", "self", ".", "hash_directories", "(", "needle", ",", "haystack", ")", "self", ".", "footer", "(", ")", "return", "True" ]
https://github.com/rampageX/firmware-mod-kit/blob/c94cd6aeee50d92ec5280a6dba6d74828fd3606b/src/binwalk-2.1.1/src/binwalk/modules/hashmatch.py#L307-L328
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor.py
python
ServiceDescriptor.CopyToProto
(self, proto)
Copies this to a descriptor_pb2.ServiceDescriptorProto. Args: proto: An empty descriptor_pb2.ServiceDescriptorProto.
Copies this to a descriptor_pb2.ServiceDescriptorProto.
[ "Copies", "this", "to", "a", "descriptor_pb2", ".", "ServiceDescriptorProto", "." ]
def CopyToProto(self, proto): """Copies this to a descriptor_pb2.ServiceDescriptorProto. Args: proto: An empty descriptor_pb2.ServiceDescriptorProto. """ # This function is overridden to give a better doc comment. super(ServiceDescriptor, self).CopyToProto(proto)
[ "def", "CopyToProto", "(", "self", ",", "proto", ")", ":", "# This function is overridden to give a better doc comment.", "super", "(", "ServiceDescriptor", ",", "self", ")", ".", "CopyToProto", "(", "proto", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/descriptor.py#L744-L751
facebookarchive/LogDevice
ce7726050edc49a1e15d9160e81c890736b779e2
logdevice/ops/ldshell/logdevice_context.py
python
LDShellContext.on_connected
(self, *args, **kwargs)
Gets called after a connect() command is executed
Gets called after a connect() command is executed
[ "Gets", "called", "after", "a", "connect", "()", "command", "is", "executed" ]
def on_connected(self, *args, **kwargs): """ Gets called after a connect() command is executed """ with self._lock: self._reset_cache() if not self._should_we_be_connected(): cprint(self._get_disconnected_warning(), "yellow", file=sys.stderr) self._is_connected = False else: self._is_connected = True # Fetch config, and cluster name. try: self._initialize_after_connected() except Exception as e: cprint("{}".format(e), "red", file=sys.stderr) self._reset() self._is_connected = False
[ "def", "on_connected", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_reset_cache", "(", ")", "if", "not", "self", ".", "_should_we_be_connected", "(", ")", ":", "cprint", "(", "self", ".", "_get_disconnected_warning", "(", ")", ",", "\"yellow\"", ",", "file", "=", "sys", ".", "stderr", ")", "self", ".", "_is_connected", "=", "False", "else", ":", "self", ".", "_is_connected", "=", "True", "# Fetch config, and cluster name.", "try", ":", "self", ".", "_initialize_after_connected", "(", ")", "except", "Exception", "as", "e", ":", "cprint", "(", "\"{}\"", ".", "format", "(", "e", ")", ",", "\"red\"", ",", "file", "=", "sys", ".", "stderr", ")", "self", ".", "_reset", "(", ")", "self", ".", "_is_connected", "=", "False" ]
https://github.com/facebookarchive/LogDevice/blob/ce7726050edc49a1e15d9160e81c890736b779e2/logdevice/ops/ldshell/logdevice_context.py#L160-L177
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py
python
Locator.get_errors
(self)
return result
Return any errors which have occurred.
Return any errors which have occurred.
[ "Return", "any", "errors", "which", "have", "occurred", "." ]
def get_errors(self): """ Return any errors which have occurred. """ result = [] while not self.errors.empty(): # pragma: no cover try: e = self.errors.get(False) result.append(e) except self.errors.Empty: continue self.errors.task_done() return result
[ "def", "get_errors", "(", "self", ")", ":", "result", "=", "[", "]", "while", "not", "self", ".", "errors", ".", "empty", "(", ")", ":", "# pragma: no cover", "try", ":", "e", "=", "self", ".", "errors", ".", "get", "(", "False", ")", "result", ".", "append", "(", "e", ")", "except", "self", ".", "errors", ".", "Empty", ":", "continue", "self", ".", "errors", ".", "task_done", "(", ")", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/locators.py#L121-L133
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/mesh.py
python
Mesh.structured_iterate_hex_volumes
(self, order="zyx", **kw)
Get an iterator over the volumes of the mesh hexahedra See structured_iterate_hex() for an explanation of the order argument and the available keyword arguments.
Get an iterator over the volumes of the mesh hexahedra
[ "Get", "an", "iterator", "over", "the", "volumes", "of", "the", "mesh", "hexahedra" ]
def structured_iterate_hex_volumes(self, order="zyx", **kw): """Get an iterator over the volumes of the mesh hexahedra See structured_iterate_hex() for an explanation of the order argument and the available keyword arguments. """ self._structured_check() indices, _ = _structured_iter_setup(self.dims, order, **kw) # Use an inefficient but simple approach: call structured_hex_volume() # on each required i,j,k pair. # A better implementation would only make one call to getVtxCoords. for A in itertools.product(*indices): # the ordmap returned from _structured_iter_setup maps to kji/zyx # ordering, but we want ijk/xyz ordering, so create the ordmap # differently. ordmap = [order.find(L) for L in "xyz"] ijk = [A[ordmap[x]] for x in range(3)] yield self.structured_hex_volume(*ijk)
[ "def", "structured_iterate_hex_volumes", "(", "self", ",", "order", "=", "\"zyx\"", ",", "*", "*", "kw", ")", ":", "self", ".", "_structured_check", "(", ")", "indices", ",", "_", "=", "_structured_iter_setup", "(", "self", ".", "dims", ",", "order", ",", "*", "*", "kw", ")", "# Use an inefficient but simple approach: call structured_hex_volume()", "# on each required i,j,k pair.", "# A better implementation would only make one call to getVtxCoords.", "for", "A", "in", "itertools", ".", "product", "(", "*", "indices", ")", ":", "# the ordmap returned from _structured_iter_setup maps to kji/zyx", "# ordering, but we want ijk/xyz ordering, so create the ordmap", "# differently.", "ordmap", "=", "[", "order", ".", "find", "(", "L", ")", "for", "L", "in", "\"xyz\"", "]", "ijk", "=", "[", "A", "[", "ordmap", "[", "x", "]", "]", "for", "x", "in", "range", "(", "3", ")", "]", "yield", "self", ".", "structured_hex_volume", "(", "*", "ijk", ")" ]
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/mesh.py#L1404-L1422
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py
python
concatenate
(arrays, axis=0)
return data
Concatenate a sequence of arrays along the given axis. Parameters ---------- arrays : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- result : MaskedArray The concatenated array with any masked entries preserved. See Also -------- numpy.concatenate : Equivalent function in the top-level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(3) >>> a[1] = ma.masked >>> b = ma.arange(2, 5) >>> a masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) >>> b masked_array(data=[2, 3, 4], mask=False, fill_value=999999) >>> ma.concatenate([a, b]) masked_array(data=[0, --, 2, 2, 3, 4], mask=[False, True, False, False, False, False], fill_value=999999)
Concatenate a sequence of arrays along the given axis.
[ "Concatenate", "a", "sequence", "of", "arrays", "along", "the", "given", "axis", "." ]
def concatenate(arrays, axis=0): """ Concatenate a sequence of arrays along the given axis. Parameters ---------- arrays : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which the arrays will be joined. Default is 0. Returns ------- result : MaskedArray The concatenated array with any masked entries preserved. See Also -------- numpy.concatenate : Equivalent function in the top-level NumPy module. Examples -------- >>> import numpy.ma as ma >>> a = ma.arange(3) >>> a[1] = ma.masked >>> b = ma.arange(2, 5) >>> a masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) >>> b masked_array(data=[2, 3, 4], mask=False, fill_value=999999) >>> ma.concatenate([a, b]) masked_array(data=[0, --, 2, 2, 3, 4], mask=[False, True, False, False, False, False], fill_value=999999) """ d = np.concatenate([getdata(a) for a in arrays], axis) rcls = get_masked_subclass(*arrays) data = d.view(rcls) # Check whether one of the arrays has a non-empty mask. for x in arrays: if getmask(x) is not nomask: break else: return data # OK, so we have to concatenate the masks dm = np.concatenate([getmaskarray(a) for a in arrays], axis) dm = dm.reshape(d.shape) # If we decide to keep a '_shrinkmask' option, we want to check that # all of them are True, and then check for dm.any() data._mask = _shrink_mask(dm) return data
[ "def", "concatenate", "(", "arrays", ",", "axis", "=", "0", ")", ":", "d", "=", "np", ".", "concatenate", "(", "[", "getdata", "(", "a", ")", "for", "a", "in", "arrays", "]", ",", "axis", ")", "rcls", "=", "get_masked_subclass", "(", "*", "arrays", ")", "data", "=", "d", ".", "view", "(", "rcls", ")", "# Check whether one of the arrays has a non-empty mask.", "for", "x", "in", "arrays", ":", "if", "getmask", "(", "x", ")", "is", "not", "nomask", ":", "break", "else", ":", "return", "data", "# OK, so we have to concatenate the masks", "dm", "=", "np", ".", "concatenate", "(", "[", "getmaskarray", "(", "a", ")", "for", "a", "in", "arrays", "]", ",", "axis", ")", "dm", "=", "dm", ".", "reshape", "(", "d", ".", "shape", ")", "# If we decide to keep a '_shrinkmask' option, we want to check that", "# all of them are True, and then check for dm.any()", "data", ".", "_mask", "=", "_shrink_mask", "(", "dm", ")", "return", "data" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L6827-L6884
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/version.py
python
suggest_normalized_version
(s)
return rs
Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one.
Suggest a normalized version close to the given version string.
[ "Suggest", "a", "normalized", "version", "close", "to", "the", "given", "version", "string", "." ]
def suggest_normalized_version(s): """Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one. """ try: normalized_key(s) return s # already rational except UnsupportedVersionError: pass rs = s.lower() # part of this could use maketrans for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'), ('beta', 'b'), ('rc', 'c'), ('-final', ''), ('-pre', 'c'), ('-release', ''), ('.release', ''), ('-stable', ''), ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''), ('final', '')): rs = rs.replace(orig, repl) # if something ends with dev or pre, we add a 0 rs = re.sub(r"pre$", r"pre0", rs) rs = re.sub(r"dev$", r"dev0", rs) # if we have something like "b-2" or "a.2" at the end of the # version, that is pobably beta, alpha, etc # let's remove the dash or dot rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs) # 1.0-dev-r371 -> 1.0.dev371 # 0.1-dev-r79 -> 0.1.dev79 rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs) # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1 rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs) # Clean: v0.3, v1.0 if rs.startswith('v'): rs = rs[1:] # Clean leading '0's on numbers. #TODO: unintended side-effect on, e.g., "2003.05.09" # PyPI stats: 77 (~2%) better rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs) # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers # zero. # PyPI stats: 245 (7.56%) better rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs) # the 'dev-rNNN' tag is a dev tag rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs) # clean the - when used as a pre delimiter rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs) # a terminal "dev" or "devel" can be changed into ".dev0" rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs) # a terminal "dev" can be changed into ".dev0" rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs) # a terminal "final" or "stable" can be removed rs = re.sub(r"(final|stable)$", "", rs) # The 'r' and the '-' tags are post release tags # 0.4a1.r10 -> 0.4a1.post10 # 0.9.33-17222 -> 0.9.33.post17222 # 0.9.33-r17222 -> 0.9.33.post17222 rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs) # Clean 'r' instead of 'dev' usage: # 0.9.33+r17222 -> 0.9.33.dev17222 # 1.0dev123 -> 1.0.dev123 # 1.0.git123 -> 1.0.dev123 # 1.0.bzr123 -> 1.0.dev123 # 0.1a0dev.123 -> 0.1a0.dev123 # PyPI stats: ~150 (~4%) better rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs) # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage: # 0.2.pre1 -> 0.2c1 # 0.2-c1 -> 0.2c1 # 1.0preview123 -> 1.0c123 # PyPI stats: ~21 (0.62%) better rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs) # Tcl/Tk uses "px" for their post release markers rs = re.sub(r"p(\d+)$", r".post\1", rs) try: normalized_key(rs) except UnsupportedVersionError: rs = None return rs
[ "def", "suggest_normalized_version", "(", "s", ")", ":", "try", ":", "normalized_key", "(", "s", ")", "return", "s", "# already rational", "except", "UnsupportedVersionError", ":", "pass", "rs", "=", "s", ".", "lower", "(", ")", "# part of this could use maketrans", "for", "orig", ",", "repl", "in", "(", "(", "'-alpha'", ",", "'a'", ")", ",", "(", "'-beta'", ",", "'b'", ")", ",", "(", "'alpha'", ",", "'a'", ")", ",", "(", "'beta'", ",", "'b'", ")", ",", "(", "'rc'", ",", "'c'", ")", ",", "(", "'-final'", ",", "''", ")", ",", "(", "'-pre'", ",", "'c'", ")", ",", "(", "'-release'", ",", "''", ")", ",", "(", "'.release'", ",", "''", ")", ",", "(", "'-stable'", ",", "''", ")", ",", "(", "'+'", ",", "'.'", ")", ",", "(", "'_'", ",", "'.'", ")", ",", "(", "' '", ",", "''", ")", ",", "(", "'.final'", ",", "''", ")", ",", "(", "'final'", ",", "''", ")", ")", ":", "rs", "=", "rs", ".", "replace", "(", "orig", ",", "repl", ")", "# if something ends with dev or pre, we add a 0", "rs", "=", "re", ".", "sub", "(", "r\"pre$\"", ",", "r\"pre0\"", ",", "rs", ")", "rs", "=", "re", ".", "sub", "(", "r\"dev$\"", ",", "r\"dev0\"", ",", "rs", ")", "# if we have something like \"b-2\" or \"a.2\" at the end of the", "# version, that is pobably beta, alpha, etc", "# let's remove the dash or dot", "rs", "=", "re", ".", "sub", "(", "r\"([abc]|rc)[\\-\\.](\\d+)$\"", ",", "r\"\\1\\2\"", ",", "rs", ")", "# 1.0-dev-r371 -> 1.0.dev371", "# 0.1-dev-r79 -> 0.1.dev79", "rs", "=", "re", ".", "sub", "(", "r\"[\\-\\.](dev)[\\-\\.]?r?(\\d+)$\"", ",", "r\".\\1\\2\"", ",", "rs", ")", "# Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1", "rs", "=", "re", ".", "sub", "(", "r\"[.~]?([abc])\\.?\"", ",", "r\"\\1\"", ",", "rs", ")", "# Clean: v0.3, v1.0", "if", "rs", ".", "startswith", "(", "'v'", ")", ":", "rs", "=", "rs", "[", "1", ":", "]", "# Clean leading '0's on numbers.", "#TODO: unintended side-effect on, e.g., \"2003.05.09\"", "# PyPI stats: 77 (~2%) better", "rs", "=", "re", ".", "sub", "(", "r\"\\b0+(\\d+)(?!\\d)\"", ",", "r\"\\1\"", ",", "rs", ")", "# Clean a/b/c with no version. E.g. \"1.0a\" -> \"1.0a0\". Setuptools infers", "# zero.", "# PyPI stats: 245 (7.56%) better", "rs", "=", "re", ".", "sub", "(", "r\"(\\d+[abc])$\"", ",", "r\"\\g<1>0\"", ",", "rs", ")", "# the 'dev-rNNN' tag is a dev tag", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(dev-r|dev\\.r)\\.?(\\d+)$\"", ",", "r\".dev\\2\"", ",", "rs", ")", "# clean the - when used as a pre delimiter", "rs", "=", "re", ".", "sub", "(", "r\"-(a|b|c)(\\d+)$\"", ",", "r\"\\1\\2\"", ",", "rs", ")", "# a terminal \"dev\" or \"devel\" can be changed into \".dev0\"", "rs", "=", "re", ".", "sub", "(", "r\"[\\.\\-](dev|devel)$\"", ",", "r\".dev0\"", ",", "rs", ")", "# a terminal \"dev\" can be changed into \".dev0\"", "rs", "=", "re", ".", "sub", "(", "r\"(?![\\.\\-])dev$\"", ",", "r\".dev0\"", ",", "rs", ")", "# a terminal \"final\" or \"stable\" can be removed", "rs", "=", "re", ".", "sub", "(", "r\"(final|stable)$\"", ",", "\"\"", ",", "rs", ")", "# The 'r' and the '-' tags are post release tags", "# 0.4a1.r10 -> 0.4a1.post10", "# 0.9.33-17222 -> 0.9.33.post17222", "# 0.9.33-r17222 -> 0.9.33.post17222", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(r|-|-r)\\.?(\\d+)$\"", ",", "r\".post\\2\"", ",", "rs", ")", "# Clean 'r' instead of 'dev' usage:", "# 0.9.33+r17222 -> 0.9.33.dev17222", "# 1.0dev123 -> 1.0.dev123", "# 1.0.git123 -> 1.0.dev123", "# 1.0.bzr123 -> 1.0.dev123", "# 0.1a0dev.123 -> 0.1a0.dev123", "# PyPI stats: ~150 (~4%) better", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(dev|git|bzr)\\.?(\\d+)$\"", ",", "r\".dev\\2\"", ",", "rs", ")", "# Clean '.pre' (normalized from '-pre' above) instead of 'c' usage:", "# 0.2.pre1 -> 0.2c1", "# 0.2-c1 -> 0.2c1", "# 1.0preview123 -> 1.0c123", "# PyPI stats: ~21 (0.62%) better", "rs", "=", "re", ".", "sub", "(", "r\"\\.?(pre|preview|-c)(\\d+)$\"", ",", "r\"c\\g<2>\"", ",", "rs", ")", "# Tcl/Tk uses \"px\" for their post release markers", "rs", "=", "re", ".", "sub", "(", "r\"p(\\d+)$\"", ",", "r\".post\\1\"", ",", "rs", ")", "try", ":", "normalized_key", "(", "rs", ")", "except", "UnsupportedVersionError", ":", "rs", "=", "None", "return", "rs" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/version.py#L420-L528
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
Grid.GetSelectionBackground
(*args, **kwargs)
return _grid.Grid_GetSelectionBackground(*args, **kwargs)
GetSelectionBackground(self) -> Colour
GetSelectionBackground(self) -> Colour
[ "GetSelectionBackground", "(", "self", ")", "-", ">", "Colour" ]
def GetSelectionBackground(*args, **kwargs): """GetSelectionBackground(self) -> Colour""" return _grid.Grid_GetSelectionBackground(*args, **kwargs)
[ "def", "GetSelectionBackground", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetSelectionBackground", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L2093-L2095
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/nn/utils/prune.py
python
global_unstructured
(parameters, pruning_method, importance_scores=None, **kwargs)
r""" Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``. Modifies modules in place by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: parameters (Iterable of (module, name) tuples): parameters of the model to prune in a global fashion, i.e. by aggregating all weights prior to deciding which ones to prune. module must be of type :class:`nn.Module`, and name must be a string. pruning_method (function): a valid pruning function from this module, or a custom one implemented by the user that satisfies the implementation guidelines and has ``PRUNING_TYPE='unstructured'``. importance_scores (dict): a dictionary mapping (module, name) tuples to the corresponding parameter's importance scores tensor. The tensor should be the same shape as the parameter, and is used for computing mask for pruning. If unspecified or None, the parameter will be used in place of its importance scores. kwargs: other keyword arguments such as: amount (int or float): quantity of parameters to prune across the specified parameters. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. Raises: TypeError: if ``PRUNING_TYPE != 'unstructured'`` Note: Since global structured pruning doesn't make much sense unless the norm is normalized by the size of the parameter, we now limit the scope of global pruning to unstructured methods. Examples: >>> net = nn.Sequential(OrderedDict([ ('first', nn.Linear(10, 4)), ('second', nn.Linear(4, 1)), ])) >>> parameters_to_prune = ( (net.first, 'weight'), (net.second, 'weight'), ) >>> prune.global_unstructured( parameters_to_prune, pruning_method=prune.L1Unstructured, amount=10, ) >>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0)) tensor(10, dtype=torch.uint8)
r""" Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``. Modifies modules in place by:
[ "r", "Globally", "prunes", "tensors", "corresponding", "to", "all", "parameters", "in", "parameters", "by", "applying", "the", "specified", "pruning_method", ".", "Modifies", "modules", "in", "place", "by", ":" ]
def global_unstructured(parameters, pruning_method, importance_scores=None, **kwargs): r""" Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``. Modifies modules in place by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: parameters (Iterable of (module, name) tuples): parameters of the model to prune in a global fashion, i.e. by aggregating all weights prior to deciding which ones to prune. module must be of type :class:`nn.Module`, and name must be a string. pruning_method (function): a valid pruning function from this module, or a custom one implemented by the user that satisfies the implementation guidelines and has ``PRUNING_TYPE='unstructured'``. importance_scores (dict): a dictionary mapping (module, name) tuples to the corresponding parameter's importance scores tensor. The tensor should be the same shape as the parameter, and is used for computing mask for pruning. If unspecified or None, the parameter will be used in place of its importance scores. kwargs: other keyword arguments such as: amount (int or float): quantity of parameters to prune across the specified parameters. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. Raises: TypeError: if ``PRUNING_TYPE != 'unstructured'`` Note: Since global structured pruning doesn't make much sense unless the norm is normalized by the size of the parameter, we now limit the scope of global pruning to unstructured methods. Examples: >>> net = nn.Sequential(OrderedDict([ ('first', nn.Linear(10, 4)), ('second', nn.Linear(4, 1)), ])) >>> parameters_to_prune = ( (net.first, 'weight'), (net.second, 'weight'), ) >>> prune.global_unstructured( parameters_to_prune, pruning_method=prune.L1Unstructured, amount=10, ) >>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0)) tensor(10, dtype=torch.uint8) """ # ensure parameters is a list or generator of tuples if not isinstance(parameters, Iterable): raise TypeError("global_unstructured(): parameters is not an Iterable") importance_scores = importance_scores if importance_scores is not None else {} if not isinstance(importance_scores, dict): raise TypeError("global_unstructured(): importance_scores must be of type dict") # flatten importance scores to consider them all at once in global pruning relevant_importance_scores = torch.nn.utils.parameters_to_vector( [ importance_scores.get((module, name), getattr(module, name)) for (module, name) in parameters ] ) # similarly, flatten the masks (if they exist), or use a flattened vector # of 1s of the same dimensions as t default_mask = torch.nn.utils.parameters_to_vector( [ getattr(module, name + "_mask", torch.ones_like(getattr(module, name))) for (module, name) in parameters ] ) # use the canonical pruning methods to compute the new mask, even if the # parameter is now a flattened out version of `parameters` container = PruningContainer() container._tensor_name = "temp" # to make it match that of `method` method = pruning_method(**kwargs) method._tensor_name = "temp" # to make it match that of `container` if method.PRUNING_TYPE != "unstructured": raise TypeError( 'Only "unstructured" PRUNING_TYPE supported for ' "the `pruning_method`. Found method {} of type {}".format( pruning_method, method.PRUNING_TYPE ) ) container.add_pruning_method(method) # use the `compute_mask` method from `PruningContainer` to combine the # mask computed by the new method with the pre-existing mask final_mask = container.compute_mask(relevant_importance_scores, default_mask) # Pointer for slicing the mask to match the shape of each parameter pointer = 0 for module, name in parameters: param = getattr(module, name) # The length of the parameter num_param = param.numel() # Slice the mask, reshape it param_mask = final_mask[pointer : pointer + num_param].view_as(param) # Assign the correct pre-computed mask to each parameter and add it # to the forward_pre_hooks like any other pruning method custom_from_mask(module, name, mask=param_mask) # Increment the pointer to continue slicing the final_mask pointer += num_param
[ "def", "global_unstructured", "(", "parameters", ",", "pruning_method", ",", "importance_scores", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# ensure parameters is a list or generator of tuples", "if", "not", "isinstance", "(", "parameters", ",", "Iterable", ")", ":", "raise", "TypeError", "(", "\"global_unstructured(): parameters is not an Iterable\"", ")", "importance_scores", "=", "importance_scores", "if", "importance_scores", "is", "not", "None", "else", "{", "}", "if", "not", "isinstance", "(", "importance_scores", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"global_unstructured(): importance_scores must be of type dict\"", ")", "# flatten importance scores to consider them all at once in global pruning", "relevant_importance_scores", "=", "torch", ".", "nn", ".", "utils", ".", "parameters_to_vector", "(", "[", "importance_scores", ".", "get", "(", "(", "module", ",", "name", ")", ",", "getattr", "(", "module", ",", "name", ")", ")", "for", "(", "module", ",", "name", ")", "in", "parameters", "]", ")", "# similarly, flatten the masks (if they exist), or use a flattened vector", "# of 1s of the same dimensions as t", "default_mask", "=", "torch", ".", "nn", ".", "utils", ".", "parameters_to_vector", "(", "[", "getattr", "(", "module", ",", "name", "+", "\"_mask\"", ",", "torch", ".", "ones_like", "(", "getattr", "(", "module", ",", "name", ")", ")", ")", "for", "(", "module", ",", "name", ")", "in", "parameters", "]", ")", "# use the canonical pruning methods to compute the new mask, even if the", "# parameter is now a flattened out version of `parameters`", "container", "=", "PruningContainer", "(", ")", "container", ".", "_tensor_name", "=", "\"temp\"", "# to make it match that of `method`", "method", "=", "pruning_method", "(", "*", "*", "kwargs", ")", "method", ".", "_tensor_name", "=", "\"temp\"", "# to make it match that of `container`", "if", "method", ".", "PRUNING_TYPE", "!=", "\"unstructured\"", ":", "raise", "TypeError", "(", "'Only \"unstructured\" PRUNING_TYPE supported for '", "\"the `pruning_method`. Found method {} of type {}\"", ".", "format", "(", "pruning_method", ",", "method", ".", "PRUNING_TYPE", ")", ")", "container", ".", "add_pruning_method", "(", "method", ")", "# use the `compute_mask` method from `PruningContainer` to combine the", "# mask computed by the new method with the pre-existing mask", "final_mask", "=", "container", ".", "compute_mask", "(", "relevant_importance_scores", ",", "default_mask", ")", "# Pointer for slicing the mask to match the shape of each parameter", "pointer", "=", "0", "for", "module", ",", "name", "in", "parameters", ":", "param", "=", "getattr", "(", "module", ",", "name", ")", "# The length of the parameter", "num_param", "=", "param", ".", "numel", "(", ")", "# Slice the mask, reshape it", "param_mask", "=", "final_mask", "[", "pointer", ":", "pointer", "+", "num_param", "]", ".", "view_as", "(", "param", ")", "# Assign the correct pre-computed mask to each parameter and add it", "# to the forward_pre_hooks like any other pruning method", "custom_from_mask", "(", "module", ",", "name", ",", "mask", "=", "param_mask", ")", "# Increment the pointer to continue slicing the final_mask", "pointer", "+=", "num_param" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/utils/prune.py#L1011-L1128
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/iostream.py
python
BaseIOStream.read_until_close
(self)
return future
Asynchronously reads all data from the socket until it is closed. This will buffer all available data until ``max_buffer_size`` is reached. If flow control or cancellation are desired, use a loop with `read_bytes(partial=True) <.read_bytes>` instead. .. versionchanged:: 4.0 The callback argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` and ``streaming_callback`` arguments have been removed. Use the returned `.Future` (and `read_bytes` with ``partial=True`` for ``streaming_callback``) instead.
Asynchronously reads all data from the socket until it is closed.
[ "Asynchronously", "reads", "all", "data", "from", "the", "socket", "until", "it", "is", "closed", "." ]
def read_until_close(self) -> Awaitable[bytes]: """Asynchronously reads all data from the socket until it is closed. This will buffer all available data until ``max_buffer_size`` is reached. If flow control or cancellation are desired, use a loop with `read_bytes(partial=True) <.read_bytes>` instead. .. versionchanged:: 4.0 The callback argument is now optional and a `.Future` will be returned if it is omitted. .. versionchanged:: 6.0 The ``callback`` and ``streaming_callback`` arguments have been removed. Use the returned `.Future` (and `read_bytes` with ``partial=True`` for ``streaming_callback``) instead. """ future = self._start_read() if self.closed(): self._finish_read(self._read_buffer_size, False) return future self._read_until_close = True try: self._try_inline_read() except: future.add_done_callback(lambda f: f.exception()) raise return future
[ "def", "read_until_close", "(", "self", ")", "->", "Awaitable", "[", "bytes", "]", ":", "future", "=", "self", ".", "_start_read", "(", ")", "if", "self", ".", "closed", "(", ")", ":", "self", ".", "_finish_read", "(", "self", ".", "_read_buffer_size", ",", "False", ")", "return", "future", "self", ".", "_read_until_close", "=", "True", "try", ":", "self", ".", "_try_inline_read", "(", ")", "except", ":", "future", ".", "add_done_callback", "(", "lambda", "f", ":", "f", ".", "exception", "(", ")", ")", "raise", "return", "future" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/iostream.py#L481-L509
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/web-page-replay/net_configs.py
python
GetNetConfig
(key)
return _NET_CONFIGS[key]
Returns the NetConfig object corresponding to the given |key|.
Returns the NetConfig object corresponding to the given |key|.
[ "Returns", "the", "NetConfig", "object", "corresponding", "to", "the", "given", "|key|", "." ]
def GetNetConfig(key): """Returns the NetConfig object corresponding to the given |key|.""" if key not in _NET_CONFIGS: raise KeyError('No net config with key: %s' % key) return _NET_CONFIGS[key]
[ "def", "GetNetConfig", "(", "key", ")", ":", "if", "key", "not", "in", "_NET_CONFIGS", ":", "raise", "KeyError", "(", "'No net config with key: %s'", "%", "key", ")", "return", "_NET_CONFIGS", "[", "key", "]" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/web-page-replay/net_configs.py#L44-L48
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py
python
Output.encoding
(self)
Return the encoding for this output, e.g. 'utf-8'. (This is used mainly to know which characters are supported by the output the data, so that the UI can provide alternatives, when required.)
Return the encoding for this output, e.g. 'utf-8'. (This is used mainly to know which characters are supported by the output the data, so that the UI can provide alternatives, when required.)
[ "Return", "the", "encoding", "for", "this", "output", "e", ".", "g", ".", "utf", "-", "8", ".", "(", "This", "is", "used", "mainly", "to", "know", "which", "characters", "are", "supported", "by", "the", "output", "the", "data", "so", "that", "the", "UI", "can", "provide", "alternatives", "when", "required", ".", ")" ]
def encoding(self): """ Return the encoding for this output, e.g. 'utf-8'. (This is used mainly to know which characters are supported by the output the data, so that the UI can provide alternatives, when required.) """
[ "def", "encoding", "(", "self", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py#L28-L34
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_concept_space.py
python
p_terms_terms_term
(p)
terms : terms COMMA term
terms : terms COMMA term
[ "terms", ":", "terms", "COMMA", "term" ]
def p_terms_terms_term(p): 'terms : terms COMMA term' p[0] = p[1] p[0].append(p[3])
[ "def", "p_terms_terms_term", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "p", "[", "0", "]", ".", "append", "(", "p", "[", "3", "]", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_concept_space.py#L146-L149
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/_parseaddr.py
python
AddrlistClass.getaddrlist
(self)
return result
Parse all addresses. Returns a list containing all of the addresses.
Parse all addresses.
[ "Parse", "all", "addresses", "." ]
def getaddrlist(self): """Parse all addresses. Returns a list containing all of the addresses. """ result = [] while self.pos < len(self.field): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result
[ "def", "getaddrlist", "(", "self", ")", ":", "result", "=", "[", "]", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "ad", "=", "self", ".", "getaddress", "(", ")", "if", "ad", ":", "result", "+=", "ad", "else", ":", "result", ".", "append", "(", "(", "''", ",", "''", ")", ")", "return", "result" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/email/_parseaddr.py#L211-L223
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/vision/py_transforms_util.py
python
horizontal_flip
(img)
return img.transpose(Image.FLIP_LEFT_RIGHT)
Flip the input image horizontally. Args: img (PIL image): Image to be flipped horizontally. Returns: img (PIL image), Horizontally flipped image.
Flip the input image horizontally.
[ "Flip", "the", "input", "image", "horizontally", "." ]
def horizontal_flip(img): """ Flip the input image horizontally. Args: img (PIL image): Image to be flipped horizontally. Returns: img (PIL image), Horizontally flipped image. """ if not is_pil(img): raise TypeError(augment_error_message.format(type(img))) return img.transpose(Image.FLIP_LEFT_RIGHT)
[ "def", "horizontal_flip", "(", "img", ")", ":", "if", "not", "is_pil", "(", "img", ")", ":", "raise", "TypeError", "(", "augment_error_message", ".", "format", "(", "type", "(", "img", ")", ")", ")", "return", "img", ".", "transpose", "(", "Image", ".", "FLIP_LEFT_RIGHT", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/vision/py_transforms_util.py#L175-L188
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py
python
extract_audio
( video_source_filename, audio_id=128, verbose_flag=0, dry_run_flag=0)
This extracts the given audio_id track as raw uncompressed PCM from the given source video. Note that mplayer always saves this to audiodump.wav. At this time there is no way to set the output audio name.
This extracts the given audio_id track as raw uncompressed PCM from the given source video. Note that mplayer always saves this to audiodump.wav. At this time there is no way to set the output audio name.
[ "This", "extracts", "the", "given", "audio_id", "track", "as", "raw", "uncompressed", "PCM", "from", "the", "given", "source", "video", ".", "Note", "that", "mplayer", "always", "saves", "this", "to", "audiodump", ".", "wav", ".", "At", "this", "time", "there", "is", "no", "way", "to", "set", "the", "output", "audio", "name", "." ]
def extract_audio( video_source_filename, audio_id=128, verbose_flag=0, dry_run_flag=0): """This extracts the given audio_id track as raw uncompressed PCM from the given source video. Note that mplayer always saves this to audiodump.wav. At this time there is no way to set the output audio name. """ #cmd = "mplayer %(video_source_filename)s -vc null -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop" % locals() cmd = "mplayer -quiet '%(video_source_filename)s' -vc dummy -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop" % locals() if verbose_flag: print cmd if not dry_run_flag: run(cmd) print
[ "def", "extract_audio", "(", "video_source_filename", ",", "audio_id", "=", "128", ",", "verbose_flag", "=", "0", ",", "dry_run_flag", "=", "0", ")", ":", "#cmd = \"mplayer %(video_source_filename)s -vc null -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop\" % locals()", "cmd", "=", "\"mplayer -quiet '%(video_source_filename)s' -vc dummy -vo null -aid %(audio_id)s -ao pcm:fast -noframedrop\"", "%", "locals", "(", ")", "if", "verbose_flag", ":", "print", "cmd", "if", "not", "dry_run_flag", ":", "run", "(", "cmd", ")", "print" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/third_party/Python/module/pexpect-2.4/examples/rippy.py#L494-L509
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PSDraw.py
python
PSDraw.setfont
(self, font, size)
Selects which font to use. :param font: A Postscript font name :param size: Size in points.
Selects which font to use.
[ "Selects", "which", "font", "to", "use", "." ]
def setfont(self, font, size): """ Selects which font to use. :param font: A Postscript font name :param size: Size in points. """ if font not in self.isofont: # reencode font self._fp_write("/PSDraw-{} ISOLatin1Encoding /{} E\n".format(font, font)) self.isofont[font] = 1 # rough self._fp_write("/F0 %d /PSDraw-%s F\n" % (size, font))
[ "def", "setfont", "(", "self", ",", "font", ",", "size", ")", ":", "if", "font", "not", "in", "self", ".", "isofont", ":", "# reencode font", "self", ".", "_fp_write", "(", "\"/PSDraw-{} ISOLatin1Encoding /{} E\\n\"", ".", "format", "(", "font", ",", "font", ")", ")", "self", ".", "isofont", "[", "font", "]", "=", "1", "# rough", "self", ".", "_fp_write", "(", "\"/F0 %d /PSDraw-%s F\\n\"", "%", "(", "size", ",", "font", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PSDraw.py#L65-L77
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/rpm.py
python
build_specfile
(target, source, env)
Builds a RPM specfile from a dictionary with string metadata and by analyzing a tree of nodes.
Builds a RPM specfile from a dictionary with string metadata and by analyzing a tree of nodes.
[ "Builds", "a", "RPM", "specfile", "from", "a", "dictionary", "with", "string", "metadata", "and", "by", "analyzing", "a", "tree", "of", "nodes", "." ]
def build_specfile(target, source, env): """ Builds a RPM specfile from a dictionary with string metadata and by analyzing a tree of nodes. """ file = open(target[0].get_abspath(), 'w') try: file.write( build_specfile_header(env) ) file.write( build_specfile_sections(env) ) file.write( build_specfile_filesection(env, source) ) file.close() # call a user specified function if 'CHANGE_SPECFILE' in env: env['CHANGE_SPECFILE'](target, source) except KeyError, e: raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] )
[ "def", "build_specfile", "(", "target", ",", "source", ",", "env", ")", ":", "file", "=", "open", "(", "target", "[", "0", "]", ".", "get_abspath", "(", ")", ",", "'w'", ")", "try", ":", "file", ".", "write", "(", "build_specfile_header", "(", "env", ")", ")", "file", ".", "write", "(", "build_specfile_sections", "(", "env", ")", ")", "file", ".", "write", "(", "build_specfile_filesection", "(", "env", ",", "source", ")", ")", "file", ".", "close", "(", ")", "# call a user specified function", "if", "'CHANGE_SPECFILE'", "in", "env", ":", "env", "[", "'CHANGE_SPECFILE'", "]", "(", "target", ",", "source", ")", "except", "KeyError", ",", "e", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "'\"%s\" package field for RPM is missing.'", "%", "e", ".", "args", "[", "0", "]", ")" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/packaging/rpm.py#L123-L140
projectchrono/chrono
92015a8a6f84ef63ac8206a74e54a676251dcc89
src/demos/python/chrono-tensorflow/PPO/utils.py
python
Scaler.__init__
(self, obs_dim, env_name)
Args: obs_dim: dimension of axis=1
Args: obs_dim: dimension of axis=1
[ "Args", ":", "obs_dim", ":", "dimension", "of", "axis", "=", "1" ]
def __init__(self, obs_dim, env_name): """ Args: obs_dim: dimension of axis=1 """ self.env_name = env_name self.vars = np.zeros(obs_dim) self.means = np.zeros(obs_dim) self.m = 0 self.n = 0 self.first_pass = True
[ "def", "__init__", "(", "self", ",", "obs_dim", ",", "env_name", ")", ":", "self", ".", "env_name", "=", "env_name", "self", ".", "vars", "=", "np", ".", "zeros", "(", "obs_dim", ")", "self", ".", "means", "=", "np", ".", "zeros", "(", "obs_dim", ")", "self", ".", "m", "=", "0", "self", ".", "n", "=", "0", "self", ".", "first_pass", "=", "True" ]
https://github.com/projectchrono/chrono/blob/92015a8a6f84ef63ac8206a74e54a676251dcc89/src/demos/python/chrono-tensorflow/PPO/utils.py#L19-L29
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
RemoveMultiLineCommentsFromRange
(lines, begin, end)
Clears a range of lines for multi-line comments.
Clears a range of lines for multi-line comments.
[ "Clears", "a", "range", "of", "lines", "for", "multi", "-", "line", "comments", "." ]
def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '/**/'
[ "def", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "begin", ",", "end", ")", ":", "# Having // dummy comments makes the lines non-empty, so we will not get", "# unnecessary blank line warnings later in the code.", "for", "i", "in", "range", "(", "begin", ",", "end", ")", ":", "lines", "[", "i", "]", "=", "'/**/'" ]
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L1384-L1389
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
llvm/bindings/python/llvm/object.py
python
Section.address
(self)
return lib.LLVMGetSectionAddress(self)
The address of this section, in long bytes.
The address of this section, in long bytes.
[ "The", "address", "of", "this", "section", "in", "long", "bytes", "." ]
def address(self): """The address of this section, in long bytes.""" if self.expired: raise Exception('Section instance has expired.') return lib.LLVMGetSectionAddress(self)
[ "def", "address", "(", "self", ")", ":", "if", "self", ".", "expired", ":", "raise", "Exception", "(", "'Section instance has expired.'", ")", "return", "lib", ".", "LLVMGetSectionAddress", "(", "self", ")" ]
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/llvm/bindings/python/llvm/object.py#L224-L229
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_vim.py
python
EditraCommander.JoinLines
(self, repeat)
Join lines into a single line. @param repeat: number of lines below the current line to join with
Join lines into a single line. @param repeat: number of lines below the current line to join with
[ "Join", "lines", "into", "a", "single", "line", ".", "@param", "repeat", ":", "number", "of", "lines", "below", "the", "current", "line", "to", "join", "with" ]
def JoinLines(self, repeat): """Join lines into a single line. @param repeat: number of lines below the current line to join with """ self.SelectLines(repeat) self.stc.LinesJoinSelected()
[ "def", "JoinLines", "(", "self", ",", "repeat", ")", ":", "self", ".", "SelectLines", "(", "repeat", ")", "self", ".", "stc", ".", "LinesJoinSelected", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_vim.py#L687-L693
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py
python
Regex.__init__
( self, pattern, flags=0)
The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.
The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.
[ "The", "parameters", "C", "{", "pattern", "}", "and", "C", "{", "flags", "}", "are", "passed", "to", "the", "C", "{", "re", ".", "compile", "()", "}", "function", "as", "-", "is", ".", "See", "the", "Python", "C", "{", "re", "}", "module", "for", "an", "explanation", "of", "the", "acceptable", "patterns", "and", "flags", "." ]
def __init__( self, pattern, flags=0): """The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.""" super(Regex,self).__init__() if isinstance(pattern, basestring): if not pattern: warnings.warn("null string passed to Regex; use Empty() instead", SyntaxWarning, stacklevel=2) self.pattern = pattern self.flags = flags try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error: warnings.warn("invalid pattern (%s) passed to Regex" % pattern, SyntaxWarning, stacklevel=2) raise elif isinstance(pattern, Regex.compiledREtype): self.re = pattern self.pattern = \ self.reString = str(pattern) self.flags = flags else: raise ValueError("Regex may only be constructed with a string or a compiled RE object") self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayIndexError = False self.mayReturnEmpty = True
[ "def", "__init__", "(", "self", ",", "pattern", ",", "flags", "=", "0", ")", ":", "super", "(", "Regex", ",", "self", ")", ".", "__init__", "(", ")", "if", "isinstance", "(", "pattern", ",", "basestring", ")", ":", "if", "not", "pattern", ":", "warnings", ".", "warn", "(", "\"null string passed to Regex; use Empty() instead\"", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "self", ".", "pattern", "=", "pattern", "self", ".", "flags", "=", "flags", "try", ":", "self", ".", "re", "=", "re", ".", "compile", "(", "self", ".", "pattern", ",", "self", ".", "flags", ")", "self", ".", "reString", "=", "self", ".", "pattern", "except", "sre_constants", ".", "error", ":", "warnings", ".", "warn", "(", "\"invalid pattern (%s) passed to Regex\"", "%", "pattern", ",", "SyntaxWarning", ",", "stacklevel", "=", "2", ")", "raise", "elif", "isinstance", "(", "pattern", ",", "Regex", ".", "compiledREtype", ")", ":", "self", ".", "re", "=", "pattern", "self", ".", "pattern", "=", "self", ".", "reString", "=", "str", "(", "pattern", ")", "self", ".", "flags", "=", "flags", "else", ":", "raise", "ValueError", "(", "\"Regex may only be constructed with a string or a compiled RE object\"", ")", "self", ".", "name", "=", "_ustr", "(", "self", ")", "self", ".", "errmsg", "=", "\"Expected \"", "+", "self", ".", "name", "self", ".", "mayIndexError", "=", "False", "self", ".", "mayReturnEmpty", "=", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pkg_resources/_vendor/pyparsing.py#L2779-L2811
abyzovlab/CNVnator
c73786d6160f17b020feae928148533ca036fad2
pytools/io.py
python
IO.signal_name
(self, chr, bin_size, signal, flags=FLAG_USEMASK | FLAG_GC_CORR)
return self.signals[signal] % {"chr": chr, "bin_size": bin_size, "rd_flag": self.sufix_rd_flag(flags), "snp_flag": self.sufix_snp_flag(flags), "flag": self.sufix_flag(flags)}
Returns TH1 or TH2 name for signal
Returns TH1 or TH2 name for signal
[ "Returns", "TH1", "or", "TH2", "name", "for", "signal" ]
def signal_name(self, chr, bin_size, signal, flags=FLAG_USEMASK | FLAG_GC_CORR): """Returns TH1 or TH2 name for signal""" return self.signals[signal] % {"chr": chr, "bin_size": bin_size, "rd_flag": self.sufix_rd_flag(flags), "snp_flag": self.sufix_snp_flag(flags), "flag": self.sufix_flag(flags)}
[ "def", "signal_name", "(", "self", ",", "chr", ",", "bin_size", ",", "signal", ",", "flags", "=", "FLAG_USEMASK", "|", "FLAG_GC_CORR", ")", ":", "return", "self", ".", "signals", "[", "signal", "]", "%", "{", "\"chr\"", ":", "chr", ",", "\"bin_size\"", ":", "bin_size", ",", "\"rd_flag\"", ":", "self", ".", "sufix_rd_flag", "(", "flags", ")", ",", "\"snp_flag\"", ":", "self", ".", "sufix_snp_flag", "(", "flags", ")", ",", "\"flag\"", ":", "self", ".", "sufix_flag", "(", "flags", ")", "}" ]
https://github.com/abyzovlab/CNVnator/blob/c73786d6160f17b020feae928148533ca036fad2/pytools/io.py#L98-L101
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/ciconfig/evergreen.py
python
Task.generated_task_name
(self)
return self.name[:-4]
Get basename of the tasks generated by this _gen task. :return: Basename of the generated tasks.
Get basename of the tasks generated by this _gen task.
[ "Get", "basename", "of", "the", "tasks", "generated", "by", "this", "_gen", "task", "." ]
def generated_task_name(self): """ Get basename of the tasks generated by this _gen task. :return: Basename of the generated tasks. """ if not self.is_generate_resmoke_task: raise TypeError("Only _gen tasks can have generated task names") return self.name[:-4]
[ "def", "generated_task_name", "(", "self", ")", ":", "if", "not", "self", ".", "is_generate_resmoke_task", ":", "raise", "TypeError", "(", "\"Only _gen tasks can have generated task names\"", ")", "return", "self", ".", "name", "[", ":", "-", "4", "]" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/ciconfig/evergreen.py#L153-L162
google/clif
cab24d6a105609a65c95a36a1712ae3c20c7b5df
clif/python/gen.py
python
FunctionCall
(pyname, wrapper, doc, catch, call, postcall_init, typepostconversion, func_ast, lineno, prepend_self=None)
Generate PyCFunction wrapper from AST.FuncDecl func_ast. Args: pyname: str - Python function name (may be special: ends with @) wrapper: str - generated function name doc: str - C++ signature catch: bool - catch C++ exceptions call: str | [str] - C++ command(s) to call the wrapped function (without "(params);" part). postcall_init: str - C++ command; to (re)set ret0. typepostconversion: dict(pytype, index) to convert to pytype func_ast: AST.FuncDecl protobuf lineno: int - .clif line number where func_ast defined prepend_self: AST.Param - Use self as 1st parameter. Yields: Source code for wrapped function. Raises: ValueError: for non-supported default arguments
Generate PyCFunction wrapper from AST.FuncDecl func_ast.
[ "Generate", "PyCFunction", "wrapper", "from", "AST", ".", "FuncDecl", "func_ast", "." ]
def FunctionCall(pyname, wrapper, doc, catch, call, postcall_init, typepostconversion, func_ast, lineno, prepend_self=None): """Generate PyCFunction wrapper from AST.FuncDecl func_ast. Args: pyname: str - Python function name (may be special: ends with @) wrapper: str - generated function name doc: str - C++ signature catch: bool - catch C++ exceptions call: str | [str] - C++ command(s) to call the wrapped function (without "(params);" part). postcall_init: str - C++ command; to (re)set ret0. typepostconversion: dict(pytype, index) to convert to pytype func_ast: AST.FuncDecl protobuf lineno: int - .clif line number where func_ast defined prepend_self: AST.Param - Use self as 1st parameter. Yields: Source code for wrapped function. Raises: ValueError: for non-supported default arguments """ ctxmgr = pyname.endswith('@') if ctxmgr: ctxmgr = pyname assert ctxmgr in ('__enter__@', '__exit__@'), ( 'Invalid context manager name ' + pyname) pyname = pyname.rstrip('@') nret = len(func_ast.returns) return_type = astutils.FuncReturnType(func_ast) # Can't use cpp_exact_type. # return_type mangled to FQN and drop &, sadly it also drop const. void_return_type = 'void' == return_type # Has extra func parameters for output values. xouts = nret > (0 if void_return_type else 1) params = [] # C++ parameter names. nargs = len(func_ast.params) is_ternaryfunc_slot = pyname == '__call__' yield '' if func_ast.classmethod: yield '// @classmethod ' + doc arg0 = 'cls' # Extra protection that generated code does not use 'self'. else: yield '// ' + doc arg0 = 'self' needs_kw = nargs or is_ternaryfunc_slot yield 'static PyObject* %s(PyObject* %s%s) {' % ( wrapper, arg0, ', PyObject* args, PyObject* kw' if needs_kw else '') if is_ternaryfunc_slot and not nargs: yield I+('if (!ensure_no_args_and_kw_args("%s", args, kw)) return nullptr;' % pyname) if prepend_self: unused_check_nullptr, out = _CreateInputParameter( pyname+' line %d' % lineno, prepend_self, 'arg0', params) yield I+out yield I+'if (!Clif_PyObjAs(self, &arg0)) return nullptr;' minargs = sum(1 for p in func_ast.params if not p.default_value) if nargs: yield I+'PyObject* a[%d]%s;' % (nargs, '' if minargs == nargs else '{}') yield I+'const char* names[] = {' for p in func_ast.params: yield I+I+I+'"%s",' % p.name.native yield I+I+I+'nullptr' yield I+'};' yield I+('if (!PyArg_ParseTupleAndKeywords(args, kw, "%s:%s", ' 'const_cast<char**>(names), %s)) ' 'return nullptr;' % ('O'*nargs if minargs == nargs else 'O'*minargs+'|'+'O'*(nargs-minargs), pyname, ', '.join('&a[%d]'%i for i in range(nargs)))) if minargs < nargs and not xouts: yield I+'int nargs; // Find how many args actually passed in.' yield I+'for (nargs = %d; nargs > %d; --nargs) {' % (nargs, minargs) yield I+I+'if (a[nargs-1] != nullptr) break;' yield I+'}' # Convert input parameters from Python. for i, p in enumerate(func_ast.params): n = i+1 arg = 'arg%d' % n check_nullptr, out = _CreateInputParameter( pyname+' line %d' % lineno, p, arg, params) yield I+out return_arg_err = ( 'return ArgError("{func_name}", names[{i}], "{ctype}", a[{i}]);' ).format(i=i, func_name=pyname, ctype=astutils.Type(p)) cvt = ('if (!Clif_PyObjAs(a[{i}], &{cvar}{postconv})) {return_arg_err}' ).format(i=i, cvar=arg, return_arg_err=return_arg_err, # Add post conversion parameter for std::function. postconv='' if p.type.cpp_type else ', {%s}' % ', '.join( postconv.Initializer(t.type, typepostconversion) for t in p.type.callable.params)) def YieldCheckNullptr(ii): # pylint: disable=cell-var-from-loop if check_nullptr: yield ii+'if (%s == nullptr) {' % arg yield ii+I+return_arg_err yield ii+'}' if i < minargs: # Non-default parameter. yield I+cvt for s in YieldCheckNullptr(I): yield s else: if xouts: _I = '' # pylint: disable=invalid-name else: _I = I # pylint: disable=invalid-name yield I+'if (nargs > %d) {' % i # Check if we're passed kw args, skipping some default C++ args. # In this case we must substitute missed default args with default_value if (p.default_value == 'default' # Matcher could not find the default. or 'inf' in p.default_value): # W/A for b/29437257 if xouts: raise ValueError("Can't supply the default for C++ function" ' argument. Drop =default in def %s(%s).' % (pyname, p.name.native)) if n < nargs: if p.type.cpp_type.startswith('::std::unique_ptr'): yield I+I+'if (!a[%d]) { /* default-constructed smartptr */ }' % i yield I+I+'else '+cvt else: yield I+I+('if (!a[{i}]) return DefaultArgMissedError(' '"{}", names[{i}]);'.format(pyname, i=i)) yield I+I+cvt else: yield I+I+cvt for s in YieldCheckNullptr(I+I): yield s elif (p.default_value and params[-1].startswith('&') and p.type.cpp_raw_pointer): # Special case for a pointer to an integral type param (like int*). raise ValueError('A default for integral type pointer argument is ' ' not supported. Drop =default in def %s(%s).' % (pyname, p.name.native)) else: # C-cast takes care of the case where |arg| is an enum value, while # the matcher would return an integral literal. Using static_cast # would be ideal, but its argument should be an expression, which a # struct value like {1, 2, 3} is not. yield _I+I+'if (!a[%d]) %s = (%s)%s;' % (i, arg, astutils.Type(p), p.default_value) yield _I+I+'else '+cvt for s in YieldCheckNullptr(_I+I): yield s if not xouts: yield I+'}' # Create input parameters for extra return values. for n, p in enumerate(func_ast.returns): if n or void_return_type: yield I+'%s ret%d{};' % (astutils.Type(p), n) params.append('&ret%d' % n) yield I+'// Call actual C++ method.' if isinstance(call, list): for s in call[:-1]: yield I+s call = call[-1] if not func_ast.py_keep_gil: if nargs: yield I+'Py_INCREF(args);' yield I+'Py_XINCREF(kw);' yield I+'PyThreadState* _save;' yield I+'Py_UNBLOCK_THREADS' optional_ret0 = False convert_ref_to_ptr = False if (minargs < nargs or catch) and not void_return_type: if catch and return_type.rstrip().endswith('&'): convert_ref_to_ptr = True idx = return_type.rindex('&') return_type = return_type[:idx] + '*' if func_ast.returns[0].type.cpp_has_def_ctor: yield I+return_type+' ret0;' else: # Using optional<> requires T be have T(x) and T::op=(x) available. # While we need only t=x, implementing it will be a pain we skip for now. yield I+'::absl::optional<%s> ret0;' % return_type optional_ret0 = True if catch: for s in _GenExceptionTry(): yield s if minargs < nargs and not xouts: if not void_return_type: call = 'ret0 = '+call yield I+'switch (nargs) {' for n in range(minargs, nargs+1): yield I+'case %d:' % n if func_ast.is_extend_method and func_ast.constructor: call_with_params = call % (func_ast.name.cpp_name, astutils.TupleStr(params[:n])) else: num_params = n # extended methods need to include `self` as the first parameter, but # extended constructors do not. if func_ast.is_extend_method: num_params += 1 call_with_params = call + astutils.TupleStr(params[:num_params]) yield I+I+'%s; break;' % call_with_params yield I+'}' else: if func_ast.is_extend_method and func_ast.constructor: call = call % (func_ast.name.cpp_name, astutils.TupleStr(params)) else: call += astutils.TupleStr(params) _I = I if catch else '' # pylint: disable=invalid-name if void_return_type: yield _I+I+call+';' elif catch: if convert_ref_to_ptr: yield _I+I+'ret0 = &'+call+';' else: yield _I+I+'ret0 = '+call+';' else: yield _I+I+return_type+' ret0 = '+call+';' if catch: for s in _GenExceptionCatch(): yield s if postcall_init: if void_return_type: yield I+postcall_init else: yield I+'ret0'+postcall_init if not func_ast.py_keep_gil: yield I+'Py_BLOCK_THREADS' if nargs: yield I+'Py_DECREF(args);' yield I+'Py_XDECREF(kw);' if catch: for s in _GenExceptionRaise(): yield s if func_ast.postproc == '->self': func_ast.postproc = '' return_self = True assert nret == 0, '-> self must have no other output parameters' else: return_self = False ret = '*ret' if convert_ref_to_ptr else 'ret' # If ctxmgr, force return self on enter, None on exit. if nret > 1 or (func_ast.postproc or ctxmgr) and nret: yield I+'// Convert return values to Python.' yield I+'PyObject* p, * result_tuple = PyTuple_New(%d);' % nret yield I+'if (result_tuple == nullptr) return nullptr;' for i in range(nret): yield I+'if ((p=Clif_PyObjFrom(std::move(%s%d), %s)) == nullptr) {' % ( ret, i, postconv.Initializer( func_ast.returns[i].type, typepostconversion, marked_non_raising=func_ast.marked_non_raising)) yield I+I+'Py_DECREF(result_tuple);' yield I+I+'return nullptr;' yield I+'}' yield I+'PyTuple_SET_ITEM(result_tuple, %d, p);' % i if func_ast.postproc: yield I+'PyObject* pyproc = ImportFQName("%s");' % func_ast.postproc yield I+'if (pyproc == nullptr) {' yield I+I+'Py_DECREF(result_tuple);' yield I+I+'return nullptr;' yield I+'}' yield I+'p = PyObject_CallObject(pyproc, result_tuple);' yield I+'Py_DECREF(pyproc);' yield I+'Py_CLEAR(result_tuple);' if ctxmgr: yield I+'if (p == nullptr) return nullptr;' yield I+'Py_DECREF(p); // Not needed by the context manager.' else: yield I+'result_tuple = p;' if ctxmgr == '__enter__@': yield I+'Py_XDECREF(result_tuple);' yield I+'Py_INCREF(self);' yield I+'return self;' elif ctxmgr == '__exit__@': yield I+'Py_XDECREF(result_tuple);' yield I+'Py_RETURN_NONE;' else: yield I+'return result_tuple;' elif nret: yield I+'return Clif_PyObjFrom(std::move(%s0%s), %s);' % ( ret, ('.value()' if optional_ret0 else ''), postconv.Initializer( func_ast.returns[0].type, typepostconversion, marked_non_raising=func_ast.marked_non_raising)) elif return_self or ctxmgr == '__enter__@': yield I+'Py_INCREF(self);' yield I+'return self;' else: yield I+'Py_RETURN_NONE;' yield '}'
[ "def", "FunctionCall", "(", "pyname", ",", "wrapper", ",", "doc", ",", "catch", ",", "call", ",", "postcall_init", ",", "typepostconversion", ",", "func_ast", ",", "lineno", ",", "prepend_self", "=", "None", ")", ":", "ctxmgr", "=", "pyname", ".", "endswith", "(", "'@'", ")", "if", "ctxmgr", ":", "ctxmgr", "=", "pyname", "assert", "ctxmgr", "in", "(", "'__enter__@'", ",", "'__exit__@'", ")", ",", "(", "'Invalid context manager name '", "+", "pyname", ")", "pyname", "=", "pyname", ".", "rstrip", "(", "'@'", ")", "nret", "=", "len", "(", "func_ast", ".", "returns", ")", "return_type", "=", "astutils", ".", "FuncReturnType", "(", "func_ast", ")", "# Can't use cpp_exact_type.", "# return_type mangled to FQN and drop &, sadly it also drop const.", "void_return_type", "=", "'void'", "==", "return_type", "# Has extra func parameters for output values.", "xouts", "=", "nret", ">", "(", "0", "if", "void_return_type", "else", "1", ")", "params", "=", "[", "]", "# C++ parameter names.", "nargs", "=", "len", "(", "func_ast", ".", "params", ")", "is_ternaryfunc_slot", "=", "pyname", "==", "'__call__'", "yield", "''", "if", "func_ast", ".", "classmethod", ":", "yield", "'// @classmethod '", "+", "doc", "arg0", "=", "'cls'", "# Extra protection that generated code does not use 'self'.", "else", ":", "yield", "'// '", "+", "doc", "arg0", "=", "'self'", "needs_kw", "=", "nargs", "or", "is_ternaryfunc_slot", "yield", "'static PyObject* %s(PyObject* %s%s) {'", "%", "(", "wrapper", ",", "arg0", ",", "', PyObject* args, PyObject* kw'", "if", "needs_kw", "else", "''", ")", "if", "is_ternaryfunc_slot", "and", "not", "nargs", ":", "yield", "I", "+", "(", "'if (!ensure_no_args_and_kw_args(\"%s\", args, kw)) return nullptr;'", "%", "pyname", ")", "if", "prepend_self", ":", "unused_check_nullptr", ",", "out", "=", "_CreateInputParameter", "(", "pyname", "+", "' line %d'", "%", "lineno", ",", "prepend_self", ",", "'arg0'", ",", "params", ")", "yield", "I", "+", "out", "yield", "I", "+", "'if (!Clif_PyObjAs(self, &arg0)) return nullptr;'", "minargs", "=", "sum", "(", "1", "for", "p", "in", "func_ast", ".", "params", "if", "not", "p", ".", "default_value", ")", "if", "nargs", ":", "yield", "I", "+", "'PyObject* a[%d]%s;'", "%", "(", "nargs", ",", "''", "if", "minargs", "==", "nargs", "else", "'{}'", ")", "yield", "I", "+", "'const char* names[] = {'", "for", "p", "in", "func_ast", ".", "params", ":", "yield", "I", "+", "I", "+", "I", "+", "'\"%s\",'", "%", "p", ".", "name", ".", "native", "yield", "I", "+", "I", "+", "I", "+", "'nullptr'", "yield", "I", "+", "'};'", "yield", "I", "+", "(", "'if (!PyArg_ParseTupleAndKeywords(args, kw, \"%s:%s\", '", "'const_cast<char**>(names), %s)) '", "'return nullptr;'", "%", "(", "'O'", "*", "nargs", "if", "minargs", "==", "nargs", "else", "'O'", "*", "minargs", "+", "'|'", "+", "'O'", "*", "(", "nargs", "-", "minargs", ")", ",", "pyname", ",", "', '", ".", "join", "(", "'&a[%d]'", "%", "i", "for", "i", "in", "range", "(", "nargs", ")", ")", ")", ")", "if", "minargs", "<", "nargs", "and", "not", "xouts", ":", "yield", "I", "+", "'int nargs; // Find how many args actually passed in.'", "yield", "I", "+", "'for (nargs = %d; nargs > %d; --nargs) {'", "%", "(", "nargs", ",", "minargs", ")", "yield", "I", "+", "I", "+", "'if (a[nargs-1] != nullptr) break;'", "yield", "I", "+", "'}'", "# Convert input parameters from Python.", "for", "i", ",", "p", "in", "enumerate", "(", "func_ast", ".", "params", ")", ":", "n", "=", "i", "+", "1", "arg", "=", "'arg%d'", "%", "n", "check_nullptr", ",", "out", "=", "_CreateInputParameter", "(", "pyname", "+", "' line %d'", "%", "lineno", ",", "p", ",", "arg", ",", "params", ")", "yield", "I", "+", "out", "return_arg_err", "=", "(", "'return ArgError(\"{func_name}\", names[{i}], \"{ctype}\", a[{i}]);'", ")", ".", "format", "(", "i", "=", "i", ",", "func_name", "=", "pyname", ",", "ctype", "=", "astutils", ".", "Type", "(", "p", ")", ")", "cvt", "=", "(", "'if (!Clif_PyObjAs(a[{i}], &{cvar}{postconv})) {return_arg_err}'", ")", ".", "format", "(", "i", "=", "i", ",", "cvar", "=", "arg", ",", "return_arg_err", "=", "return_arg_err", ",", "# Add post conversion parameter for std::function.", "postconv", "=", "''", "if", "p", ".", "type", ".", "cpp_type", "else", "', {%s}'", "%", "', '", ".", "join", "(", "postconv", ".", "Initializer", "(", "t", ".", "type", ",", "typepostconversion", ")", "for", "t", "in", "p", ".", "type", ".", "callable", ".", "params", ")", ")", "def", "YieldCheckNullptr", "(", "ii", ")", ":", "# pylint: disable=cell-var-from-loop", "if", "check_nullptr", ":", "yield", "ii", "+", "'if (%s == nullptr) {'", "%", "arg", "yield", "ii", "+", "I", "+", "return_arg_err", "yield", "ii", "+", "'}'", "if", "i", "<", "minargs", ":", "# Non-default parameter.", "yield", "I", "+", "cvt", "for", "s", "in", "YieldCheckNullptr", "(", "I", ")", ":", "yield", "s", "else", ":", "if", "xouts", ":", "_I", "=", "''", "# pylint: disable=invalid-name", "else", ":", "_I", "=", "I", "# pylint: disable=invalid-name", "yield", "I", "+", "'if (nargs > %d) {'", "%", "i", "# Check if we're passed kw args, skipping some default C++ args.", "# In this case we must substitute missed default args with default_value", "if", "(", "p", ".", "default_value", "==", "'default'", "# Matcher could not find the default.", "or", "'inf'", "in", "p", ".", "default_value", ")", ":", "# W/A for b/29437257", "if", "xouts", ":", "raise", "ValueError", "(", "\"Can't supply the default for C++ function\"", "' argument. Drop =default in def %s(%s).'", "%", "(", "pyname", ",", "p", ".", "name", ".", "native", ")", ")", "if", "n", "<", "nargs", ":", "if", "p", ".", "type", ".", "cpp_type", ".", "startswith", "(", "'::std::unique_ptr'", ")", ":", "yield", "I", "+", "I", "+", "'if (!a[%d]) { /* default-constructed smartptr */ }'", "%", "i", "yield", "I", "+", "I", "+", "'else '", "+", "cvt", "else", ":", "yield", "I", "+", "I", "+", "(", "'if (!a[{i}]) return DefaultArgMissedError('", "'\"{}\", names[{i}]);'", ".", "format", "(", "pyname", ",", "i", "=", "i", ")", ")", "yield", "I", "+", "I", "+", "cvt", "else", ":", "yield", "I", "+", "I", "+", "cvt", "for", "s", "in", "YieldCheckNullptr", "(", "I", "+", "I", ")", ":", "yield", "s", "elif", "(", "p", ".", "default_value", "and", "params", "[", "-", "1", "]", ".", "startswith", "(", "'&'", ")", "and", "p", ".", "type", ".", "cpp_raw_pointer", ")", ":", "# Special case for a pointer to an integral type param (like int*).", "raise", "ValueError", "(", "'A default for integral type pointer argument is '", "' not supported. Drop =default in def %s(%s).'", "%", "(", "pyname", ",", "p", ".", "name", ".", "native", ")", ")", "else", ":", "# C-cast takes care of the case where |arg| is an enum value, while", "# the matcher would return an integral literal. Using static_cast", "# would be ideal, but its argument should be an expression, which a", "# struct value like {1, 2, 3} is not.", "yield", "_I", "+", "I", "+", "'if (!a[%d]) %s = (%s)%s;'", "%", "(", "i", ",", "arg", ",", "astutils", ".", "Type", "(", "p", ")", ",", "p", ".", "default_value", ")", "yield", "_I", "+", "I", "+", "'else '", "+", "cvt", "for", "s", "in", "YieldCheckNullptr", "(", "_I", "+", "I", ")", ":", "yield", "s", "if", "not", "xouts", ":", "yield", "I", "+", "'}'", "# Create input parameters for extra return values.", "for", "n", ",", "p", "in", "enumerate", "(", "func_ast", ".", "returns", ")", ":", "if", "n", "or", "void_return_type", ":", "yield", "I", "+", "'%s ret%d{};'", "%", "(", "astutils", ".", "Type", "(", "p", ")", ",", "n", ")", "params", ".", "append", "(", "'&ret%d'", "%", "n", ")", "yield", "I", "+", "'// Call actual C++ method.'", "if", "isinstance", "(", "call", ",", "list", ")", ":", "for", "s", "in", "call", "[", ":", "-", "1", "]", ":", "yield", "I", "+", "s", "call", "=", "call", "[", "-", "1", "]", "if", "not", "func_ast", ".", "py_keep_gil", ":", "if", "nargs", ":", "yield", "I", "+", "'Py_INCREF(args);'", "yield", "I", "+", "'Py_XINCREF(kw);'", "yield", "I", "+", "'PyThreadState* _save;'", "yield", "I", "+", "'Py_UNBLOCK_THREADS'", "optional_ret0", "=", "False", "convert_ref_to_ptr", "=", "False", "if", "(", "minargs", "<", "nargs", "or", "catch", ")", "and", "not", "void_return_type", ":", "if", "catch", "and", "return_type", ".", "rstrip", "(", ")", ".", "endswith", "(", "'&'", ")", ":", "convert_ref_to_ptr", "=", "True", "idx", "=", "return_type", ".", "rindex", "(", "'&'", ")", "return_type", "=", "return_type", "[", ":", "idx", "]", "+", "'*'", "if", "func_ast", ".", "returns", "[", "0", "]", ".", "type", ".", "cpp_has_def_ctor", ":", "yield", "I", "+", "return_type", "+", "' ret0;'", "else", ":", "# Using optional<> requires T be have T(x) and T::op=(x) available.", "# While we need only t=x, implementing it will be a pain we skip for now.", "yield", "I", "+", "'::absl::optional<%s> ret0;'", "%", "return_type", "optional_ret0", "=", "True", "if", "catch", ":", "for", "s", "in", "_GenExceptionTry", "(", ")", ":", "yield", "s", "if", "minargs", "<", "nargs", "and", "not", "xouts", ":", "if", "not", "void_return_type", ":", "call", "=", "'ret0 = '", "+", "call", "yield", "I", "+", "'switch (nargs) {'", "for", "n", "in", "range", "(", "minargs", ",", "nargs", "+", "1", ")", ":", "yield", "I", "+", "'case %d:'", "%", "n", "if", "func_ast", ".", "is_extend_method", "and", "func_ast", ".", "constructor", ":", "call_with_params", "=", "call", "%", "(", "func_ast", ".", "name", ".", "cpp_name", ",", "astutils", ".", "TupleStr", "(", "params", "[", ":", "n", "]", ")", ")", "else", ":", "num_params", "=", "n", "# extended methods need to include `self` as the first parameter, but", "# extended constructors do not.", "if", "func_ast", ".", "is_extend_method", ":", "num_params", "+=", "1", "call_with_params", "=", "call", "+", "astutils", ".", "TupleStr", "(", "params", "[", ":", "num_params", "]", ")", "yield", "I", "+", "I", "+", "'%s; break;'", "%", "call_with_params", "yield", "I", "+", "'}'", "else", ":", "if", "func_ast", ".", "is_extend_method", "and", "func_ast", ".", "constructor", ":", "call", "=", "call", "%", "(", "func_ast", ".", "name", ".", "cpp_name", ",", "astutils", ".", "TupleStr", "(", "params", ")", ")", "else", ":", "call", "+=", "astutils", ".", "TupleStr", "(", "params", ")", "_I", "=", "I", "if", "catch", "else", "''", "# pylint: disable=invalid-name", "if", "void_return_type", ":", "yield", "_I", "+", "I", "+", "call", "+", "';'", "elif", "catch", ":", "if", "convert_ref_to_ptr", ":", "yield", "_I", "+", "I", "+", "'ret0 = &'", "+", "call", "+", "';'", "else", ":", "yield", "_I", "+", "I", "+", "'ret0 = '", "+", "call", "+", "';'", "else", ":", "yield", "_I", "+", "I", "+", "return_type", "+", "' ret0 = '", "+", "call", "+", "';'", "if", "catch", ":", "for", "s", "in", "_GenExceptionCatch", "(", ")", ":", "yield", "s", "if", "postcall_init", ":", "if", "void_return_type", ":", "yield", "I", "+", "postcall_init", "else", ":", "yield", "I", "+", "'ret0'", "+", "postcall_init", "if", "not", "func_ast", ".", "py_keep_gil", ":", "yield", "I", "+", "'Py_BLOCK_THREADS'", "if", "nargs", ":", "yield", "I", "+", "'Py_DECREF(args);'", "yield", "I", "+", "'Py_XDECREF(kw);'", "if", "catch", ":", "for", "s", "in", "_GenExceptionRaise", "(", ")", ":", "yield", "s", "if", "func_ast", ".", "postproc", "==", "'->self'", ":", "func_ast", ".", "postproc", "=", "''", "return_self", "=", "True", "assert", "nret", "==", "0", ",", "'-> self must have no other output parameters'", "else", ":", "return_self", "=", "False", "ret", "=", "'*ret'", "if", "convert_ref_to_ptr", "else", "'ret'", "# If ctxmgr, force return self on enter, None on exit.", "if", "nret", ">", "1", "or", "(", "func_ast", ".", "postproc", "or", "ctxmgr", ")", "and", "nret", ":", "yield", "I", "+", "'// Convert return values to Python.'", "yield", "I", "+", "'PyObject* p, * result_tuple = PyTuple_New(%d);'", "%", "nret", "yield", "I", "+", "'if (result_tuple == nullptr) return nullptr;'", "for", "i", "in", "range", "(", "nret", ")", ":", "yield", "I", "+", "'if ((p=Clif_PyObjFrom(std::move(%s%d), %s)) == nullptr) {'", "%", "(", "ret", ",", "i", ",", "postconv", ".", "Initializer", "(", "func_ast", ".", "returns", "[", "i", "]", ".", "type", ",", "typepostconversion", ",", "marked_non_raising", "=", "func_ast", ".", "marked_non_raising", ")", ")", "yield", "I", "+", "I", "+", "'Py_DECREF(result_tuple);'", "yield", "I", "+", "I", "+", "'return nullptr;'", "yield", "I", "+", "'}'", "yield", "I", "+", "'PyTuple_SET_ITEM(result_tuple, %d, p);'", "%", "i", "if", "func_ast", ".", "postproc", ":", "yield", "I", "+", "'PyObject* pyproc = ImportFQName(\"%s\");'", "%", "func_ast", ".", "postproc", "yield", "I", "+", "'if (pyproc == nullptr) {'", "yield", "I", "+", "I", "+", "'Py_DECREF(result_tuple);'", "yield", "I", "+", "I", "+", "'return nullptr;'", "yield", "I", "+", "'}'", "yield", "I", "+", "'p = PyObject_CallObject(pyproc, result_tuple);'", "yield", "I", "+", "'Py_DECREF(pyproc);'", "yield", "I", "+", "'Py_CLEAR(result_tuple);'", "if", "ctxmgr", ":", "yield", "I", "+", "'if (p == nullptr) return nullptr;'", "yield", "I", "+", "'Py_DECREF(p); // Not needed by the context manager.'", "else", ":", "yield", "I", "+", "'result_tuple = p;'", "if", "ctxmgr", "==", "'__enter__@'", ":", "yield", "I", "+", "'Py_XDECREF(result_tuple);'", "yield", "I", "+", "'Py_INCREF(self);'", "yield", "I", "+", "'return self;'", "elif", "ctxmgr", "==", "'__exit__@'", ":", "yield", "I", "+", "'Py_XDECREF(result_tuple);'", "yield", "I", "+", "'Py_RETURN_NONE;'", "else", ":", "yield", "I", "+", "'return result_tuple;'", "elif", "nret", ":", "yield", "I", "+", "'return Clif_PyObjFrom(std::move(%s0%s), %s);'", "%", "(", "ret", ",", "(", "'.value()'", "if", "optional_ret0", "else", "''", ")", ",", "postconv", ".", "Initializer", "(", "func_ast", ".", "returns", "[", "0", "]", ".", "type", ",", "typepostconversion", ",", "marked_non_raising", "=", "func_ast", ".", "marked_non_raising", ")", ")", "elif", "return_self", "or", "ctxmgr", "==", "'__enter__@'", ":", "yield", "I", "+", "'Py_INCREF(self);'", "yield", "I", "+", "'return self;'", "else", ":", "yield", "I", "+", "'Py_RETURN_NONE;'", "yield", "'}'" ]
https://github.com/google/clif/blob/cab24d6a105609a65c95a36a1712ae3c20c7b5df/clif/python/gen.py#L605-L890
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/function_deserialization.py
python
recreate_function
(saved_function, concrete_functions)
return tf_decorator.make_decorator( restored_function_body, restored_function, decorator_argspec=function_spec.fullargspec)
Creates a `Function` from a `SavedFunction`. Args: saved_function: `SavedFunction` proto. concrete_functions: map from function name to `ConcreteFunction`. Returns: A `Function`.
Creates a `Function` from a `SavedFunction`.
[ "Creates", "a", "Function", "from", "a", "SavedFunction", "." ]
def recreate_function(saved_function, concrete_functions): """Creates a `Function` from a `SavedFunction`. Args: saved_function: `SavedFunction` proto. concrete_functions: map from function name to `ConcreteFunction`. Returns: A `Function`. """ # TODO(andresp): Construct a `Function` with the cache populated # instead of creating a new `Function` backed by a Python layer to # glue things together. Current approach is nesting functions deeper for each # serialization cycle. coder = nested_structure_coder.StructureCoder() # Note: handling method functions is tricky since make_decorator does not # allows control of "ismethod". Additionally since restored functions do # not behave as methods i.e. they always use the same captured tensors # independent of the object they are bound to, there is little value on # propagating that correctly. # # Ideally this conversion should happen at serialization time. But since # there are SavedModels which have "ismethod" populated and have an extra # argument that they expect to be ignored, we do it at deserialization. function_spec = _deserialize_function_spec_as_nonmethod( saved_function.function_spec, coder) def restored_function_body(*args, **kwargs): """Calls a restored function.""" # This is the format of function.graph.structured_input_signature. At this # point, the args and kwargs have already been canonicalized. inputs = (args, kwargs) # First try to find a concrete function that can be called without input # conversions. This allows one to pick a more specific trace in case there # was also a more expensive one that supported tensors. for allow_conversion in [False, True]: for function_name in saved_function.concrete_functions: function = concrete_functions[function_name] if _concrete_function_callable_with(function, inputs, allow_conversion): return _call_concrete_function(function, inputs) signature_descriptions = [] def _pretty_format_positional(positional): return "Positional arguments ({} total):\n * {}".format( len(positional), "\n * ".join([str(a) for a in positional])) for index, function_name in enumerate(saved_function.concrete_functions): concrete_function = concrete_functions[function_name] positional, keyword = concrete_function.structured_input_signature signature_descriptions.append( "Option {}:\n {}\n Keyword arguments: {}" .format(index + 1, _pretty_format_positional(positional), keyword)) raise ValueError( "Could not find matching function to call loaded from the SavedModel. " "Got:\n {}\n Keyword arguments: {}\n\nExpected " "these arguments to match one of the following {} option(s):\n\n{}" .format(_pretty_format_positional(args), kwargs, len(saved_function.concrete_functions), "\n\n".join(signature_descriptions))) concrete_function_objects = [] for concrete_function_name in saved_function.concrete_functions: concrete_function_objects.append(concrete_functions[concrete_function_name]) restored_function = RestoredFunction( restored_function_body, restored_function_body.__name__, function_spec, concrete_function_objects) return tf_decorator.make_decorator( restored_function_body, restored_function, decorator_argspec=function_spec.fullargspec)
[ "def", "recreate_function", "(", "saved_function", ",", "concrete_functions", ")", ":", "# TODO(andresp): Construct a `Function` with the cache populated", "# instead of creating a new `Function` backed by a Python layer to", "# glue things together. Current approach is nesting functions deeper for each", "# serialization cycle.", "coder", "=", "nested_structure_coder", ".", "StructureCoder", "(", ")", "# Note: handling method functions is tricky since make_decorator does not", "# allows control of \"ismethod\". Additionally since restored functions do", "# not behave as methods i.e. they always use the same captured tensors", "# independent of the object they are bound to, there is little value on", "# propagating that correctly.", "#", "# Ideally this conversion should happen at serialization time. But since", "# there are SavedModels which have \"ismethod\" populated and have an extra", "# argument that they expect to be ignored, we do it at deserialization.", "function_spec", "=", "_deserialize_function_spec_as_nonmethod", "(", "saved_function", ".", "function_spec", ",", "coder", ")", "def", "restored_function_body", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Calls a restored function.\"\"\"", "# This is the format of function.graph.structured_input_signature. At this", "# point, the args and kwargs have already been canonicalized.", "inputs", "=", "(", "args", ",", "kwargs", ")", "# First try to find a concrete function that can be called without input", "# conversions. This allows one to pick a more specific trace in case there", "# was also a more expensive one that supported tensors.", "for", "allow_conversion", "in", "[", "False", ",", "True", "]", ":", "for", "function_name", "in", "saved_function", ".", "concrete_functions", ":", "function", "=", "concrete_functions", "[", "function_name", "]", "if", "_concrete_function_callable_with", "(", "function", ",", "inputs", ",", "allow_conversion", ")", ":", "return", "_call_concrete_function", "(", "function", ",", "inputs", ")", "signature_descriptions", "=", "[", "]", "def", "_pretty_format_positional", "(", "positional", ")", ":", "return", "\"Positional arguments ({} total):\\n * {}\"", ".", "format", "(", "len", "(", "positional", ")", ",", "\"\\n * \"", ".", "join", "(", "[", "str", "(", "a", ")", "for", "a", "in", "positional", "]", ")", ")", "for", "index", ",", "function_name", "in", "enumerate", "(", "saved_function", ".", "concrete_functions", ")", ":", "concrete_function", "=", "concrete_functions", "[", "function_name", "]", "positional", ",", "keyword", "=", "concrete_function", ".", "structured_input_signature", "signature_descriptions", ".", "append", "(", "\"Option {}:\\n {}\\n Keyword arguments: {}\"", ".", "format", "(", "index", "+", "1", ",", "_pretty_format_positional", "(", "positional", ")", ",", "keyword", ")", ")", "raise", "ValueError", "(", "\"Could not find matching function to call loaded from the SavedModel. \"", "\"Got:\\n {}\\n Keyword arguments: {}\\n\\nExpected \"", "\"these arguments to match one of the following {} option(s):\\n\\n{}\"", ".", "format", "(", "_pretty_format_positional", "(", "args", ")", ",", "kwargs", ",", "len", "(", "saved_function", ".", "concrete_functions", ")", ",", "\"\\n\\n\"", ".", "join", "(", "signature_descriptions", ")", ")", ")", "concrete_function_objects", "=", "[", "]", "for", "concrete_function_name", "in", "saved_function", ".", "concrete_functions", ":", "concrete_function_objects", ".", "append", "(", "concrete_functions", "[", "concrete_function_name", "]", ")", "restored_function", "=", "RestoredFunction", "(", "restored_function_body", ",", "restored_function_body", ".", "__name__", ",", "function_spec", ",", "concrete_function_objects", ")", "return", "tf_decorator", ".", "make_decorator", "(", "restored_function_body", ",", "restored_function", ",", "decorator_argspec", "=", "function_spec", ".", "fullargspec", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/function_deserialization.py#L198-L277
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Sizer.RecalcSizes
(*args, **kwargs)
return _core_.Sizer_RecalcSizes(*args, **kwargs)
RecalcSizes(self) Using the sizes calculated by `CalcMin` reposition and resize all the items managed by this sizer. You should not need to call this directly as it is called by `Layout`.
RecalcSizes(self)
[ "RecalcSizes", "(", "self", ")" ]
def RecalcSizes(*args, **kwargs): """ RecalcSizes(self) Using the sizes calculated by `CalcMin` reposition and resize all the items managed by this sizer. You should not need to call this directly as it is called by `Layout`. """ return _core_.Sizer_RecalcSizes(*args, **kwargs)
[ "def", "RecalcSizes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Sizer_RecalcSizes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L14815-L14823
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xpathContext.xpathRegisteredNsCleanup
(self)
Cleanup the XPath context data associated to registered variables
Cleanup the XPath context data associated to registered variables
[ "Cleanup", "the", "XPath", "context", "data", "associated", "to", "registered", "variables" ]
def xpathRegisteredNsCleanup(self): """Cleanup the XPath context data associated to registered variables """ libxml2mod.xmlXPathRegisteredNsCleanup(self._o)
[ "def", "xpathRegisteredNsCleanup", "(", "self", ")", ":", "libxml2mod", ".", "xmlXPathRegisteredNsCleanup", "(", "self", ".", "_o", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L6595-L6598
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/common/Layer.py
python
Layer.get_param
(self, *keys)
return Param(None, None)
Given a key, this will return the address of the child corresponding to it If multiple keys are given, it will return the key found first
Given a key, this will return the address of the child corresponding to it If multiple keys are given, it will return the key found first
[ "Given", "a", "key", "this", "will", "return", "the", "address", "of", "the", "child", "corresponding", "to", "it", "If", "multiple", "keys", "are", "given", "it", "will", "return", "the", "key", "found", "first" ]
def get_param(self, *keys): """ Given a key, this will return the address of the child corresponding to it If multiple keys are given, it will return the key found first """ for key in keys: if key in self.params.keys(): return self.params[key] return Param(None, None)
[ "def", "get_param", "(", "self", ",", "*", "keys", ")", ":", "for", "key", "in", "keys", ":", "if", "key", "in", "self", ".", "params", ".", "keys", "(", ")", ":", "return", "self", ".", "params", "[", "key", "]", "return", "Param", "(", "None", ",", "None", ")" ]
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Layer.py#L83-L92
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/reductions/complex2real/atom_canonicalizers/matrix_canon.py
python
lambda_sum_largest_canon
(expr, real_args, imag_args, real2imag)
return real, imag
Canonicalize nuclear norm with Hermitian matrix input.
Canonicalize nuclear norm with Hermitian matrix input.
[ "Canonicalize", "nuclear", "norm", "with", "Hermitian", "matrix", "input", "." ]
def lambda_sum_largest_canon(expr, real_args, imag_args, real2imag): """Canonicalize nuclear norm with Hermitian matrix input. """ # Divide by two because each eigenvalue is repeated twice. real, imag = hermitian_canon(expr, real_args, imag_args, real2imag) real.k *= 2 if imag_args[0] is not None: real /= 2 return real, imag
[ "def", "lambda_sum_largest_canon", "(", "expr", ",", "real_args", ",", "imag_args", ",", "real2imag", ")", ":", "# Divide by two because each eigenvalue is repeated twice.", "real", ",", "imag", "=", "hermitian_canon", "(", "expr", ",", "real_args", ",", "imag_args", ",", "real2imag", ")", "real", ".", "k", "*=", "2", "if", "imag_args", "[", "0", "]", "is", "not", "None", ":", "real", "/=", "2", "return", "real", ",", "imag" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/reductions/complex2real/atom_canonicalizers/matrix_canon.py#L52-L60
wang-bin/QtAV
3b937991afce248648836ae811324d4051b31def
python/configure.py
python
_TargetConfiguration.get_qt_configuration
(self, opts)
Get the Qt configuration that can be extracted from qmake. opts are the command line options.
Get the Qt configuration that can be extracted from qmake. opts are the command line options.
[ "Get", "the", "Qt", "configuration", "that", "can", "be", "extracted", "from", "qmake", ".", "opts", "are", "the", "command", "line", "options", "." ]
def get_qt_configuration(self, opts): """ Get the Qt configuration that can be extracted from qmake. opts are the command line options. """ # Query qmake. qt_config = _TargetQtConfiguration(self.qmake) self.qt_version_str = getattr(qt_config, 'QT_VERSION', '') self.qt_version = version_from_string(self.qt_version_str) if self.qt_version is None: error("Unable to determine the version of Qt.") # On Windows for Qt versions prior to v5.9.0 we need to be explicit # about the qmake spec. if self.qt_version < 0x050900 and self.py_platform == 'win32': if self.py_version >= 0x030500: self.qmake_spec = 'win32-msvc2015' elif self.py_version >= 0x030300: self.qmake_spec = 'win32-msvc2010' elif self.py_version >= 0x020600: self.qmake_spec = 'win32-msvc2008' elif self.py_version >= 0x020400: self.qmake_spec = 'win32-msvc.net' else: self.qmake_spec = 'win32-msvc' else: # Otherwise use the default. self.qmake_spec = '' # The binary MacOS/X Qt installer used to default to XCode. If so then # use macx-clang (Qt v5) or macx-g++ (Qt v4). if sys.platform == 'darwin': try: # Qt v5. if qt_config.QMAKE_SPEC == 'macx-xcode': # This will exist (and we can't check anyway). self.qmake_spec = 'macx-clang' else: # No need to explicitly name the default. self.qmake_spec = '' except AttributeError: # Qt v4. self.qmake_spec = 'macx-g++' self.api_dir = os.path.join(qt_config.QT_INSTALL_DATA, 'qsci') self.qt_inc_dir = qt_config.QT_INSTALL_HEADERS self.qt_lib_dir = qt_config.QT_INSTALL_LIBS if self.sysroot == '': self.sysroot = getattr(qt_config, 'QT_SYSROOT', '')
[ "def", "get_qt_configuration", "(", "self", ",", "opts", ")", ":", "# Query qmake.", "qt_config", "=", "_TargetQtConfiguration", "(", "self", ".", "qmake", ")", "self", ".", "qt_version_str", "=", "getattr", "(", "qt_config", ",", "'QT_VERSION'", ",", "''", ")", "self", ".", "qt_version", "=", "version_from_string", "(", "self", ".", "qt_version_str", ")", "if", "self", ".", "qt_version", "is", "None", ":", "error", "(", "\"Unable to determine the version of Qt.\"", ")", "# On Windows for Qt versions prior to v5.9.0 we need to be explicit", "# about the qmake spec.", "if", "self", ".", "qt_version", "<", "0x050900", "and", "self", ".", "py_platform", "==", "'win32'", ":", "if", "self", ".", "py_version", ">=", "0x030500", ":", "self", ".", "qmake_spec", "=", "'win32-msvc2015'", "elif", "self", ".", "py_version", ">=", "0x030300", ":", "self", ".", "qmake_spec", "=", "'win32-msvc2010'", "elif", "self", ".", "py_version", ">=", "0x020600", ":", "self", ".", "qmake_spec", "=", "'win32-msvc2008'", "elif", "self", ".", "py_version", ">=", "0x020400", ":", "self", ".", "qmake_spec", "=", "'win32-msvc.net'", "else", ":", "self", ".", "qmake_spec", "=", "'win32-msvc'", "else", ":", "# Otherwise use the default.", "self", ".", "qmake_spec", "=", "''", "# The binary MacOS/X Qt installer used to default to XCode. If so then", "# use macx-clang (Qt v5) or macx-g++ (Qt v4).", "if", "sys", ".", "platform", "==", "'darwin'", ":", "try", ":", "# Qt v5.", "if", "qt_config", ".", "QMAKE_SPEC", "==", "'macx-xcode'", ":", "# This will exist (and we can't check anyway).", "self", ".", "qmake_spec", "=", "'macx-clang'", "else", ":", "# No need to explicitly name the default.", "self", ".", "qmake_spec", "=", "''", "except", "AttributeError", ":", "# Qt v4.", "self", ".", "qmake_spec", "=", "'macx-g++'", "self", ".", "api_dir", "=", "os", ".", "path", ".", "join", "(", "qt_config", ".", "QT_INSTALL_DATA", ",", "'qsci'", ")", "self", ".", "qt_inc_dir", "=", "qt_config", ".", "QT_INSTALL_HEADERS", "self", ".", "qt_lib_dir", "=", "qt_config", ".", "QT_INSTALL_LIBS", "if", "self", ".", "sysroot", "==", "''", ":", "self", ".", "sysroot", "=", "getattr", "(", "qt_config", ",", "'QT_SYSROOT'", ",", "''", ")" ]
https://github.com/wang-bin/QtAV/blob/3b937991afce248648836ae811324d4051b31def/python/configure.py#L958-L1008
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/psutil/psutil/_psbsd.py
python
Process.get_process_uids
(self)
return nt_uids(real, effective, saved)
Return real, effective and saved user ids.
Return real, effective and saved user ids.
[ "Return", "real", "effective", "and", "saved", "user", "ids", "." ]
def get_process_uids(self): """Return real, effective and saved user ids.""" real, effective, saved = _psutil_bsd.get_process_uids(self.pid) return nt_uids(real, effective, saved)
[ "def", "get_process_uids", "(", "self", ")", ":", "real", ",", "effective", ",", "saved", "=", "_psutil_bsd", ".", "get_process_uids", "(", "self", ".", "pid", ")", "return", "nt_uids", "(", "real", ",", "effective", ",", "saved", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/psutil/psutil/_psbsd.py#L235-L238
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/plan/rigidobjectcspace.py
python
RigidObjectCSpace.__init__
(self,rigidObject,collider=None,translationDomain=None,rotationDomain=None)
Args: rigidObject (RigidObjectModel): the object that should move. collider (:class:`WorldCollider`, optional): a collider instance containing the world in which the object lives. Any ignored collisions will be respected in the feasibility test. translationDomain (list of pairs, optional): a bounding box in which the translation should be sampled. If None (default), the improper logarithmic prior is used to sample translations. rotationDomain (pair, optional): If provided, must be a (rotation0,rdomain) pair specifying a range in which the rotation should be sampled. rotation0 must be an SO3 element. rdomain may be: * A number: rotation is sampled with absolute angular error from rotation0 in the range [0,rdomain]. * A triple: rotation is sampled with euler angles with roll in the range [-rdomain[0],rdomain[0]], pitch in the range [-rdomain[1],rdomain[1]], and yaw in the range [-rdomain[2],rdomain[2]]. The sampled rotation is then multiplied by rotation0.
Args: rigidObject (RigidObjectModel): the object that should move. collider (:class:`WorldCollider`, optional): a collider instance containing the world in which the object lives. Any ignored collisions will be respected in the feasibility test. translationDomain (list of pairs, optional): a bounding box in which the translation should be sampled. If None (default), the improper logarithmic prior is used to sample translations. rotationDomain (pair, optional): If provided, must be a (rotation0,rdomain) pair specifying a range in which the rotation should be sampled. rotation0 must be an SO3 element. rdomain may be:
[ "Args", ":", "rigidObject", "(", "RigidObjectModel", ")", ":", "the", "object", "that", "should", "move", ".", "collider", "(", ":", "class", ":", "WorldCollider", "optional", ")", ":", "a", "collider", "instance", "containing", "the", "world", "in", "which", "the", "object", "lives", ".", "Any", "ignored", "collisions", "will", "be", "respected", "in", "the", "feasibility", "test", ".", "translationDomain", "(", "list", "of", "pairs", "optional", ")", ":", "a", "bounding", "box", "in", "which", "the", "translation", "should", "be", "sampled", ".", "If", "None", "(", "default", ")", "the", "improper", "logarithmic", "prior", "is", "used", "to", "sample", "translations", ".", "rotationDomain", "(", "pair", "optional", ")", ":", "If", "provided", "must", "be", "a", "(", "rotation0", "rdomain", ")", "pair", "specifying", "a", "range", "in", "which", "the", "rotation", "should", "be", "sampled", ".", "rotation0", "must", "be", "an", "SO3", "element", ".", "rdomain", "may", "be", ":" ]
def __init__(self,rigidObject,collider=None,translationDomain=None,rotationDomain=None): """ Args: rigidObject (RigidObjectModel): the object that should move. collider (:class:`WorldCollider`, optional): a collider instance containing the world in which the object lives. Any ignored collisions will be respected in the feasibility test. translationDomain (list of pairs, optional): a bounding box in which the translation should be sampled. If None (default), the improper logarithmic prior is used to sample translations. rotationDomain (pair, optional): If provided, must be a (rotation0,rdomain) pair specifying a range in which the rotation should be sampled. rotation0 must be an SO3 element. rdomain may be: * A number: rotation is sampled with absolute angular error from rotation0 in the range [0,rdomain]. * A triple: rotation is sampled with euler angles with roll in the range [-rdomain[0],rdomain[0]], pitch in the range [-rdomain[1],rdomain[1]], and yaw in the range [-rdomain[2],rdomain[2]]. The sampled rotation is then multiplied by rotation0. """ CSpace.__init__(self) self.rigidObject = rigidObject if translationDomain is None: translationDomain = [(-float('inf'),float('inf'))]*3 self.bound = translationDomain + [(-math.pi,math.pi)]*3 self.rotationDomain = rotationDomain self.collider = collider self.rotationWeight = 1.0/math.pi if collider: def robCollide(r): return any(True for _ in self.collider.robotObjectCollisions(r,self.rigidObject.index)) def objCollide(o): return any(True for _ in self.collider.objectObjectCollisions(self.rigidObject.index,o)) def terrCollide(o): return any(True for _ in self.collider.objectTerrainCollisions(self.rigidObject.index,o)) self.addFeasibilityTest(self.setConfig,"setconfig") for o in range(self.collider.world.numRobots()): self.addFeasibilityTest((lambda x,o=o: not robCollide(o)),"robot collision "+str(o)+" "+self.collider.world.robot(o).getName(),dependencies="setconfig") for o in range(self.collider.world.numRigidObjects()): if o != self.rigidObject.index: self.addFeasibilityTest((lambda x,o=o: not objCollide(o)),"obj collision "+str(o)+" "+self.collider.world.rigidObject(o).getName(),dependencies="setconfig") for o in range(self.collider.world.numTerrains()): self.addFeasibilityTest((lambda x,o=o: not terrCollide(o)),"terrain collision "+str(o)+" "+self.collider.world.terrain(o).getName(),dependencies="setconfig") else: self.addFeasibilityTest(self.setConfig,"setconfig") self.properties['geodesic'] = 1
[ "def", "__init__", "(", "self", ",", "rigidObject", ",", "collider", "=", "None", ",", "translationDomain", "=", "None", ",", "rotationDomain", "=", "None", ")", ":", "CSpace", ".", "__init__", "(", "self", ")", "self", ".", "rigidObject", "=", "rigidObject", "if", "translationDomain", "is", "None", ":", "translationDomain", "=", "[", "(", "-", "float", "(", "'inf'", ")", ",", "float", "(", "'inf'", ")", ")", "]", "*", "3", "self", ".", "bound", "=", "translationDomain", "+", "[", "(", "-", "math", ".", "pi", ",", "math", ".", "pi", ")", "]", "*", "3", "self", ".", "rotationDomain", "=", "rotationDomain", "self", ".", "collider", "=", "collider", "self", ".", "rotationWeight", "=", "1.0", "/", "math", ".", "pi", "if", "collider", ":", "def", "robCollide", "(", "r", ")", ":", "return", "any", "(", "True", "for", "_", "in", "self", ".", "collider", ".", "robotObjectCollisions", "(", "r", ",", "self", ".", "rigidObject", ".", "index", ")", ")", "def", "objCollide", "(", "o", ")", ":", "return", "any", "(", "True", "for", "_", "in", "self", ".", "collider", ".", "objectObjectCollisions", "(", "self", ".", "rigidObject", ".", "index", ",", "o", ")", ")", "def", "terrCollide", "(", "o", ")", ":", "return", "any", "(", "True", "for", "_", "in", "self", ".", "collider", ".", "objectTerrainCollisions", "(", "self", ".", "rigidObject", ".", "index", ",", "o", ")", ")", "self", ".", "addFeasibilityTest", "(", "self", ".", "setConfig", ",", "\"setconfig\"", ")", "for", "o", "in", "range", "(", "self", ".", "collider", ".", "world", ".", "numRobots", "(", ")", ")", ":", "self", ".", "addFeasibilityTest", "(", "(", "lambda", "x", ",", "o", "=", "o", ":", "not", "robCollide", "(", "o", ")", ")", ",", "\"robot collision \"", "+", "str", "(", "o", ")", "+", "\" \"", "+", "self", ".", "collider", ".", "world", ".", "robot", "(", "o", ")", ".", "getName", "(", ")", ",", "dependencies", "=", "\"setconfig\"", ")", "for", "o", "in", "range", "(", "self", ".", "collider", ".", "world", ".", "numRigidObjects", "(", ")", ")", ":", "if", "o", "!=", "self", ".", "rigidObject", ".", "index", ":", "self", ".", "addFeasibilityTest", "(", "(", "lambda", "x", ",", "o", "=", "o", ":", "not", "objCollide", "(", "o", ")", ")", ",", "\"obj collision \"", "+", "str", "(", "o", ")", "+", "\" \"", "+", "self", ".", "collider", ".", "world", ".", "rigidObject", "(", "o", ")", ".", "getName", "(", ")", ",", "dependencies", "=", "\"setconfig\"", ")", "for", "o", "in", "range", "(", "self", ".", "collider", ".", "world", ".", "numTerrains", "(", ")", ")", ":", "self", ".", "addFeasibilityTest", "(", "(", "lambda", "x", ",", "o", "=", "o", ":", "not", "terrCollide", "(", "o", ")", ")", ",", "\"terrain collision \"", "+", "str", "(", "o", ")", "+", "\" \"", "+", "self", ".", "collider", ".", "world", ".", "terrain", "(", "o", ")", ".", "getName", "(", ")", ",", "dependencies", "=", "\"setconfig\"", ")", "else", ":", "self", ".", "addFeasibilityTest", "(", "self", ".", "setConfig", ",", "\"setconfig\"", ")", "self", ".", "properties", "[", "'geodesic'", "]", "=", "1" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/plan/rigidobjectcspace.py#L21-L71
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
lldb/utils/lui/lldbutil.py
python
run_break_set_by_regexp
( test, regexp, extra_options=None, num_expected_locations=-1)
return get_bpno_from_match(break_results)
Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line.
Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line.
[ "Set", "a", "breakpoint", "by", "regular", "expression", "match", "on", "symbol", "name", ".", "Common", "options", "are", "the", "same", "as", "run_break_set_by_file_and_line", "." ]
def run_break_set_by_regexp( test, regexp, extra_options=None, num_expected_locations=-1): """Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line.""" command = 'breakpoint set -r "%s"' % (regexp) if extra_options: command += " " + extra_options break_results = run_break_set_command(test, command) check_breakpoint_result( test, break_results, num_locations=num_expected_locations) return get_bpno_from_match(break_results)
[ "def", "run_break_set_by_regexp", "(", "test", ",", "regexp", ",", "extra_options", "=", "None", ",", "num_expected_locations", "=", "-", "1", ")", ":", "command", "=", "'breakpoint set -r \"%s\"'", "%", "(", "regexp", ")", "if", "extra_options", ":", "command", "+=", "\" \"", "+", "extra_options", "break_results", "=", "run_break_set_command", "(", "test", ",", "command", ")", "check_breakpoint_result", "(", "test", ",", "break_results", ",", "num_locations", "=", "num_expected_locations", ")", "return", "get_bpno_from_match", "(", "break_results", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/utils/lui/lldbutil.py#L438-L456
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/signal/python/ops/mel_ops.py
python
_validate_arguments
(num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, upper_edge_hertz, dtype)
Checks the inputs to linear_to_mel_weight_matrix.
Checks the inputs to linear_to_mel_weight_matrix.
[ "Checks", "the", "inputs", "to", "linear_to_mel_weight_matrix", "." ]
def _validate_arguments(num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, upper_edge_hertz, dtype): """Checks the inputs to linear_to_mel_weight_matrix.""" if num_mel_bins <= 0: raise ValueError('num_mel_bins must be positive. Got: %s' % num_mel_bins) if num_spectrogram_bins <= 0: raise ValueError('num_spectrogram_bins must be positive. Got: %s' % num_spectrogram_bins) if sample_rate <= 0.0: raise ValueError('sample_rate must be positive. Got: %s' % sample_rate) if lower_edge_hertz < 0.0: raise ValueError('lower_edge_hertz must be non-negative. Got: %s' % lower_edge_hertz) if lower_edge_hertz >= upper_edge_hertz: raise ValueError('lower_edge_hertz %.1f >= upper_edge_hertz %.1f' % (lower_edge_hertz, upper_edge_hertz)) if not dtype.is_floating: raise ValueError('dtype must be a floating point type. Got: %s' % dtype)
[ "def", "_validate_arguments", "(", "num_mel_bins", ",", "num_spectrogram_bins", ",", "sample_rate", ",", "lower_edge_hertz", ",", "upper_edge_hertz", ",", "dtype", ")", ":", "if", "num_mel_bins", "<=", "0", ":", "raise", "ValueError", "(", "'num_mel_bins must be positive. Got: %s'", "%", "num_mel_bins", ")", "if", "num_spectrogram_bins", "<=", "0", ":", "raise", "ValueError", "(", "'num_spectrogram_bins must be positive. Got: %s'", "%", "num_spectrogram_bins", ")", "if", "sample_rate", "<=", "0.0", ":", "raise", "ValueError", "(", "'sample_rate must be positive. Got: %s'", "%", "sample_rate", ")", "if", "lower_edge_hertz", "<", "0.0", ":", "raise", "ValueError", "(", "'lower_edge_hertz must be non-negative. Got: %s'", "%", "lower_edge_hertz", ")", "if", "lower_edge_hertz", ">=", "upper_edge_hertz", ":", "raise", "ValueError", "(", "'lower_edge_hertz %.1f >= upper_edge_hertz %.1f'", "%", "(", "lower_edge_hertz", ",", "upper_edge_hertz", ")", ")", "if", "not", "dtype", ".", "is_floating", ":", "raise", "ValueError", "(", "'dtype must be a floating point type. Got: %s'", "%", "dtype", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/signal/python/ops/mel_ops.py#L67-L84
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/six.py
python
add_move
(move)
Add an item to six.moves.
Add an item to six.moves.
[ "Add", "an", "item", "to", "six", ".", "moves", "." ]
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
[ "def", "add_move", "(", "move", ")", ":", "setattr", "(", "_MovedItems", ",", "move", ".", "name", ",", "move", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/six.py#L470-L472
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/tclib.py
python
BaseMessage.GetContent
(self)
return self.parts
Returns the parts of the message. You may modify parts if you wish. Note that you must not call GetId() on this object until you have finished modifying the contents.
Returns the parts of the message. You may modify parts if you wish. Note that you must not call GetId() on this object until you have finished modifying the contents.
[ "Returns", "the", "parts", "of", "the", "message", ".", "You", "may", "modify", "parts", "if", "you", "wish", ".", "Note", "that", "you", "must", "not", "call", "GetId", "()", "on", "this", "object", "until", "you", "have", "finished", "modifying", "the", "contents", "." ]
def GetContent(self): '''Returns the parts of the message. You may modify parts if you wish. Note that you must not call GetId() on this object until you have finished modifying the contents. ''' self.dirty = True # user might modify content return self.parts
[ "def", "GetContent", "(", "self", ")", ":", "self", ".", "dirty", "=", "True", "# user might modify content", "return", "self", ".", "parts" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/tclib.py#L125-L131
google/iree
1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76
integrations/tensorflow/python_projects/iree_tf/iree/tf/support/trace_utils.py
python
ModuleCall.get_tolerances
(self)
return self.rtol, self.atol
Gets the floating point tolerances associated with this call.
Gets the floating point tolerances associated with this call.
[ "Gets", "the", "floating", "point", "tolerances", "associated", "with", "this", "call", "." ]
def get_tolerances(self) -> Tuple[float, float]: """Gets the floating point tolerances associated with this call.""" return self.rtol, self.atol
[ "def", "get_tolerances", "(", "self", ")", "->", "Tuple", "[", "float", ",", "float", "]", ":", "return", "self", ".", "rtol", ",", "self", ".", "atol" ]
https://github.com/google/iree/blob/1224bbdbe65b0d1fdf40e7324f60f68beeaf7c76/integrations/tensorflow/python_projects/iree_tf/iree/tf/support/trace_utils.py#L72-L74
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py
python
RegistryInfo.windows_kits_roots
(self)
return r'Windows Kits\Installed Roots'
Microsoft Windows Kits Roots registry key.
Microsoft Windows Kits Roots registry key.
[ "Microsoft", "Windows", "Kits", "Roots", "registry", "key", "." ]
def windows_kits_roots(self): """ Microsoft Windows Kits Roots registry key. """ return r'Windows Kits\Installed Roots'
[ "def", "windows_kits_roots", "(", "self", ")", ":", "return", "r'Windows Kits\\Installed Roots'" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/msvc.py#L406-L410
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/ffmpeg/ffmpeg_ops.py
python
_decode_audio_shape
(op)
return [tensor_shape.TensorShape([None, channels])]
Computes the shape of a DecodeAudio operation. Args: op: A DecodeAudio operation. Returns: A list of output shapes. There's exactly one output, the sampled audio. This is a rank 2 tensor with an unknown number of samples and a known number of channels.
Computes the shape of a DecodeAudio operation.
[ "Computes", "the", "shape", "of", "a", "DecodeAudio", "operation", "." ]
def _decode_audio_shape(op): """Computes the shape of a DecodeAudio operation. Args: op: A DecodeAudio operation. Returns: A list of output shapes. There's exactly one output, the sampled audio. This is a rank 2 tensor with an unknown number of samples and a known number of channels. """ try: channels = op.get_attr('channel_count') except ValueError: channels = None return [tensor_shape.TensorShape([None, channels])]
[ "def", "_decode_audio_shape", "(", "op", ")", ":", "try", ":", "channels", "=", "op", ".", "get_attr", "(", "'channel_count'", ")", "except", "ValueError", ":", "channels", "=", "None", "return", "[", "tensor_shape", ".", "TensorShape", "(", "[", "None", ",", "channels", "]", ")", "]" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/ffmpeg/ffmpeg_ops.py#L32-L47
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/agents/baseline_controller/leg_controller.py
python
LegController.get_action
(self)
Gets the control signal e.g. torques/positions for the leg.
Gets the control signal e.g. torques/positions for the leg.
[ "Gets", "the", "control", "signal", "e", ".", "g", ".", "torques", "/", "positions", "for", "the", "leg", "." ]
def get_action(self) -> Any: """Gets the control signal e.g. torques/positions for the leg.""" pass
[ "def", "get_action", "(", "self", ")", "->", "Any", ":", "pass" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/agents/baseline_controller/leg_controller.py#L27-L29
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
llvm/utils/lint/common_lint.py
python
VerifyTrailingWhitespace
(filename, lines)
return lint
Checks to make sure the file has no lines with trailing whitespace. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found.
Checks to make sure the file has no lines with trailing whitespace.
[ "Checks", "to", "make", "sure", "the", "file", "has", "no", "lines", "with", "trailing", "whitespace", "." ]
def VerifyTrailingWhitespace(filename, lines): """Checks to make sure the file has no lines with trailing whitespace. Args: filename: the file under consideration as string lines: contents of the file as string array Returns: A list of tuples with format [(filename, line number, msg), ...] with any violations found. """ lint = [] trailing_whitespace_re = re.compile(r'\s+$') line_num = 1 for line in lines: if trailing_whitespace_re.match(line.rstrip('\n')): lint.append((filename, line_num, 'Trailing whitespace')) line_num += 1 return lint
[ "def", "VerifyTrailingWhitespace", "(", "filename", ",", "lines", ")", ":", "lint", "=", "[", "]", "trailing_whitespace_re", "=", "re", ".", "compile", "(", "r'\\s+$'", ")", "line_num", "=", "1", "for", "line", "in", "lines", ":", "if", "trailing_whitespace_re", ".", "match", "(", "line", ".", "rstrip", "(", "'\\n'", ")", ")", ":", "lint", ".", "append", "(", "(", "filename", ",", "line_num", ",", "'Trailing whitespace'", ")", ")", "line_num", "+=", "1", "return", "lint" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/llvm/utils/lint/common_lint.py#L52-L70
commaai/openpilot
4416c21b1e738ab7d04147c5ae52b5135e0cdb40
pyextra/acados_template/acados_ocp.py
python
AcadosOcpOptions.hessian_approx
(self)
return self.__hessian_approx
Hessian approximation. String in ('GAUSS_NEWTON', 'EXACT'). Default: 'GAUSS_NEWTON'.
Hessian approximation. String in ('GAUSS_NEWTON', 'EXACT'). Default: 'GAUSS_NEWTON'.
[ "Hessian", "approximation", ".", "String", "in", "(", "GAUSS_NEWTON", "EXACT", ")", ".", "Default", ":", "GAUSS_NEWTON", "." ]
def hessian_approx(self): """Hessian approximation. String in ('GAUSS_NEWTON', 'EXACT'). Default: 'GAUSS_NEWTON'. """ return self.__hessian_approx
[ "def", "hessian_approx", "(", "self", ")", ":", "return", "self", ".", "__hessian_approx" ]
https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L2165-L2170
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__getslice__
(self, start, stop)
return self._values[start:stop]
Retrieves the subset of items from between the specified indices.
Retrieves the subset of items from between the specified indices.
[ "Retrieves", "the", "subset", "of", "items", "from", "between", "the", "specified", "indices", "." ]
def __getslice__(self, start, stop): """Retrieves the subset of items from between the specified indices.""" return self._values[start:stop]
[ "def", "__getslice__", "(", "self", ",", "start", ",", "stop", ")", ":", "return", "self", ".", "_values", "[", "start", ":", "stop", "]" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/containers.py#L153-L155
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
PanedWindow.remove
(self, child)
Remove the pane containing child from the panedwindow All geometry management options for child will be forgotten.
Remove the pane containing child from the panedwindow
[ "Remove", "the", "pane", "containing", "child", "from", "the", "panedwindow" ]
def remove(self, child): """Remove the pane containing child from the panedwindow All geometry management options for child will be forgotten. """ self.tk.call(self._w, 'forget', child)
[ "def", "remove", "(", "self", ",", "child", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'forget'", ",", "child", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3825-L3830
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/data_flow_ops.py
python
Barrier.barrier_ref
(self)
return self._barrier_ref
Get the underlying barrier reference.
Get the underlying barrier reference.
[ "Get", "the", "underlying", "barrier", "reference", "." ]
def barrier_ref(self): """Get the underlying barrier reference.""" return self._barrier_ref
[ "def", "barrier_ref", "(", "self", ")", ":", "return", "self", ".", "_barrier_ref" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L922-L924
ukoethe/vigra
093d57d15c8c237adf1704d96daa6393158ce299
vigranumpy/lib/arraytypes.py
python
ImagePyramid.__getitem__
(self, level)
return list.__getitem__(self, level - self.lowestLevel)
Get the image at 'level'. Raises IndexError when the level does not exist.
Get the image at 'level'. Raises IndexError when the level does not exist.
[ "Get", "the", "image", "at", "level", ".", "Raises", "IndexError", "when", "the", "level", "does", "not", "exist", "." ]
def __getitem__(self, level): '''Get the image at 'level'. Raises IndexError when the level does not exist. ''' if level < self.lowestLevel or level > self.highestLevel: raise IndexError("ImagePyramid[level]: level out of range.") return list.__getitem__(self, level - self.lowestLevel)
[ "def", "__getitem__", "(", "self", ",", "level", ")", ":", "if", "level", "<", "self", ".", "lowestLevel", "or", "level", ">", "self", ".", "highestLevel", ":", "raise", "IndexError", "(", "\"ImagePyramid[level]: level out of range.\"", ")", "return", "list", ".", "__getitem__", "(", "self", ",", "level", "-", "self", ".", "lowestLevel", ")" ]
https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/arraytypes.py#L2003-L2009
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py
python
categorical_column_with_vocabulary_file
(key, vocabulary_file, vocabulary_size=None, num_oov_buckets=0, default_value=None, dtype=dtypes.string)
return categorical_column_with_vocabulary_file_v2( key, vocabulary_file, vocabulary_size, dtype, default_value, num_oov_buckets)
A `CategoricalColumn` with a vocabulary file. Use this when your inputs are in string or integer format, and you have a vocabulary file that maps each value to an integer ID. By default, out-of-vocabulary values are ignored. Use either (but not both) of `num_oov_buckets` and `default_value` to specify how to include out-of-vocabulary values. For input dictionary `features`, `features[key]` is either `Tensor` or `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int and `''` for string, which will be dropped by this feature column. Example with `num_oov_buckets`: File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state abbreviation. All inputs with values in that file are assigned an ID 0-49, corresponding to its line number. All other values are hashed and assigned an ID 50-54. ```python states = categorical_column_with_vocabulary_file( key='states', vocabulary_file='/us/states.txt', vocabulary_size=50, num_oov_buckets=5) columns = [states, ...] features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) linear_prediction = linear_model(features, columns) ``` Example with `default_value`: File '/us/states.txt' contains 51 lines - the first line is 'XX', and the other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX' in input, and other values missing from the file, will be assigned ID 0. All others are assigned the corresponding line number 1-50. ```python states = categorical_column_with_vocabulary_file( key='states', vocabulary_file='/us/states.txt', vocabulary_size=51, default_value=0) columns = [states, ...] features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) linear_prediction, _, _ = linear_model(features, columns) ``` And to make an embedding with either: ```python columns = [embedding_column(states, 3),...] features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) dense_tensor = input_layer(features, columns) ``` Args: key: A unique string identifying the input feature. It is used as the column name and the dictionary key for feature parsing configs, feature `Tensor` objects, and feature columns. vocabulary_file: The vocabulary file name. vocabulary_size: Number of the elements in the vocabulary. This must be no greater than length of `vocabulary_file`, if less than length, later values are ignored. If None, it is set to the length of `vocabulary_file`. num_oov_buckets: Non-negative integer, the number of out-of-vocabulary buckets. All out-of-vocabulary inputs will be assigned IDs in the range `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of the input value. A positive `num_oov_buckets` can not be specified with `default_value`. default_value: The integer ID value to return for out-of-vocabulary feature values, defaults to `-1`. This can not be specified with a positive `num_oov_buckets`. dtype: The type of features. Only string and integer types are supported. Returns: A `CategoricalColumn` with a vocabulary file. Raises: ValueError: `vocabulary_file` is missing or cannot be opened. ValueError: `vocabulary_size` is missing or < 1. ValueError: `num_oov_buckets` is a negative integer. ValueError: `num_oov_buckets` and `default_value` are both specified. ValueError: `dtype` is neither string nor integer.
A `CategoricalColumn` with a vocabulary file.
[ "A", "CategoricalColumn", "with", "a", "vocabulary", "file", "." ]
def categorical_column_with_vocabulary_file(key, vocabulary_file, vocabulary_size=None, num_oov_buckets=0, default_value=None, dtype=dtypes.string): """A `CategoricalColumn` with a vocabulary file. Use this when your inputs are in string or integer format, and you have a vocabulary file that maps each value to an integer ID. By default, out-of-vocabulary values are ignored. Use either (but not both) of `num_oov_buckets` and `default_value` to specify how to include out-of-vocabulary values. For input dictionary `features`, `features[key]` is either `Tensor` or `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int and `''` for string, which will be dropped by this feature column. Example with `num_oov_buckets`: File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state abbreviation. All inputs with values in that file are assigned an ID 0-49, corresponding to its line number. All other values are hashed and assigned an ID 50-54. ```python states = categorical_column_with_vocabulary_file( key='states', vocabulary_file='/us/states.txt', vocabulary_size=50, num_oov_buckets=5) columns = [states, ...] features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) linear_prediction = linear_model(features, columns) ``` Example with `default_value`: File '/us/states.txt' contains 51 lines - the first line is 'XX', and the other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX' in input, and other values missing from the file, will be assigned ID 0. All others are assigned the corresponding line number 1-50. ```python states = categorical_column_with_vocabulary_file( key='states', vocabulary_file='/us/states.txt', vocabulary_size=51, default_value=0) columns = [states, ...] features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) linear_prediction, _, _ = linear_model(features, columns) ``` And to make an embedding with either: ```python columns = [embedding_column(states, 3),...] features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) dense_tensor = input_layer(features, columns) ``` Args: key: A unique string identifying the input feature. It is used as the column name and the dictionary key for feature parsing configs, feature `Tensor` objects, and feature columns. vocabulary_file: The vocabulary file name. vocabulary_size: Number of the elements in the vocabulary. This must be no greater than length of `vocabulary_file`, if less than length, later values are ignored. If None, it is set to the length of `vocabulary_file`. num_oov_buckets: Non-negative integer, the number of out-of-vocabulary buckets. All out-of-vocabulary inputs will be assigned IDs in the range `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of the input value. A positive `num_oov_buckets` can not be specified with `default_value`. default_value: The integer ID value to return for out-of-vocabulary feature values, defaults to `-1`. This can not be specified with a positive `num_oov_buckets`. dtype: The type of features. Only string and integer types are supported. Returns: A `CategoricalColumn` with a vocabulary file. Raises: ValueError: `vocabulary_file` is missing or cannot be opened. ValueError: `vocabulary_size` is missing or < 1. ValueError: `num_oov_buckets` is a negative integer. ValueError: `num_oov_buckets` and `default_value` are both specified. ValueError: `dtype` is neither string nor integer. """ return categorical_column_with_vocabulary_file_v2( key, vocabulary_file, vocabulary_size, dtype, default_value, num_oov_buckets)
[ "def", "categorical_column_with_vocabulary_file", "(", "key", ",", "vocabulary_file", ",", "vocabulary_size", "=", "None", ",", "num_oov_buckets", "=", "0", ",", "default_value", "=", "None", ",", "dtype", "=", "dtypes", ".", "string", ")", ":", "return", "categorical_column_with_vocabulary_file_v2", "(", "key", ",", "vocabulary_file", ",", "vocabulary_size", ",", "dtype", ",", "default_value", ",", "num_oov_buckets", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L1475-L1562
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/vendored/six.py
python
with_metaclass
(meta, *bases)
return type.__new__(metaclass, 'temporary_class', (), {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "meta", ")", ":", "def", "__new__", "(", "cls", ",", "name", ",", "this_bases", ",", "d", ")", ":", "return", "meta", "(", "name", ",", "bases", ",", "d", ")", "return", "type", ".", "__new__", "(", "metaclass", ",", "'temporary_class'", ",", "(", ")", ",", "{", "}", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/vendored/six.py#L800-L809
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/io/stata.py
python
StataReader.value_labels
(self)
return self.value_label_dict
Returns a dict, associating each variable name a dict, associating each value its corresponding label
Returns a dict, associating each variable name a dict, associating each value its corresponding label
[ "Returns", "a", "dict", "associating", "each", "variable", "name", "a", "dict", "associating", "each", "value", "its", "corresponding", "label" ]
def value_labels(self): """Returns a dict, associating each variable name a dict, associating each value its corresponding label """ if not self._value_labels_read: self._read_value_labels() return self.value_label_dict
[ "def", "value_labels", "(", "self", ")", ":", "if", "not", "self", ".", "_value_labels_read", ":", "self", ".", "_read_value_labels", "(", ")", "return", "self", ".", "value_label_dict" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/io/stata.py#L1738-L1745
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/madpack.py
python
_get_relative_maddir
(maddir, port)
Return a relative path version of maddir GPDB installations have a symlink outside of GPHOME that links to the current GPHOME. After a DB upgrade, this symlink is updated to the new GPHOME. 'maddir_lib', which uses the absolute path of GPHOME, is hardcoded into each madlib function definition. Replacing the GPHOME path with the equivalent relative path makes it simpler to perform DB upgrades without breaking MADlib.
Return a relative path version of maddir
[ "Return", "a", "relative", "path", "version", "of", "maddir" ]
def _get_relative_maddir(maddir, port): """ Return a relative path version of maddir GPDB installations have a symlink outside of GPHOME that links to the current GPHOME. After a DB upgrade, this symlink is updated to the new GPHOME. 'maddir_lib', which uses the absolute path of GPHOME, is hardcoded into each madlib function definition. Replacing the GPHOME path with the equivalent relative path makes it simpler to perform DB upgrades without breaking MADlib. """ if port == 'postgres': # do nothing for postgres return maddir # e.g. maddir_lib = $GPHOME/madlib/Versions/1.9/lib/libmadlib.so # 'madlib' is supposed to be in this path, which is the default folder # used by GPPKG to install madlib try: abs_gphome, tail = maddir.split('madlib/') except ValueError: return maddir # Check outside $GPHOME if there is a symlink to this absolute path # os.pardir is equivalent to .. # os.path.normpath removes the extraneous .. from that path rel_gphome = os.path.normpath(os.path.join(abs_gphome, os.pardir, 'greenplum-db')) if (os.path.islink(rel_gphome) and os.path.realpath(rel_gphome) == os.path.realpath(abs_gphome)): # if the relative link exists and is pointing to current location return os.path.join(rel_gphome, 'madlib', tail) else: return maddir
[ "def", "_get_relative_maddir", "(", "maddir", ",", "port", ")", ":", "if", "port", "==", "'postgres'", ":", "# do nothing for postgres", "return", "maddir", "# e.g. maddir_lib = $GPHOME/madlib/Versions/1.9/lib/libmadlib.so", "# 'madlib' is supposed to be in this path, which is the default folder", "# used by GPPKG to install madlib", "try", ":", "abs_gphome", ",", "tail", "=", "maddir", ".", "split", "(", "'madlib/'", ")", "except", "ValueError", ":", "return", "maddir", "# Check outside $GPHOME if there is a symlink to this absolute path", "# os.pardir is equivalent to ..", "# os.path.normpath removes the extraneous .. from that path", "rel_gphome", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "abs_gphome", ",", "os", ".", "pardir", ",", "'greenplum-db'", ")", ")", "if", "(", "os", ".", "path", ".", "islink", "(", "rel_gphome", ")", "and", "os", ".", "path", ".", "realpath", "(", "rel_gphome", ")", "==", "os", ".", "path", ".", "realpath", "(", "abs_gphome", ")", ")", ":", "# if the relative link exists and is pointing to current location", "return", "os", ".", "path", ".", "join", "(", "rel_gphome", ",", "'madlib'", ",", "tail", ")", "else", ":", "return", "maddir" ]
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/madpack.py#L102-L134
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py
python
convert_slice_axis
(node, **kwargs)
return nodes
Map MXNet's slice_axis operator attributes to onnx's Slice operator and return the created node.
Map MXNet's slice_axis operator attributes to onnx's Slice operator and return the created node.
[ "Map", "MXNet", "s", "slice_axis", "operator", "attributes", "to", "onnx", "s", "Slice", "operator", "and", "return", "the", "created", "node", "." ]
def convert_slice_axis(node, **kwargs): """Map MXNet's slice_axis operator attributes to onnx's Slice operator and return the created node. """ from onnx.helper import make_node name, input_nodes, attrs = get_inputs(node, kwargs) axis = int(attrs.get("axis")) begin = int(attrs.get("begin")) end = attrs.get("end", None) nodes = [] create_tensor([axis], name+'_axis', kwargs["initializer"]) create_tensor([begin], name+'_begin', kwargs["initializer"]) if not end or end == 'None': # ONNX doesn't support None for ends. Since ends=None depicts # length of dimension, passing dimension in this case. nodes += [ make_node('Shape', [input_nodes[0]], [name+"_data_shape"]) ] # corner case when end = None and axis = -1 if axis == -1: create_tensor([-1], name+'_-1', kwargs["initializer"]) nodes += [ make_node('Shape', [name+'_data_shape'], [name+'_data_dim']), make_node('Add', [name+'_data_dim', name+'_-1'], [name+'_axis_max']), make_node('Slice', [name+'_data_shape', name+'_axis_max', name+'_data_dim'], [name+'_end']), ] else: create_tensor([axis+1], name+"_axis_plus_1", kwargs["initializer"]) nodes += [ make_node('Slice', [name+'_data_shape', name+'_axis', name+'_axis_plus_1'], [name+"_end"]) ] else: create_tensor([int(end)], name+'_end', kwargs["initializer"]) nodes += [ make_node('Slice', [input_nodes[0], name+'_begin', name+'_end', name+'_axis'], [name], name=name) ] return nodes
[ "def", "convert_slice_axis", "(", "node", ",", "*", "*", "kwargs", ")", ":", "from", "onnx", ".", "helper", "import", "make_node", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "axis", "=", "int", "(", "attrs", ".", "get", "(", "\"axis\"", ")", ")", "begin", "=", "int", "(", "attrs", ".", "get", "(", "\"begin\"", ")", ")", "end", "=", "attrs", ".", "get", "(", "\"end\"", ",", "None", ")", "nodes", "=", "[", "]", "create_tensor", "(", "[", "axis", "]", ",", "name", "+", "'_axis'", ",", "kwargs", "[", "\"initializer\"", "]", ")", "create_tensor", "(", "[", "begin", "]", ",", "name", "+", "'_begin'", ",", "kwargs", "[", "\"initializer\"", "]", ")", "if", "not", "end", "or", "end", "==", "'None'", ":", "# ONNX doesn't support None for ends. Since ends=None depicts", "# length of dimension, passing dimension in this case.", "nodes", "+=", "[", "make_node", "(", "'Shape'", ",", "[", "input_nodes", "[", "0", "]", "]", ",", "[", "name", "+", "\"_data_shape\"", "]", ")", "]", "# corner case when end = None and axis = -1", "if", "axis", "==", "-", "1", ":", "create_tensor", "(", "[", "-", "1", "]", ",", "name", "+", "'_-1'", ",", "kwargs", "[", "\"initializer\"", "]", ")", "nodes", "+=", "[", "make_node", "(", "'Shape'", ",", "[", "name", "+", "'_data_shape'", "]", ",", "[", "name", "+", "'_data_dim'", "]", ")", ",", "make_node", "(", "'Add'", ",", "[", "name", "+", "'_data_dim'", ",", "name", "+", "'_-1'", "]", ",", "[", "name", "+", "'_axis_max'", "]", ")", ",", "make_node", "(", "'Slice'", ",", "[", "name", "+", "'_data_shape'", ",", "name", "+", "'_axis_max'", ",", "name", "+", "'_data_dim'", "]", ",", "[", "name", "+", "'_end'", "]", ")", ",", "]", "else", ":", "create_tensor", "(", "[", "axis", "+", "1", "]", ",", "name", "+", "\"_axis_plus_1\"", ",", "kwargs", "[", "\"initializer\"", "]", ")", "nodes", "+=", "[", "make_node", "(", "'Slice'", ",", "[", "name", "+", "'_data_shape'", ",", "name", "+", "'_axis'", ",", "name", "+", "'_axis_plus_1'", "]", ",", "[", "name", "+", "\"_end\"", "]", ")", "]", "else", ":", "create_tensor", "(", "[", "int", "(", "end", ")", "]", ",", "name", "+", "'_end'", ",", "kwargs", "[", "\"initializer\"", "]", ")", "nodes", "+=", "[", "make_node", "(", "'Slice'", ",", "[", "input_nodes", "[", "0", "]", ",", "name", "+", "'_begin'", ",", "name", "+", "'_end'", ",", "name", "+", "'_axis'", "]", ",", "[", "name", "]", ",", "name", "=", "name", ")", "]", "return", "nodes" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/onnx/mx2onnx/_op_translations/_op_translations_opset12.py#L1995-L2037
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py
python
BufferingHandler.close
(self)
Close the handler. This version just flushes and chains to the parent class' close().
Close the handler.
[ "Close", "the", "handler", "." ]
def close(self): """ Close the handler. This version just flushes and chains to the parent class' close(). """ try: self.flush() finally: logging.Handler.close(self)
[ "def", "close", "(", "self", ")", ":", "try", ":", "self", ".", "flush", "(", ")", "finally", ":", "logging", ".", "Handler", ".", "close", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py#L1249-L1258
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
VolumeGrid.set
(self, *args)
return _robotsim.VolumeGrid_set(self, *args)
set(VolumeGrid self, double value) set(VolumeGrid self, int i, int j, int k, double value)
set(VolumeGrid self, double value) set(VolumeGrid self, int i, int j, int k, double value)
[ "set", "(", "VolumeGrid", "self", "double", "value", ")", "set", "(", "VolumeGrid", "self", "int", "i", "int", "j", "int", "k", "double", "value", ")" ]
def set(self, *args): """ set(VolumeGrid self, double value) set(VolumeGrid self, int i, int j, int k, double value) """ return _robotsim.VolumeGrid_set(self, *args)
[ "def", "set", "(", "self", ",", "*", "args", ")", ":", "return", "_robotsim", ".", "VolumeGrid_set", "(", "self", ",", "*", "args", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L1492-L1500
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py
python
MaxAbsScaler.transform
(self, X)
return X
Scale the data Parameters ---------- X : {array-like, sparse matrix} The data that should be scaled.
Scale the data
[ "Scale", "the", "data" ]
def transform(self, X): """Scale the data Parameters ---------- X : {array-like, sparse matrix} The data that should be scaled. """ check_is_fitted(self) X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, estimator=self, dtype=FLOAT_DTYPES, force_all_finite='allow-nan') if sparse.issparse(X): inplace_column_scale(X, 1.0 / self.scale_) else: X /= self.scale_ return X
[ "def", "transform", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ")", "X", "=", "check_array", "(", "X", ",", "accept_sparse", "=", "(", "'csr'", ",", "'csc'", ")", ",", "copy", "=", "self", ".", "copy", ",", "estimator", "=", "self", ",", "dtype", "=", "FLOAT_DTYPES", ",", "force_all_finite", "=", "'allow-nan'", ")", "if", "sparse", ".", "issparse", "(", "X", ")", ":", "inplace_column_scale", "(", "X", ",", "1.0", "/", "self", ".", "scale_", ")", "else", ":", "X", "/=", "self", ".", "scale_", "return", "X" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/preprocessing/_data.py#L990-L1007
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/CMAC.py
python
CMAC._update
(self, data_block)
Update a block aligned to the block boundary
Update a block aligned to the block boundary
[ "Update", "a", "block", "aligned", "to", "the", "block", "boundary" ]
def _update(self, data_block): """Update a block aligned to the block boundary""" bs = self._block_size assert len(data_block) % bs == 0 if len(data_block) == 0: return ct = self._cbc.encrypt(data_block) if len(data_block) == bs: second_last = self._last_ct else: second_last = ct[-bs*2:-bs] self._last_ct = ct[-bs:] self._last_pt = strxor(second_last, data_block[-bs:])
[ "def", "_update", "(", "self", ",", "data_block", ")", ":", "bs", "=", "self", ".", "_block_size", "assert", "len", "(", "data_block", ")", "%", "bs", "==", "0", "if", "len", "(", "data_block", ")", "==", "0", ":", "return", "ct", "=", "self", ".", "_cbc", ".", "encrypt", "(", "data_block", ")", "if", "len", "(", "data_block", ")", "==", "bs", ":", "second_last", "=", "self", ".", "_last_ct", "else", ":", "second_last", "=", "ct", "[", "-", "bs", "*", "2", ":", "-", "bs", "]", "self", ".", "_last_ct", "=", "ct", "[", "-", "bs", ":", "]", "self", ".", "_last_pt", "=", "strxor", "(", "second_last", ",", "data_block", "[", "-", "bs", ":", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/CMAC.py#L148-L163
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Import/App/config_control_design.py
python
gbsf_check_curve
(cv,)
return FALSE
:param cv :type cv:curve
:param cv :type cv:curve
[ ":", "param", "cv", ":", "type", "cv", ":", "curve" ]
def gbsf_check_curve(cv,): ''' :param cv :type cv:curve ''' if (SIZEOF(['CONFIG_CONTROL_DESIGN.BOUNDED_CURVE','CONFIG_CONTROL_DESIGN.CONIC','CONFIG_CONTROL_DESIGN.CURVE_REPLICA','CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D'] * TYPEOF(cv)) > 1): return FALSE else: if (SIZEOF(['CONFIG_CONTROL_DESIGN.CIRCLE','CONFIG_CONTROL_DESIGN.ELLIPSE'] * TYPEOF(cv)) == 1): return TRUE else: if ((('CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE' == TYPEOF(cv)) and (cv.b_spline_curve.self_intersect == FALSE)) or (cv.b_spline_curve.self_intersect == UNKNOWN)): return TRUE else: if ((('CONFIG_CONTROL_DESIGN.COMPOSITE_CURVE' == TYPEOF(cv)) and (cv.composite_curve.self_intersect == FALSE)) or (cv.composite_curve.self_intersect == UNKNOWN)): return SIZEOF(None) == 0 else: if ('CONFIG_CONTROL_DESIGN.CURVE_REPLICA' == TYPEOF(cv)): return gbsf_check_curve(cv.curve_replica.parent_curve) else: if ((('CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D' == TYPEOF(cv)) and ((cv.offset_curve_3d.self_intersect == FALSE) or (cv.offset_curve_3d.self_intersect == UNKNOWN))) and ( not ('CONFIG_CONTROL_DESIGN.POLYLINE' == TYPEOF(cv.basis_curve)))): return gbsf_check_curve(cv.offset_curve_3d.basis_curve) else: if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(cv)): return gbsf_check_curve(cv.pcurve.reference_to_curve.representation.items[1]) and gbsf_check_surface(cv.pcurve.basis_surface) else: if ('CONFIG_CONTROL_DESIGN.POLYLINE' == TYPEOF(cv)): if (SIZEOF(cv.polyline.points) >= 3): return TRUE else: if ('CONFIG_CONTROL_DESIGN.SURFACE_CURVE' == TYPEOF(cv)): if (gbsf_check_curve(cv.surface_curve.curve_3d)): for i in range(1,SIZEOF(cv.surface_curve.associated_geometry),1): if ('CONFIG_CONTROL_DESIGN.SURFACE' == TYPEOF(cv.surface_curve.associated_geometry[i])): if ( not gbsf_check_surface(cv.surface_curve.associated_geometry[i])): return FALSE else: if ('CONFIG_CONTROL_DESIGN.PCURVE' == TYPEOF(cv.surface_curve.associated_geometry[i])): if ( not gbsf_check_curve(cv.surface_curve.associated_geometry[i])): return FALSE return TRUE else: if ('CONFIG_CONTROL_DESIGN.TRIMMED_CURVE' == TYPEOF(cv)): if (SIZEOF(['CONFIG_CONTROL_DESIGN.LINE','CONFIG_CONTROL_DESIGN.PARABOLA','CONFIG_CONTROL_DESIGN.HYPERBOLA'] * TYPEOF(cv.trimmed_curve.basis_curve)) == 1): return TRUE else: return gbsf_check_curve(cv.trimmed_curve.basis_curve) return FALSE
[ "def", "gbsf_check_curve", "(", "cv", ",", ")", ":", "if", "(", "SIZEOF", "(", "[", "'CONFIG_CONTROL_DESIGN.BOUNDED_CURVE'", ",", "'CONFIG_CONTROL_DESIGN.CONIC'", ",", "'CONFIG_CONTROL_DESIGN.CURVE_REPLICA'", ",", "'CONFIG_CONTROL_DESIGN.LINE'", ",", "'CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D'", "]", "*", "TYPEOF", "(", "cv", ")", ")", ">", "1", ")", ":", "return", "FALSE", "else", ":", "if", "(", "SIZEOF", "(", "[", "'CONFIG_CONTROL_DESIGN.CIRCLE'", ",", "'CONFIG_CONTROL_DESIGN.ELLIPSE'", "]", "*", "TYPEOF", "(", "cv", ")", ")", "==", "1", ")", ":", "return", "TRUE", "else", ":", "if", "(", "(", "(", "'CONFIG_CONTROL_DESIGN.B_SPLINE_CURVE'", "==", "TYPEOF", "(", "cv", ")", ")", "and", "(", "cv", ".", "b_spline_curve", ".", "self_intersect", "==", "FALSE", ")", ")", "or", "(", "cv", ".", "b_spline_curve", ".", "self_intersect", "==", "UNKNOWN", ")", ")", ":", "return", "TRUE", "else", ":", "if", "(", "(", "(", "'CONFIG_CONTROL_DESIGN.COMPOSITE_CURVE'", "==", "TYPEOF", "(", "cv", ")", ")", "and", "(", "cv", ".", "composite_curve", ".", "self_intersect", "==", "FALSE", ")", ")", "or", "(", "cv", ".", "composite_curve", ".", "self_intersect", "==", "UNKNOWN", ")", ")", ":", "return", "SIZEOF", "(", "None", ")", "==", "0", "else", ":", "if", "(", "'CONFIG_CONTROL_DESIGN.CURVE_REPLICA'", "==", "TYPEOF", "(", "cv", ")", ")", ":", "return", "gbsf_check_curve", "(", "cv", ".", "curve_replica", ".", "parent_curve", ")", "else", ":", "if", "(", "(", "(", "'CONFIG_CONTROL_DESIGN.OFFSET_CURVE_3D'", "==", "TYPEOF", "(", "cv", ")", ")", "and", "(", "(", "cv", ".", "offset_curve_3d", ".", "self_intersect", "==", "FALSE", ")", "or", "(", "cv", ".", "offset_curve_3d", ".", "self_intersect", "==", "UNKNOWN", ")", ")", ")", "and", "(", "not", "(", "'CONFIG_CONTROL_DESIGN.POLYLINE'", "==", "TYPEOF", "(", "cv", ".", "basis_curve", ")", ")", ")", ")", ":", "return", "gbsf_check_curve", "(", "cv", ".", "offset_curve_3d", ".", "basis_curve", ")", "else", ":", "if", "(", "'CONFIG_CONTROL_DESIGN.PCURVE'", "==", "TYPEOF", "(", "cv", ")", ")", ":", "return", "gbsf_check_curve", "(", "cv", ".", "pcurve", ".", "reference_to_curve", ".", "representation", ".", "items", "[", "1", "]", ")", "and", "gbsf_check_surface", "(", "cv", ".", "pcurve", ".", "basis_surface", ")", "else", ":", "if", "(", "'CONFIG_CONTROL_DESIGN.POLYLINE'", "==", "TYPEOF", "(", "cv", ")", ")", ":", "if", "(", "SIZEOF", "(", "cv", ".", "polyline", ".", "points", ")", ">=", "3", ")", ":", "return", "TRUE", "else", ":", "if", "(", "'CONFIG_CONTROL_DESIGN.SURFACE_CURVE'", "==", "TYPEOF", "(", "cv", ")", ")", ":", "if", "(", "gbsf_check_curve", "(", "cv", ".", "surface_curve", ".", "curve_3d", ")", ")", ":", "for", "i", "in", "range", "(", "1", ",", "SIZEOF", "(", "cv", ".", "surface_curve", ".", "associated_geometry", ")", ",", "1", ")", ":", "if", "(", "'CONFIG_CONTROL_DESIGN.SURFACE'", "==", "TYPEOF", "(", "cv", ".", "surface_curve", ".", "associated_geometry", "[", "i", "]", ")", ")", ":", "if", "(", "not", "gbsf_check_surface", "(", "cv", ".", "surface_curve", ".", "associated_geometry", "[", "i", "]", ")", ")", ":", "return", "FALSE", "else", ":", "if", "(", "'CONFIG_CONTROL_DESIGN.PCURVE'", "==", "TYPEOF", "(", "cv", ".", "surface_curve", ".", "associated_geometry", "[", "i", "]", ")", ")", ":", "if", "(", "not", "gbsf_check_curve", "(", "cv", ".", "surface_curve", ".", "associated_geometry", "[", "i", "]", ")", ")", ":", "return", "FALSE", "return", "TRUE", "else", ":", "if", "(", "'CONFIG_CONTROL_DESIGN.TRIMMED_CURVE'", "==", "TYPEOF", "(", "cv", ")", ")", ":", "if", "(", "SIZEOF", "(", "[", "'CONFIG_CONTROL_DESIGN.LINE'", ",", "'CONFIG_CONTROL_DESIGN.PARABOLA'", ",", "'CONFIG_CONTROL_DESIGN.HYPERBOLA'", "]", "*", "TYPEOF", "(", "cv", ".", "trimmed_curve", ".", "basis_curve", ")", ")", "==", "1", ")", ":", "return", "TRUE", "else", ":", "return", "gbsf_check_curve", "(", "cv", ".", "trimmed_curve", ".", "basis_curve", ")", "return", "FALSE" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Import/App/config_control_design.py#L11988-L12035
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/backend.py
python
batch_normalization
(x, mean, var, beta, gamma, epsilon=1e-3)
return nn.batch_normalization(x, mean, var, beta, gamma, epsilon)
Applies batch normalization on x given mean, var, beta and gamma. I.e. returns: `output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta` Arguments: x: Input tensor or variable. mean: Mean of batch. var: Variance of batch. beta: Tensor with which to center the input. gamma: Tensor by which to scale the input. epsilon: Fuzz factor. Returns: A tensor.
Applies batch normalization on x given mean, var, beta and gamma.
[ "Applies", "batch", "normalization", "on", "x", "given", "mean", "var", "beta", "and", "gamma", "." ]
def batch_normalization(x, mean, var, beta, gamma, epsilon=1e-3): """Applies batch normalization on x given mean, var, beta and gamma. I.e. returns: `output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta` Arguments: x: Input tensor or variable. mean: Mean of batch. var: Variance of batch. beta: Tensor with which to center the input. gamma: Tensor by which to scale the input. epsilon: Fuzz factor. Returns: A tensor. """ return nn.batch_normalization(x, mean, var, beta, gamma, epsilon)
[ "def", "batch_normalization", "(", "x", ",", "mean", ",", "var", ",", "beta", ",", "gamma", ",", "epsilon", "=", "1e-3", ")", ":", "return", "nn", ".", "batch_normalization", "(", "x", ",", "mean", ",", "var", ",", "beta", ",", "gamma", ",", "epsilon", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L1879-L1896
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextObject_GetTotalMargin
(*args, **kwargs)
return _richtext.RichTextObject_GetTotalMargin(*args, **kwargs)
RichTextObject_GetTotalMargin(DC dc, RichTextBuffer buffer, RichTextAttr attr, int leftMargin, int rightMargin, int topMargin, int bottomMargin) -> bool
RichTextObject_GetTotalMargin(DC dc, RichTextBuffer buffer, RichTextAttr attr, int leftMargin, int rightMargin, int topMargin, int bottomMargin) -> bool
[ "RichTextObject_GetTotalMargin", "(", "DC", "dc", "RichTextBuffer", "buffer", "RichTextAttr", "attr", "int", "leftMargin", "int", "rightMargin", "int", "topMargin", "int", "bottomMargin", ")", "-", ">", "bool" ]
def RichTextObject_GetTotalMargin(*args, **kwargs): """ RichTextObject_GetTotalMargin(DC dc, RichTextBuffer buffer, RichTextAttr attr, int leftMargin, int rightMargin, int topMargin, int bottomMargin) -> bool """ return _richtext.RichTextObject_GetTotalMargin(*args, **kwargs)
[ "def", "RichTextObject_GetTotalMargin", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_GetTotalMargin", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L1486-L1492
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
_get_sharded_variable
(name, shape, dtype, num_shards)
return shards
Get a list of sharded variables with the given dtype.
Get a list of sharded variables with the given dtype.
[ "Get", "a", "list", "of", "sharded", "variables", "with", "the", "given", "dtype", "." ]
def _get_sharded_variable(name, shape, dtype, num_shards): """Get a list of sharded variables with the given dtype.""" if num_shards > shape[0]: raise ValueError("Too many shards: shape=%s, num_shards=%d" % (shape, num_shards)) unit_shard_size = int(math.floor(shape[0] / num_shards)) remaining_rows = shape[0] - unit_shard_size * num_shards shards = [] for i in range(num_shards): current_size = unit_shard_size if i < remaining_rows: current_size += 1 shards.append(vs.get_variable(name + "_%d" % i, [current_size] + shape[1:], dtype=dtype)) return shards
[ "def", "_get_sharded_variable", "(", "name", ",", "shape", ",", "dtype", ",", "num_shards", ")", ":", "if", "num_shards", ">", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "\"Too many shards: shape=%s, num_shards=%d\"", "%", "(", "shape", ",", "num_shards", ")", ")", "unit_shard_size", "=", "int", "(", "math", ".", "floor", "(", "shape", "[", "0", "]", "/", "num_shards", ")", ")", "remaining_rows", "=", "shape", "[", "0", "]", "-", "unit_shard_size", "*", "num_shards", "shards", "=", "[", "]", "for", "i", "in", "range", "(", "num_shards", ")", ":", "current_size", "=", "unit_shard_size", "if", "i", "<", "remaining_rows", ":", "current_size", "+=", "1", "shards", ".", "append", "(", "vs", ".", "get_variable", "(", "name", "+", "\"_%d\"", "%", "i", ",", "[", "current_size", "]", "+", "shape", "[", "1", ":", "]", ",", "dtype", "=", "dtype", ")", ")", "return", "shards" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L51-L66
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintscoordentry.py
python
VariableValue.type
(self)
return 'VariableType'
Gets specialization type of CoordValue
Gets specialization type of CoordValue
[ "Gets", "specialization", "type", "of", "CoordValue" ]
def type(self): """Gets specialization type of CoordValue""" return 'VariableType'
[ "def", "type", "(", "self", ")", ":", "return", "'VariableType'" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintscoordentry.py#L142-L144
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
AboutDialogInfo.HasLicence
(*args, **kwargs)
return _misc_.AboutDialogInfo_HasLicence(*args, **kwargs)
HasLicence(self) -> bool Returns ``True`` if the licence property has been set.
HasLicence(self) -> bool
[ "HasLicence", "(", "self", ")", "-", ">", "bool" ]
def HasLicence(*args, **kwargs): """ HasLicence(self) -> bool Returns ``True`` if the licence property has been set. """ return _misc_.AboutDialogInfo_HasLicence(*args, **kwargs)
[ "def", "HasLicence", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "AboutDialogInfo_HasLicence", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6716-L6722
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/layers/python/layers/feature_column_ops.py
python
_check_forbidden_sequence_columns
(feature_columns)
Recursively cecks `feature_columns` for `_FORBIDDEN_SEQUENCE_COLUMNS`.
Recursively cecks `feature_columns` for `_FORBIDDEN_SEQUENCE_COLUMNS`.
[ "Recursively", "cecks", "feature_columns", "for", "_FORBIDDEN_SEQUENCE_COLUMNS", "." ]
def _check_forbidden_sequence_columns(feature_columns): """Recursively cecks `feature_columns` for `_FORBIDDEN_SEQUENCE_COLUMNS`.""" all_feature_columns = _gather_feature_columns(feature_columns) for feature_column in all_feature_columns: if isinstance(feature_column, _FORBIDDEN_SEQUENCE_COLUMNS): raise ValueError( 'Column {} is of type {}, which is not currently supported for ' 'sequences.'.format(feature_column.name, type(feature_column).__name__))
[ "def", "_check_forbidden_sequence_columns", "(", "feature_columns", ")", ":", "all_feature_columns", "=", "_gather_feature_columns", "(", "feature_columns", ")", "for", "feature_column", "in", "all_feature_columns", ":", "if", "isinstance", "(", "feature_column", ",", "_FORBIDDEN_SEQUENCE_COLUMNS", ")", ":", "raise", "ValueError", "(", "'Column {} is of type {}, which is not currently supported for '", "'sequences.'", ".", "format", "(", "feature_column", ".", "name", ",", "type", "(", "feature_column", ")", ".", "__name__", ")", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/layers/python/layers/feature_column_ops.py#L821-L829
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/google/protobuf/internal/python_message.py
python
_IsPresent
(item)
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().
[ "Given", "a", "(", "FieldDescriptor", "value", ")", "tuple", "from", "_fields", "return", "true", "if", "the", "value", "should", "be", "included", "in", "the", "list", "returned", "by", "ListFields", "()", "." ]
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return item[1]._is_present_in_parent else: return True
[ "def", "_IsPresent", "(", "item", ")", ":", "if", "item", "[", "0", "]", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "return", "bool", "(", "item", "[", "1", "]", ")", "elif", "item", "[", "0", "]", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "return", "item", "[", "1", "]", ".", "_is_present_in_parent", "else", ":", "return", "True" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/internal/python_message.py#L588-L597
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/codecs.py
python
IncrementalEncoder.getstate
(self)
return 0
Return the current state of the encoder.
Return the current state of the encoder.
[ "Return", "the", "current", "state", "of", "the", "encoder", "." ]
def getstate(self): """ Return the current state of the encoder. """ return 0
[ "def", "getstate", "(", "self", ")", ":", "return", "0" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/codecs.py#L208-L212
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/crash/module.py
python
Module.timestamp_filter
(self, f: Callable[[datetime.datetime], bool])
return filter(inner, self.crashes.items())
Filter crash reports by timestamp. :param f: f(time) return true to keep crash report :returns: crash reports for which f(time) returns true
Filter crash reports by timestamp.
[ "Filter", "crash", "reports", "by", "timestamp", "." ]
def timestamp_filter(self, f: Callable[[datetime.datetime], bool]) -> Iterable[Tuple[str, CrashT]]: """ Filter crash reports by timestamp. :param f: f(time) return true to keep crash report :returns: crash reports for which f(time) returns true """ def inner(pair: Tuple[str, CrashT]) -> bool: _, crash = pair time = self.time_from_string(cast(str, crash["timestamp"])) return f(time) assert self.crashes is not None return filter(inner, self.crashes.items())
[ "def", "timestamp_filter", "(", "self", ",", "f", ":", "Callable", "[", "[", "datetime", ".", "datetime", "]", ",", "bool", "]", ")", "->", "Iterable", "[", "Tuple", "[", "str", ",", "CrashT", "]", "]", ":", "def", "inner", "(", "pair", ":", "Tuple", "[", "str", ",", "CrashT", "]", ")", "->", "bool", ":", "_", ",", "crash", "=", "pair", "time", "=", "self", ".", "time_from_string", "(", "cast", "(", "str", ",", "crash", "[", "\"timestamp\"", "]", ")", ")", "return", "f", "(", "time", ")", "assert", "self", ".", "crashes", "is", "not", "None", "return", "filter", "(", "inner", ",", "self", ".", "crashes", ".", "items", "(", ")", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/crash/module.py#L171-L183
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/logging/handlers.py
python
SocketHandler.emit
(self, record)
Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket.
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket. """ try: s = self.makePickle(record) self.send(s) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "s", "=", "self", ".", "makePickle", "(", "record", ")", "self", ".", "send", "(", "s", ")", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "raise", "except", ":", "self", ".", "handleError", "(", "record", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/handlers.py#L531-L546
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/logging/graph.py
python
plot
(root, filename=None)
return model
Walks through every node of the graph starting at ``root``, creates a network graph, and returns a network description. If ``filename`` is specified, it outputs a DOT, PNG, PDF, or SVG file depending on the file name's suffix. Requirements: * for DOT output: `pydot_ng <https://pypi.python.org/pypi/pydot-ng>`__ * for PNG, PDF, and SVG output: `pydot_ng <https://pypi.python.org/pypi/pydot-ng>`__ and `graphviz <http://graphviz.org>`__ (GraphViz executable has to be in the system's PATH). Args: node (graph node): the node to start the journey from filename (`str`, default None): file with extension '.dot', 'png', 'pdf', or 'svg' to denote what format should be written. If `None` then nothing will be plotted, and the returned string can be used to debug the graph. Returns: `str` describing the graph
Walks through every node of the graph starting at ``root``, creates a network graph, and returns a network description. If ``filename`` is specified, it outputs a DOT, PNG, PDF, or SVG file depending on the file name's suffix.
[ "Walks", "through", "every", "node", "of", "the", "graph", "starting", "at", "root", "creates", "a", "network", "graph", "and", "returns", "a", "network", "description", ".", "If", "filename", "is", "specified", "it", "outputs", "a", "DOT", "PNG", "PDF", "or", "SVG", "file", "depending", "on", "the", "file", "name", "s", "suffix", "." ]
def plot(root, filename=None): ''' Walks through every node of the graph starting at ``root``, creates a network graph, and returns a network description. If ``filename`` is specified, it outputs a DOT, PNG, PDF, or SVG file depending on the file name's suffix. Requirements: * for DOT output: `pydot_ng <https://pypi.python.org/pypi/pydot-ng>`__ * for PNG, PDF, and SVG output: `pydot_ng <https://pypi.python.org/pypi/pydot-ng>`__ and `graphviz <http://graphviz.org>`__ (GraphViz executable has to be in the system's PATH). Args: node (graph node): the node to start the journey from filename (`str`, default None): file with extension '.dot', 'png', 'pdf', or 'svg' to denote what format should be written. If `None` then nothing will be plotted, and the returned string can be used to debug the graph. Returns: `str` describing the graph ''' if filename: suffix = os.path.splitext(filename)[1].lower() if suffix not in ('.svg', '.pdf', '.png', '.dot'): raise ValueError('only file extensions ".svg", ".pdf", ".png", and ".dot" are supported') else: suffix = None if filename: try: import pydot_ng as pydot except ImportError: raise ImportError("Unable to import pydot_ng, which is required to output SVG, PDF, PNG, and DOT format.") # initialize a dot object to store vertices and edges dot_object = pydot.Dot(graph_name="network_graph", rankdir='TB') dot_object.set_node_defaults(shape='rectangle', fixedsize='false', style='filled', fillcolor='lightgray', height=.85, width=.85, fontsize=12) dot_object.set_edge_defaults(fontsize=10) # string to store model model = [] root = root.root_function root_uid = root.uid stack = [root] visited = set() # [uid] instead of node object itself, as this gives us duplicate entries for nodes with multiple outputs primitive_op_map = { 'Plus': '+', 'Minus': '-', 'ElementTimes': '*', 'Times': '@', } function_nodes = {} # [uid] -> dot node def node_desc(node): name = "<font point-size=\"10\" face=\"sans\">'%s'</font> <br/>"%node.name try: name += "<b><font point-size=\"14\" face=\"sans\">%s</font></b> <br/>"%node.op_name except AttributeError: pass name += "<font point-size=\"8\" face=\"sans\">%s</font>"%node.uid return '<' + name + '>' def shape_desc(node): dyn_axes = node.dynamic_axes dyn = '[#' + ',*' * (len(dyn_axes) - 1) + ']' if len(dyn_axes) > 0 else '' # the '#' indicates the batch axis, while * indicate dynamic axes (which can be sequences) return dyn + str(node.shape) static_shape = str(node.shape) return '"#dyn: %i\nstatic: %s"'%(num_dyn_axes, static_shape) while stack: node = stack.pop(0) if node.uid in visited: continue try: # Function node node = node.root_function stack = list(node.root_function.inputs) + stack # add current Function node def lazy_create_node(node): if node.uid in function_nodes: # dot node already exists return function_nodes[node.uid] if node.is_primitive and not node.is_block and len(node.outputs) == 1 and node.output.name == node.name: # skip the node name if redundant op_name = primitive_op_map.get(node.op_name, node.op_name) render_as_primitive = len(op_name) <= 4 size = 0.4 if render_as_primitive else 0.6 cur_node = pydot.Node(node.uid, label='"' + op_name + '"', shape='ellipse' if render_as_primitive else 'box', fixedsize='true' if render_as_primitive else 'false', height=size, width=size, fontsize=20 if render_as_primitive and len(op_name) == 1 else 12 , penwidth=4 if node.op_name != 'Pass' and node.op_name != 'ParameterOrder' else 1) # TODO: Would be cool, if the user could pass a dictionary with overrides. But maybe for a later version. else: f_name = '\n' + node.name + '()' if node.name else '' cur_node = pydot.Node(node.uid, label='"' + node.op_name + f_name + '"', fixedsize='true', height=1, width=1.3, penwidth=4 if node.op_name != 'Pass' and node.op_name != 'ParameterOrder' else 1) dot_object.add_node(cur_node) function_nodes[node.uid] = cur_node return cur_node # add current node line = [node.op_name] line.append('(') if filename: cur_node = lazy_create_node(node) dot_object.add_node(cur_node) # add node's inputs for i, input in enumerate(node.inputs): # Suppress Constants inside BlockFunctions, since those are really private to the BlockFunction. # Still show Parameters, so users know what parameters it learns, e.g. a layer. from cntk import cntk_py if node.is_block and isinstance (input, cntk_py.Variable) and input.is_constant: continue line.append(input.uid) if i != len(node.inputs) - 1: line.append(', ') if filename: if input.is_input: shape = 'invhouse' color = 'yellow' elif input.is_placeholder: shape = 'invhouse' color = 'grey' elif input.is_parameter: shape = 'diamond' color = 'green' elif input.is_constant: shape = 'rectangle' color = 'lightblue' else: # is_output shape = 'invhouse' color = 'grey' if isinstance (input, cntk_py.Variable) and not input.is_output: name = 'Parameter' if input.is_parameter else 'Constant' if input.is_constant else 'Input' if input.is_input else 'Placeholder' if input.name: if name == 'Parameter': # don't say 'Parameter' for named parameters, it's already indicated by being a box name = input.name else: name = name + '\n' + input.name name += '\n' + shape_desc(input) if input.is_input or input.is_placeholder: # graph inputs are eggs (since dot has no oval) input_node = pydot.Node(input.uid, shape='egg', label=name, fixedsize='true', height=1, width=1.3, penwidth=4) # wish it had an oval elif not input.name and input.is_constant and (input.shape == () or input.shape == (1,)): # unnamed scalar constants are just shown as values input_node = pydot.Node(input.uid, shape='box', label=str(input.as_constant().value), color='white', fillcolor='white', height=0.3, width=0.4) else: # parameters and constants are boxes input_node = pydot.Node(input.uid, shape='box', label=name, height=0.6, width=1) else: # output variables never get drawn except the final output assert(isinstance (input, cntk_py.Variable)) input_node = lazy_create_node(input.owner) # connect to where the output comes from directly, no need to draw it dot_object.add_node(input_node) label = input.name if input.name else input.uid # the Output variables have no name if the function has none label += '\n' + shape_desc(input) dot_object.add_edge(pydot.Edge(input_node, cur_node, label=label)) # add node's output line.append(') -> ') line = ''.join(line) for n in node.outputs: model.append(line + n.uid + ';\n') if (filename): if node.uid == root_uid: # only final network outputs are drawn for output in node.outputs: final_node = pydot.Node(output.uid, shape='egg', label=output.name + '\n' + shape_desc(output), fixedsize='true', height=1, width=1.3, penwidth=4) dot_object.add_node(final_node) dot_object.add_edge(pydot.Edge(cur_node, final_node, label=shape_desc(output))) except AttributeError: # OutputVariable node try: if node.is_output: stack.insert(0, node.owner) except AttributeError: pass visited.add(node.uid) if filename: if suffix == '.svg': dot_object.write_svg(filename, prog='dot') elif suffix == '.pdf': dot_object.write_pdf(filename, prog='dot') elif suffix == '.png': dot_object.write_png(filename, prog='dot') else: dot_object.write_raw(filename) model = "\n".join(reversed(model)) return model
[ "def", "plot", "(", "root", ",", "filename", "=", "None", ")", ":", "if", "filename", ":", "suffix", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ".", "lower", "(", ")", "if", "suffix", "not", "in", "(", "'.svg'", ",", "'.pdf'", ",", "'.png'", ",", "'.dot'", ")", ":", "raise", "ValueError", "(", "'only file extensions \".svg\", \".pdf\", \".png\", and \".dot\" are supported'", ")", "else", ":", "suffix", "=", "None", "if", "filename", ":", "try", ":", "import", "pydot_ng", "as", "pydot", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Unable to import pydot_ng, which is required to output SVG, PDF, PNG, and DOT format.\"", ")", "# initialize a dot object to store vertices and edges", "dot_object", "=", "pydot", ".", "Dot", "(", "graph_name", "=", "\"network_graph\"", ",", "rankdir", "=", "'TB'", ")", "dot_object", ".", "set_node_defaults", "(", "shape", "=", "'rectangle'", ",", "fixedsize", "=", "'false'", ",", "style", "=", "'filled'", ",", "fillcolor", "=", "'lightgray'", ",", "height", "=", ".85", ",", "width", "=", ".85", ",", "fontsize", "=", "12", ")", "dot_object", ".", "set_edge_defaults", "(", "fontsize", "=", "10", ")", "# string to store model", "model", "=", "[", "]", "root", "=", "root", ".", "root_function", "root_uid", "=", "root", ".", "uid", "stack", "=", "[", "root", "]", "visited", "=", "set", "(", ")", "# [uid] instead of node object itself, as this gives us duplicate entries for nodes with multiple outputs", "primitive_op_map", "=", "{", "'Plus'", ":", "'+'", ",", "'Minus'", ":", "'-'", ",", "'ElementTimes'", ":", "'*'", ",", "'Times'", ":", "'@'", ",", "}", "function_nodes", "=", "{", "}", "# [uid] -> dot node", "def", "node_desc", "(", "node", ")", ":", "name", "=", "\"<font point-size=\\\"10\\\" face=\\\"sans\\\">'%s'</font> <br/>\"", "%", "node", ".", "name", "try", ":", "name", "+=", "\"<b><font point-size=\\\"14\\\" face=\\\"sans\\\">%s</font></b> <br/>\"", "%", "node", ".", "op_name", "except", "AttributeError", ":", "pass", "name", "+=", "\"<font point-size=\\\"8\\\" face=\\\"sans\\\">%s</font>\"", "%", "node", ".", "uid", "return", "'<'", "+", "name", "+", "'>'", "def", "shape_desc", "(", "node", ")", ":", "dyn_axes", "=", "node", ".", "dynamic_axes", "dyn", "=", "'[#'", "+", "',*'", "*", "(", "len", "(", "dyn_axes", ")", "-", "1", ")", "+", "']'", "if", "len", "(", "dyn_axes", ")", ">", "0", "else", "''", "# the '#' indicates the batch axis, while * indicate dynamic axes (which can be sequences)", "return", "dyn", "+", "str", "(", "node", ".", "shape", ")", "static_shape", "=", "str", "(", "node", ".", "shape", ")", "return", "'\"#dyn: %i\\nstatic: %s\"'", "%", "(", "num_dyn_axes", ",", "static_shape", ")", "while", "stack", ":", "node", "=", "stack", ".", "pop", "(", "0", ")", "if", "node", ".", "uid", "in", "visited", ":", "continue", "try", ":", "# Function node", "node", "=", "node", ".", "root_function", "stack", "=", "list", "(", "node", ".", "root_function", ".", "inputs", ")", "+", "stack", "# add current Function node", "def", "lazy_create_node", "(", "node", ")", ":", "if", "node", ".", "uid", "in", "function_nodes", ":", "# dot node already exists", "return", "function_nodes", "[", "node", ".", "uid", "]", "if", "node", ".", "is_primitive", "and", "not", "node", ".", "is_block", "and", "len", "(", "node", ".", "outputs", ")", "==", "1", "and", "node", ".", "output", ".", "name", "==", "node", ".", "name", ":", "# skip the node name if redundant", "op_name", "=", "primitive_op_map", ".", "get", "(", "node", ".", "op_name", ",", "node", ".", "op_name", ")", "render_as_primitive", "=", "len", "(", "op_name", ")", "<=", "4", "size", "=", "0.4", "if", "render_as_primitive", "else", "0.6", "cur_node", "=", "pydot", ".", "Node", "(", "node", ".", "uid", ",", "label", "=", "'\"'", "+", "op_name", "+", "'\"'", ",", "shape", "=", "'ellipse'", "if", "render_as_primitive", "else", "'box'", ",", "fixedsize", "=", "'true'", "if", "render_as_primitive", "else", "'false'", ",", "height", "=", "size", ",", "width", "=", "size", ",", "fontsize", "=", "20", "if", "render_as_primitive", "and", "len", "(", "op_name", ")", "==", "1", "else", "12", ",", "penwidth", "=", "4", "if", "node", ".", "op_name", "!=", "'Pass'", "and", "node", ".", "op_name", "!=", "'ParameterOrder'", "else", "1", ")", "# TODO: Would be cool, if the user could pass a dictionary with overrides. But maybe for a later version.", "else", ":", "f_name", "=", "'\\n'", "+", "node", ".", "name", "+", "'()'", "if", "node", ".", "name", "else", "''", "cur_node", "=", "pydot", ".", "Node", "(", "node", ".", "uid", ",", "label", "=", "'\"'", "+", "node", ".", "op_name", "+", "f_name", "+", "'\"'", ",", "fixedsize", "=", "'true'", ",", "height", "=", "1", ",", "width", "=", "1.3", ",", "penwidth", "=", "4", "if", "node", ".", "op_name", "!=", "'Pass'", "and", "node", ".", "op_name", "!=", "'ParameterOrder'", "else", "1", ")", "dot_object", ".", "add_node", "(", "cur_node", ")", "function_nodes", "[", "node", ".", "uid", "]", "=", "cur_node", "return", "cur_node", "# add current node", "line", "=", "[", "node", ".", "op_name", "]", "line", ".", "append", "(", "'('", ")", "if", "filename", ":", "cur_node", "=", "lazy_create_node", "(", "node", ")", "dot_object", ".", "add_node", "(", "cur_node", ")", "# add node's inputs", "for", "i", ",", "input", "in", "enumerate", "(", "node", ".", "inputs", ")", ":", "# Suppress Constants inside BlockFunctions, since those are really private to the BlockFunction.", "# Still show Parameters, so users know what parameters it learns, e.g. a layer.", "from", "cntk", "import", "cntk_py", "if", "node", ".", "is_block", "and", "isinstance", "(", "input", ",", "cntk_py", ".", "Variable", ")", "and", "input", ".", "is_constant", ":", "continue", "line", ".", "append", "(", "input", ".", "uid", ")", "if", "i", "!=", "len", "(", "node", ".", "inputs", ")", "-", "1", ":", "line", ".", "append", "(", "', '", ")", "if", "filename", ":", "if", "input", ".", "is_input", ":", "shape", "=", "'invhouse'", "color", "=", "'yellow'", "elif", "input", ".", "is_placeholder", ":", "shape", "=", "'invhouse'", "color", "=", "'grey'", "elif", "input", ".", "is_parameter", ":", "shape", "=", "'diamond'", "color", "=", "'green'", "elif", "input", ".", "is_constant", ":", "shape", "=", "'rectangle'", "color", "=", "'lightblue'", "else", ":", "# is_output", "shape", "=", "'invhouse'", "color", "=", "'grey'", "if", "isinstance", "(", "input", ",", "cntk_py", ".", "Variable", ")", "and", "not", "input", ".", "is_output", ":", "name", "=", "'Parameter'", "if", "input", ".", "is_parameter", "else", "'Constant'", "if", "input", ".", "is_constant", "else", "'Input'", "if", "input", ".", "is_input", "else", "'Placeholder'", "if", "input", ".", "name", ":", "if", "name", "==", "'Parameter'", ":", "# don't say 'Parameter' for named parameters, it's already indicated by being a box", "name", "=", "input", ".", "name", "else", ":", "name", "=", "name", "+", "'\\n'", "+", "input", ".", "name", "name", "+=", "'\\n'", "+", "shape_desc", "(", "input", ")", "if", "input", ".", "is_input", "or", "input", ".", "is_placeholder", ":", "# graph inputs are eggs (since dot has no oval)", "input_node", "=", "pydot", ".", "Node", "(", "input", ".", "uid", ",", "shape", "=", "'egg'", ",", "label", "=", "name", ",", "fixedsize", "=", "'true'", ",", "height", "=", "1", ",", "width", "=", "1.3", ",", "penwidth", "=", "4", ")", "# wish it had an oval", "elif", "not", "input", ".", "name", "and", "input", ".", "is_constant", "and", "(", "input", ".", "shape", "==", "(", ")", "or", "input", ".", "shape", "==", "(", "1", ",", ")", ")", ":", "# unnamed scalar constants are just shown as values", "input_node", "=", "pydot", ".", "Node", "(", "input", ".", "uid", ",", "shape", "=", "'box'", ",", "label", "=", "str", "(", "input", ".", "as_constant", "(", ")", ".", "value", ")", ",", "color", "=", "'white'", ",", "fillcolor", "=", "'white'", ",", "height", "=", "0.3", ",", "width", "=", "0.4", ")", "else", ":", "# parameters and constants are boxes", "input_node", "=", "pydot", ".", "Node", "(", "input", ".", "uid", ",", "shape", "=", "'box'", ",", "label", "=", "name", ",", "height", "=", "0.6", ",", "width", "=", "1", ")", "else", ":", "# output variables never get drawn except the final output", "assert", "(", "isinstance", "(", "input", ",", "cntk_py", ".", "Variable", ")", ")", "input_node", "=", "lazy_create_node", "(", "input", ".", "owner", ")", "# connect to where the output comes from directly, no need to draw it", "dot_object", ".", "add_node", "(", "input_node", ")", "label", "=", "input", ".", "name", "if", "input", ".", "name", "else", "input", ".", "uid", "# the Output variables have no name if the function has none", "label", "+=", "'\\n'", "+", "shape_desc", "(", "input", ")", "dot_object", ".", "add_edge", "(", "pydot", ".", "Edge", "(", "input_node", ",", "cur_node", ",", "label", "=", "label", ")", ")", "# add node's output", "line", ".", "append", "(", "') -> '", ")", "line", "=", "''", ".", "join", "(", "line", ")", "for", "n", "in", "node", ".", "outputs", ":", "model", ".", "append", "(", "line", "+", "n", ".", "uid", "+", "';\\n'", ")", "if", "(", "filename", ")", ":", "if", "node", ".", "uid", "==", "root_uid", ":", "# only final network outputs are drawn", "for", "output", "in", "node", ".", "outputs", ":", "final_node", "=", "pydot", ".", "Node", "(", "output", ".", "uid", ",", "shape", "=", "'egg'", ",", "label", "=", "output", ".", "name", "+", "'\\n'", "+", "shape_desc", "(", "output", ")", ",", "fixedsize", "=", "'true'", ",", "height", "=", "1", ",", "width", "=", "1.3", ",", "penwidth", "=", "4", ")", "dot_object", ".", "add_node", "(", "final_node", ")", "dot_object", ".", "add_edge", "(", "pydot", ".", "Edge", "(", "cur_node", ",", "final_node", ",", "label", "=", "shape_desc", "(", "output", ")", ")", ")", "except", "AttributeError", ":", "# OutputVariable node", "try", ":", "if", "node", ".", "is_output", ":", "stack", ".", "insert", "(", "0", ",", "node", ".", "owner", ")", "except", "AttributeError", ":", "pass", "visited", ".", "add", "(", "node", ".", "uid", ")", "if", "filename", ":", "if", "suffix", "==", "'.svg'", ":", "dot_object", ".", "write_svg", "(", "filename", ",", "prog", "=", "'dot'", ")", "elif", "suffix", "==", "'.pdf'", ":", "dot_object", ".", "write_pdf", "(", "filename", ",", "prog", "=", "'dot'", ")", "elif", "suffix", "==", "'.png'", ":", "dot_object", ".", "write_png", "(", "filename", ",", "prog", "=", "'dot'", ")", "else", ":", "dot_object", ".", "write_raw", "(", "filename", ")", "model", "=", "\"\\n\"", ".", "join", "(", "reversed", "(", "model", ")", ")", "return", "model" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/logging/graph.py#L179-L387
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/zipfile.py
python
ZipFile.__init__
(self, file, mode="r", compression=ZIP_STORED, allowZip64=False)
Open the ZIP file with mode read "r", write "w" or append "a".
Open the ZIP file with mode read "r", write "w" or append "a".
[ "Open", "the", "ZIP", "file", "with", "mode", "read", "r", "write", "w", "or", "append", "a", "." ]
def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False): """Open the ZIP file with mode read "r", write "w" or append "a".""" if mode not in ("r", "w", "a"): raise RuntimeError('ZipFile() requires mode "r", "w", or "a"') if compression == ZIP_STORED: pass elif compression == ZIP_DEFLATED: if not zlib: raise RuntimeError,\ "Compression requires the (missing) zlib module" else: raise RuntimeError, "That compression method is not supported" self._allowZip64 = allowZip64 self._didModify = False self.debug = 0 # Level of printing: 0 through 3 self.NameToInfo = {} # Find file info given name self.filelist = [] # List of ZipInfo instances for archive self.compression = compression # Method of compression self.mode = key = mode.replace('b', '')[0] self.pwd = None self.comment = '' # Check if we were passed a file-like object if isinstance(file, basestring): self._filePassed = 0 self.filename = file modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} try: self.fp = open(file, modeDict[mode]) except IOError: if mode == 'a': mode = key = 'w' self.fp = open(file, modeDict[mode]) else: raise else: self._filePassed = 1 self.fp = file self.filename = getattr(file, 'name', None) if key == 'r': self._GetContents() elif key == 'w': pass elif key == 'a': try: # See if file is a zip file self._RealGetContents() # seek to start of directory and overwrite self.fp.seek(self.start_dir, 0) except BadZipfile: # file is not a zip file, just append self.fp.seek(0, 2) else: if not self._filePassed: self.fp.close() self.fp = None raise RuntimeError, 'Mode must be "r", "w" or "a"'
[ "def", "__init__", "(", "self", ",", "file", ",", "mode", "=", "\"r\"", ",", "compression", "=", "ZIP_STORED", ",", "allowZip64", "=", "False", ")", ":", "if", "mode", "not", "in", "(", "\"r\"", ",", "\"w\"", ",", "\"a\"", ")", ":", "raise", "RuntimeError", "(", "'ZipFile() requires mode \"r\", \"w\", or \"a\"'", ")", "if", "compression", "==", "ZIP_STORED", ":", "pass", "elif", "compression", "==", "ZIP_DEFLATED", ":", "if", "not", "zlib", ":", "raise", "RuntimeError", ",", "\"Compression requires the (missing) zlib module\"", "else", ":", "raise", "RuntimeError", ",", "\"That compression method is not supported\"", "self", ".", "_allowZip64", "=", "allowZip64", "self", ".", "_didModify", "=", "False", "self", ".", "debug", "=", "0", "# Level of printing: 0 through 3", "self", ".", "NameToInfo", "=", "{", "}", "# Find file info given name", "self", ".", "filelist", "=", "[", "]", "# List of ZipInfo instances for archive", "self", ".", "compression", "=", "compression", "# Method of compression", "self", ".", "mode", "=", "key", "=", "mode", ".", "replace", "(", "'b'", ",", "''", ")", "[", "0", "]", "self", ".", "pwd", "=", "None", "self", ".", "comment", "=", "''", "# Check if we were passed a file-like object", "if", "isinstance", "(", "file", ",", "basestring", ")", ":", "self", ".", "_filePassed", "=", "0", "self", ".", "filename", "=", "file", "modeDict", "=", "{", "'r'", ":", "'rb'", ",", "'w'", ":", "'wb'", ",", "'a'", ":", "'r+b'", "}", "try", ":", "self", ".", "fp", "=", "open", "(", "file", ",", "modeDict", "[", "mode", "]", ")", "except", "IOError", ":", "if", "mode", "==", "'a'", ":", "mode", "=", "key", "=", "'w'", "self", ".", "fp", "=", "open", "(", "file", ",", "modeDict", "[", "mode", "]", ")", "else", ":", "raise", "else", ":", "self", ".", "_filePassed", "=", "1", "self", ".", "fp", "=", "file", "self", ".", "filename", "=", "getattr", "(", "file", ",", "'name'", ",", "None", ")", "if", "key", "==", "'r'", ":", "self", ".", "_GetContents", "(", ")", "elif", "key", "==", "'w'", ":", "pass", "elif", "key", "==", "'a'", ":", "try", ":", "# See if file is a zip file", "self", ".", "_RealGetContents", "(", ")", "# seek to start of directory and overwrite", "self", ".", "fp", ".", "seek", "(", "self", ".", "start_dir", ",", "0", ")", "except", "BadZipfile", ":", "# file is not a zip file, just append", "self", ".", "fp", ".", "seek", "(", "0", ",", "2", ")", "else", ":", "if", "not", "self", ".", "_filePassed", ":", "self", ".", "fp", ".", "close", "(", ")", "self", ".", "fp", "=", "None", "raise", "RuntimeError", ",", "'Mode must be \"r\", \"w\" or \"a\"'" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/zipfile.py#L653-L710
CNugteren/CLBlast
4500a03440e2cc54998c0edab366babf5e504d67
scripts/generator/generator/routine.py
python
Routine.arguments_def_c
(self, flavour)
return (self.options_def_c() + self.sizes_def() + list(chain(*[self.buffer_def(b) for b in self.scalar_buffers_first()])) + self.scalar_def("alpha", flavour) + list(chain(*[self.buffer_def(b) for b in self.buffers_first()])) + self.scalar_def("beta", flavour) + list(chain(*[self.buffer_def(b) for b in self.buffers_second()])) + list(chain(*[self.buffer_def(b) for b in self.scalar_buffers_second()])) + list(chain(*[self.scalar_def(s, flavour) for s in self.other_scalars()])) + self.batch_count_def())
As above, but for the C API
As above, but for the C API
[ "As", "above", "but", "for", "the", "C", "API" ]
def arguments_def_c(self, flavour): """As above, but for the C API""" return (self.options_def_c() + self.sizes_def() + list(chain(*[self.buffer_def(b) for b in self.scalar_buffers_first()])) + self.scalar_def("alpha", flavour) + list(chain(*[self.buffer_def(b) for b in self.buffers_first()])) + self.scalar_def("beta", flavour) + list(chain(*[self.buffer_def(b) for b in self.buffers_second()])) + list(chain(*[self.buffer_def(b) for b in self.scalar_buffers_second()])) + list(chain(*[self.scalar_def(s, flavour) for s in self.other_scalars()])) + self.batch_count_def())
[ "def", "arguments_def_c", "(", "self", ",", "flavour", ")", ":", "return", "(", "self", ".", "options_def_c", "(", ")", "+", "self", ".", "sizes_def", "(", ")", "+", "list", "(", "chain", "(", "*", "[", "self", ".", "buffer_def", "(", "b", ")", "for", "b", "in", "self", ".", "scalar_buffers_first", "(", ")", "]", ")", ")", "+", "self", ".", "scalar_def", "(", "\"alpha\"", ",", "flavour", ")", "+", "list", "(", "chain", "(", "*", "[", "self", ".", "buffer_def", "(", "b", ")", "for", "b", "in", "self", ".", "buffers_first", "(", ")", "]", ")", ")", "+", "self", ".", "scalar_def", "(", "\"beta\"", ",", "flavour", ")", "+", "list", "(", "chain", "(", "*", "[", "self", ".", "buffer_def", "(", "b", ")", "for", "b", "in", "self", ".", "buffers_second", "(", ")", "]", ")", ")", "+", "list", "(", "chain", "(", "*", "[", "self", ".", "buffer_def", "(", "b", ")", "for", "b", "in", "self", ".", "scalar_buffers_second", "(", ")", "]", ")", ")", "+", "list", "(", "chain", "(", "*", "[", "self", ".", "scalar_def", "(", "s", ",", "flavour", ")", "for", "s", "in", "self", ".", "other_scalars", "(", ")", "]", ")", ")", "+", "self", ".", "batch_count_def", "(", ")", ")" ]
https://github.com/CNugteren/CLBlast/blob/4500a03440e2cc54998c0edab366babf5e504d67/scripts/generator/generator/routine.py#L755-L765
qboticslabs/mastering_ros
d83e78f30acc45b0f18522c1d5fae3a7f52974b9
chapter_9_codes/chefbot/chefbot/chefbot_bringup/scripts/bkup_working/arduino.py
python
Arduino._WriteSpeedControllerParams
(self, speedControllerParams)
Writes the speed controller parameters (drive gains (PID), and command timeout) to the Arduino controller.
Writes the speed controller parameters (drive gains (PID), and command timeout) to the Arduino controller.
[ "Writes", "the", "speed", "controller", "parameters", "(", "drive", "gains", "(", "PID", ")", "and", "command", "timeout", ")", "to", "the", "Arduino", "controller", "." ]
def _WriteSpeedControllerParams(self, speedControllerParams): """ Writes the speed controller parameters (drive gains (PID), and command timeout) to the Arduino controller. """ rospy.logdebug("Handling '_WriteSpeedControllerParams'; received parameters " + str(speedControllerParams)) message = 'SpeedCo %d %d %d %d %d %d %d %d %d %d\r' % self._GetBaseAndExponents(speedControllerParams) message = 'SpeedCo 763 -4 3700 -4 9750\r' # message = rospy.logdebug("Sending differential drive gains message: " + message)
[ "def", "_WriteSpeedControllerParams", "(", "self", ",", "speedControllerParams", ")", ":", "rospy", ".", "logdebug", "(", "\"Handling '_WriteSpeedControllerParams'; received parameters \"", "+", "str", "(", "speedControllerParams", ")", ")", "message", "=", "'SpeedCo %d %d %d %d %d %d %d %d %d %d\\r'", "%", "self", ".", "_GetBaseAndExponents", "(", "speedControllerParams", ")", "message", "=", "'SpeedCo 763 -4 3700 -4 9750\\r'", "#\t\tmessage = ", "rospy", ".", "logdebug", "(", "\"Sending differential drive gains message: \"", "+", "message", ")" ]
https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_9_codes/chefbot/chefbot/chefbot_bringup/scripts/bkup_working/arduino.py#L380-L387
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/json/encoder.py
python
JSONEncoder.default
(self, o)
Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``).
[ "Implement", "this", "method", "in", "a", "subclass", "such", "that", "it", "returns", "a", "serializable", "object", "for", "o", "or", "calls", "the", "base", "implementation", "(", "to", "raise", "a", "TypeError", ")", "." ]
def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o) """ raise TypeError(f'Object of type {o.__class__.__name__} ' f'is not JSON serializable')
[ "def", "default", "(", "self", ",", "o", ")", ":", "raise", "TypeError", "(", "f'Object of type {o.__class__.__name__} '", "f'is not JSON serializable'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/json/encoder.py#L160-L180
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/lib/sessions.py
python
RamSession.release_lock
(self)
Release the lock on the currently-loaded session data.
Release the lock on the currently-loaded session data.
[ "Release", "the", "lock", "on", "the", "currently", "-", "loaded", "session", "data", "." ]
def release_lock(self): """Release the lock on the currently-loaded session data.""" self.locks[self.id].release() self.locked = False
[ "def", "release_lock", "(", "self", ")", ":", "self", ".", "locks", "[", "self", ".", "id", "]", ".", "release", "(", ")", "self", ".", "locked", "=", "False" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/sessions.py#L372-L375
Pay20Y/FOTS_TF
c42ea59a20c28d506fee35cfb4c553b0cb20eee8
nets/resnet_utils.py
python
stack_blocks_dense
(net, blocks, output_stride=None, outputs_collections=None)
return net
Stacks ResNet `Blocks` and controls output feature density. First, this function creates scopes for the ResNet in the form of 'block_name/unit_1', 'block_name/unit_2', etc. Second, this function allows the user to explicitly control the ResNet output_stride, which is the ratio of the input to output spatial resolution. This is useful for dense prediction tasks such as semantic segmentation or object detection. Most ResNets consist of 4 ResNet blocks and subsample the activations by a factor of 2 when transitioning between consecutive ResNet blocks. This results to a nominal ResNet output_stride equal to 8. If we set the output_stride to half the nominal network stride (e.g., output_stride=4), then we compute responses twice. Control of the output feature density is implemented by atrous convolution. Args: net: A `Tensor` of size [batch, height, width, channels]. blocks: A list of length equal to the number of ResNet `Blocks`. Each element is a ResNet `Block` object describing the units in the `Block`. output_stride: If `None`, then the output will be computed at the nominal network stride. If output_stride is not `None`, it specifies the requested ratio of input to output spatial resolution, which needs to be equal to the product of unit strides from the start up to some level of the ResNet. For example, if the ResNet employs units with strides 1, 2, 1, 3, 4, 1, then valid values for the output_stride are 1, 2, 6, 24 or None (which is equivalent to output_stride=24). outputs_collections: Collection to add the ResNet block outputs. Returns: net: Output tensor with stride equal to the specified output_stride. Raises: ValueError: If the target output_stride is not valid.
Stacks ResNet `Blocks` and controls output feature density.
[ "Stacks", "ResNet", "Blocks", "and", "controls", "output", "feature", "density", "." ]
def stack_blocks_dense(net, blocks, output_stride=None, outputs_collections=None): """Stacks ResNet `Blocks` and controls output feature density. First, this function creates scopes for the ResNet in the form of 'block_name/unit_1', 'block_name/unit_2', etc. Second, this function allows the user to explicitly control the ResNet output_stride, which is the ratio of the input to output spatial resolution. This is useful for dense prediction tasks such as semantic segmentation or object detection. Most ResNets consist of 4 ResNet blocks and subsample the activations by a factor of 2 when transitioning between consecutive ResNet blocks. This results to a nominal ResNet output_stride equal to 8. If we set the output_stride to half the nominal network stride (e.g., output_stride=4), then we compute responses twice. Control of the output feature density is implemented by atrous convolution. Args: net: A `Tensor` of size [batch, height, width, channels]. blocks: A list of length equal to the number of ResNet `Blocks`. Each element is a ResNet `Block` object describing the units in the `Block`. output_stride: If `None`, then the output will be computed at the nominal network stride. If output_stride is not `None`, it specifies the requested ratio of input to output spatial resolution, which needs to be equal to the product of unit strides from the start up to some level of the ResNet. For example, if the ResNet employs units with strides 1, 2, 1, 3, 4, 1, then valid values for the output_stride are 1, 2, 6, 24 or None (which is equivalent to output_stride=24). outputs_collections: Collection to add the ResNet block outputs. Returns: net: Output tensor with stride equal to the specified output_stride. Raises: ValueError: If the target output_stride is not valid. """ # The current_stride variable keeps track of the effective stride of the # activations. This allows us to invoke atrous convolution whenever applying # the next residual unit would result in the activations having stride larger # than the target output_stride. current_stride = 1 # The atrous convolution rate parameter. rate = 1 for block in blocks: with tf.variable_scope(block.scope, 'block', [net]) as sc: for i, unit in enumerate(block.args): if output_stride is not None and current_stride > output_stride: raise ValueError('The target output_stride cannot be reached.') with tf.variable_scope('unit_%d' % (i + 1), values=[net]): unit_depth, unit_depth_bottleneck, unit_stride = unit # If we have reached the target output_stride, then we need to employ # atrous convolution with stride=1 and multiply the atrous rate by the # current unit's stride for use in subsequent layers. if output_stride is not None and current_stride == output_stride: net = block.unit_fn(net, depth=unit_depth, depth_bottleneck=unit_depth_bottleneck, stride=1, rate=rate) rate *= unit_stride else: net = block.unit_fn(net, depth=unit_depth, depth_bottleneck=unit_depth_bottleneck, stride=unit_stride, rate=1) current_stride *= unit_stride print(sc.name, net.shape) net = slim.utils.collect_named_outputs(outputs_collections, sc.name, net) if output_stride is not None and current_stride != output_stride: raise ValueError('The target output_stride cannot be reached.') return net
[ "def", "stack_blocks_dense", "(", "net", ",", "blocks", ",", "output_stride", "=", "None", ",", "outputs_collections", "=", "None", ")", ":", "# The current_stride variable keeps track of the effective stride of the", "# activations. This allows us to invoke atrous convolution whenever applying", "# the next residual unit would result in the activations having stride larger", "# than the target output_stride.", "current_stride", "=", "1", "# The atrous convolution rate parameter.", "rate", "=", "1", "for", "block", "in", "blocks", ":", "with", "tf", ".", "variable_scope", "(", "block", ".", "scope", ",", "'block'", ",", "[", "net", "]", ")", "as", "sc", ":", "for", "i", ",", "unit", "in", "enumerate", "(", "block", ".", "args", ")", ":", "if", "output_stride", "is", "not", "None", "and", "current_stride", ">", "output_stride", ":", "raise", "ValueError", "(", "'The target output_stride cannot be reached.'", ")", "with", "tf", ".", "variable_scope", "(", "'unit_%d'", "%", "(", "i", "+", "1", ")", ",", "values", "=", "[", "net", "]", ")", ":", "unit_depth", ",", "unit_depth_bottleneck", ",", "unit_stride", "=", "unit", "# If we have reached the target output_stride, then we need to employ", "# atrous convolution with stride=1 and multiply the atrous rate by the", "# current unit's stride for use in subsequent layers.", "if", "output_stride", "is", "not", "None", "and", "current_stride", "==", "output_stride", ":", "net", "=", "block", ".", "unit_fn", "(", "net", ",", "depth", "=", "unit_depth", ",", "depth_bottleneck", "=", "unit_depth_bottleneck", ",", "stride", "=", "1", ",", "rate", "=", "rate", ")", "rate", "*=", "unit_stride", "else", ":", "net", "=", "block", ".", "unit_fn", "(", "net", ",", "depth", "=", "unit_depth", ",", "depth_bottleneck", "=", "unit_depth_bottleneck", ",", "stride", "=", "unit_stride", ",", "rate", "=", "1", ")", "current_stride", "*=", "unit_stride", "print", "(", "sc", ".", "name", ",", "net", ".", "shape", ")", "net", "=", "slim", ".", "utils", ".", "collect_named_outputs", "(", "outputs_collections", ",", "sc", ".", "name", ",", "net", ")", "if", "output_stride", "is", "not", "None", "and", "current_stride", "!=", "output_stride", ":", "raise", "ValueError", "(", "'The target output_stride cannot be reached.'", ")", "return", "net" ]
https://github.com/Pay20Y/FOTS_TF/blob/c42ea59a20c28d506fee35cfb4c553b0cb20eee8/nets/resnet_utils.py#L126-L206
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
red_black_tree/red_black_tree.py
python
RedBlackTree.sibling
(node)
return node.parent.left
returns sibling of given node
returns sibling of given node
[ "returns", "sibling", "of", "given", "node" ]
def sibling(node): """ returns sibling of given node """ if node is None or node.parent is None: return None if node is node.parent.left: return node.parent.right return node.parent.left
[ "def", "sibling", "(", "node", ")", ":", "if", "node", "is", "None", "or", "node", ".", "parent", "is", "None", ":", "return", "None", "if", "node", "is", "node", ".", "parent", ".", "left", ":", "return", "node", ".", "parent", ".", "right", "return", "node", ".", "parent", ".", "left" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/red_black_tree/red_black_tree.py#L195-L202
baoboa/pyqt5
11d5f43bc6f213d9d60272f3954a0048569cfc7c
examples/ipc/sharedmemory/sharedmemory.py
python
Dialog.loadFromFile
(self)
This slot function is called when the "Load Image From File..." button is pressed on the firs Dialog process. First, it tests whether the process is already connected to a shared memory segment and, if so, detaches from that segment. This ensures that we always start the example from the beginning if we run it multiple times with the same two Dialog processes. After detaching from an existing shared memory segment, the user is prompted to select an image file. The selected file is loaded into a QImage. The QImage is displayed in the Dialog and streamed into a QBuffer with a QDataStream. Next, it gets a new shared memory segment from the system big enough to hold the image data in the QBuffer, and it locks the segment to prevent the second Dialog process from accessing it. Then it copies the image from the QBuffer into the shared memory segment. Finally, it unlocks the shared memory segment so the second Dialog process can access it. After self function runs, the user is expected to press the "Load Image from Shared Memory" button on the second Dialog process.
This slot function is called when the "Load Image From File..." button is pressed on the firs Dialog process. First, it tests whether the process is already connected to a shared memory segment and, if so, detaches from that segment. This ensures that we always start the example from the beginning if we run it multiple times with the same two Dialog processes. After detaching from an existing shared memory segment, the user is prompted to select an image file. The selected file is loaded into a QImage. The QImage is displayed in the Dialog and streamed into a QBuffer with a QDataStream. Next, it gets a new shared memory segment from the system big enough to hold the image data in the QBuffer, and it locks the segment to prevent the second Dialog process from accessing it. Then it copies the image from the QBuffer into the shared memory segment. Finally, it unlocks the shared memory segment so the second Dialog process can access it. After self function runs, the user is expected to press the "Load Image from Shared Memory" button on the second Dialog process.
[ "This", "slot", "function", "is", "called", "when", "the", "Load", "Image", "From", "File", "...", "button", "is", "pressed", "on", "the", "firs", "Dialog", "process", ".", "First", "it", "tests", "whether", "the", "process", "is", "already", "connected", "to", "a", "shared", "memory", "segment", "and", "if", "so", "detaches", "from", "that", "segment", ".", "This", "ensures", "that", "we", "always", "start", "the", "example", "from", "the", "beginning", "if", "we", "run", "it", "multiple", "times", "with", "the", "same", "two", "Dialog", "processes", ".", "After", "detaching", "from", "an", "existing", "shared", "memory", "segment", "the", "user", "is", "prompted", "to", "select", "an", "image", "file", ".", "The", "selected", "file", "is", "loaded", "into", "a", "QImage", ".", "The", "QImage", "is", "displayed", "in", "the", "Dialog", "and", "streamed", "into", "a", "QBuffer", "with", "a", "QDataStream", ".", "Next", "it", "gets", "a", "new", "shared", "memory", "segment", "from", "the", "system", "big", "enough", "to", "hold", "the", "image", "data", "in", "the", "QBuffer", "and", "it", "locks", "the", "segment", "to", "prevent", "the", "second", "Dialog", "process", "from", "accessing", "it", ".", "Then", "it", "copies", "the", "image", "from", "the", "QBuffer", "into", "the", "shared", "memory", "segment", ".", "Finally", "it", "unlocks", "the", "shared", "memory", "segment", "so", "the", "second", "Dialog", "process", "can", "access", "it", ".", "After", "self", "function", "runs", "the", "user", "is", "expected", "to", "press", "the", "Load", "Image", "from", "Shared", "Memory", "button", "on", "the", "second", "Dialog", "process", "." ]
def loadFromFile(self): """ This slot function is called when the "Load Image From File..." button is pressed on the firs Dialog process. First, it tests whether the process is already connected to a shared memory segment and, if so, detaches from that segment. This ensures that we always start the example from the beginning if we run it multiple times with the same two Dialog processes. After detaching from an existing shared memory segment, the user is prompted to select an image file. The selected file is loaded into a QImage. The QImage is displayed in the Dialog and streamed into a QBuffer with a QDataStream. Next, it gets a new shared memory segment from the system big enough to hold the image data in the QBuffer, and it locks the segment to prevent the second Dialog process from accessing it. Then it copies the image from the QBuffer into the shared memory segment. Finally, it unlocks the shared memory segment so the second Dialog process can access it. After self function runs, the user is expected to press the "Load Image from Shared Memory" button on the second Dialog process. """ if self.sharedMemory.isAttached(): self.detach() self.ui.label.setText("Select an image file") fileName, _ = QFileDialog.getOpenFileName(self, None, None, "Images (*.png *.xpm *.jpg)") image = QImage() if not image.load(fileName): self.ui.label.setText( "Selected file is not an image, please select another.") return self.ui.label.setPixmap(QPixmap.fromImage(image)) # Load into shared memory. buf = QBuffer() buf.open(QBuffer.ReadWrite) out = QDataStream(buf) out << image size = buf.size() if not self.sharedMemory.create(size): self.ui.label.setText("Unable to create shared memory segment.") return size = min(self.sharedMemory.size(), size) self.sharedMemory.lock() # Copy image data from buf into shared memory area. self.sharedMemory.data()[:size] = buf.data()[:size] self.sharedMemory.unlock()
[ "def", "loadFromFile", "(", "self", ")", ":", "if", "self", ".", "sharedMemory", ".", "isAttached", "(", ")", ":", "self", ".", "detach", "(", ")", "self", ".", "ui", ".", "label", ".", "setText", "(", "\"Select an image file\"", ")", "fileName", ",", "_", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "None", ",", "None", ",", "\"Images (*.png *.xpm *.jpg)\"", ")", "image", "=", "QImage", "(", ")", "if", "not", "image", ".", "load", "(", "fileName", ")", ":", "self", ".", "ui", ".", "label", ".", "setText", "(", "\"Selected file is not an image, please select another.\"", ")", "return", "self", ".", "ui", ".", "label", ".", "setPixmap", "(", "QPixmap", ".", "fromImage", "(", "image", ")", ")", "# Load into shared memory.", "buf", "=", "QBuffer", "(", ")", "buf", ".", "open", "(", "QBuffer", ".", "ReadWrite", ")", "out", "=", "QDataStream", "(", "buf", ")", "out", "<<", "image", "size", "=", "buf", ".", "size", "(", ")", "if", "not", "self", ".", "sharedMemory", ".", "create", "(", "size", ")", ":", "self", ".", "ui", ".", "label", ".", "setText", "(", "\"Unable to create shared memory segment.\"", ")", "return", "size", "=", "min", "(", "self", ".", "sharedMemory", ".", "size", "(", ")", ",", "size", ")", "self", ".", "sharedMemory", ".", "lock", "(", ")", "# Copy image data from buf into shared memory area.", "self", ".", "sharedMemory", ".", "data", "(", ")", "[", ":", "size", "]", "=", "buf", ".", "data", "(", ")", "[", ":", "size", "]", "self", ".", "sharedMemory", ".", "unlock", "(", ")" ]
https://github.com/baoboa/pyqt5/blob/11d5f43bc6f213d9d60272f3954a0048569cfc7c/examples/ipc/sharedmemory/sharedmemory.py#L84-L133