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
netease-youdao/hex
d7b8773dae8dde63f3807cef1d48c017077db727
tools/patch_util.py
python
from_file
(filename)
return patch
read and parse patch file return PatchInfo() object
read and parse patch file return PatchInfo() object
[ "read", "and", "parse", "patch", "file", "return", "PatchInfo", "()", "object" ]
def from_file(filename): """ read and parse patch file return PatchInfo() object """ info("reading patch from file %s" % filename) fp = open(filename, "rb") patch = PatchInfo(fp) fp.close() return patch
[ "def", "from_file", "(", "filename", ")", ":", "info", "(", "\"reading patch from file %s\"", "%", "filename", ")", "fp", "=", "open", "(", "filename", ",", "\"rb\"", ")", "patch", "=", "PatchInfo", "(", "fp", ")", "fp", ".", "close", "(", ")", "return", "patch" ]
https://github.com/netease-youdao/hex/blob/d7b8773dae8dde63f3807cef1d48c017077db727/tools/patch_util.py#L39-L48
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/importlib-metadata/py2/importlib_metadata/__init__.py
python
Distribution._convert_egg_info_reqs_to_simple_reqs
(sections)
Historically, setuptools would solicit and store 'extra' requirements, including those with environment markers, in separate sections. More modern tools expect each dependency to be defined separately, with any relevant extras and environment markers attached directly to that requirement. This method converts the former to the latter. See _test_deps_from_requires_text for an example.
Historically, setuptools would solicit and store 'extra' requirements, including those with environment markers, in separate sections. More modern tools expect each dependency to be defined separately, with any relevant extras and environment markers attached directly to that requirement. This method converts the former to the latter. See _test_deps_from_requires_text for an example.
[ "Historically", "setuptools", "would", "solicit", "and", "store", "extra", "requirements", "including", "those", "with", "environment", "markers", "in", "separate", "sections", ".", "More", "modern", "tools", "expect", "each", "dependency", "to", "be", "defined", "separately", "with", "any", "relevant", "extras", "and", "environment", "markers", "attached", "directly", "to", "that", "requirement", ".", "This", "method", "converts", "the", "former", "to", "the", "latter", ".", "See", "_test_deps_from_requires_text", "for", "an", "example", "." ]
def _convert_egg_info_reqs_to_simple_reqs(sections): """ Historically, setuptools would solicit and store 'extra' requirements, including those with environment markers, in separate sections. More modern tools expect each dependency to be defined separately, with any relevant extras and environment markers attached directly to that requirement. This method converts the former to the latter. See _test_deps_from_requires_text for an example. """ def make_condition(name): return name and 'extra == "{name}"'.format(name=name) def parse_condition(section): section = section or '' extra, sep, markers = section.partition(':') if extra and markers: markers = '({markers})'.format(markers=markers) conditions = list(filter(None, [markers, make_condition(extra)])) return '; ' + ' and '.join(conditions) if conditions else '' for section, deps in sections.items(): for dep in deps: yield dep + parse_condition(section)
[ "def", "_convert_egg_info_reqs_to_simple_reqs", "(", "sections", ")", ":", "def", "make_condition", "(", "name", ")", ":", "return", "name", "and", "'extra == \"{name}\"'", ".", "format", "(", "name", "=", "name", ")", "def", "parse_condition", "(", "section", ")", ":", "section", "=", "section", "or", "''", "extra", ",", "sep", ",", "markers", "=", "section", ".", "partition", "(", "':'", ")", "if", "extra", "and", "markers", ":", "markers", "=", "'({markers})'", ".", "format", "(", "markers", "=", "markers", ")", "conditions", "=", "list", "(", "filter", "(", "None", ",", "[", "markers", ",", "make_condition", "(", "extra", ")", "]", ")", ")", "return", "'; '", "+", "' and '", ".", "join", "(", "conditions", ")", "if", "conditions", "else", "''", "for", "section", ",", "deps", "in", "sections", ".", "items", "(", ")", ":", "for", "dep", "in", "deps", ":", "yield", "dep", "+", "parse_condition", "(", "section", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/importlib-metadata/py2/importlib_metadata/__init__.py#L366-L389
ideawu/ssdb
f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4
deps/cpy/antlr3/tree.py
python
Tree.freshenParentAndChildIndexes
(self)
Set the parent and child index values for all children
Set the parent and child index values for all children
[ "Set", "the", "parent", "and", "child", "index", "values", "for", "all", "children" ]
def freshenParentAndChildIndexes(self): """Set the parent and child index values for all children""" raise NotImplementedError
[ "def", "freshenParentAndChildIndexes", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/tree.py#L142-L145
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py
python
_detect_xgettext
(env)
return None
Detects *xgettext(1)* binary
Detects *xgettext(1)* binary
[ "Detects", "*", "xgettext", "(", "1", ")", "*", "binary" ]
def _detect_xgettext(env): """ Detects *xgettext(1)* binary """ if env.has_key('XGETTEXT'): return env['XGETTEXT'] xgettext = env.Detect('xgettext'); if xgettext: return xgettext raise SCons.Errors.StopError(XgettextNotFound,"Could not detect xgettext") return None
[ "def", "_detect_xgettext", "(", "env", ")", ":", "if", "env", ".", "has_key", "(", "'XGETTEXT'", ")", ":", "return", "env", "[", "'XGETTEXT'", "]", "xgettext", "=", "env", ".", "Detect", "(", "'xgettext'", ")", "if", "xgettext", ":", "return", "xgettext", "raise", "SCons", ".", "Errors", ".", "StopError", "(", "XgettextNotFound", ",", "\"Could not detect xgettext\"", ")", "return", "None" ]
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/GettextCommon.py#L349-L357
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/platform/profiler/android_profiling_helper.py
python
CreateSymFs
(device, symfs_dir, libraries, use_symlinks=True)
return output_kallsyms
Creates a symfs directory to be used for symbolizing profiles. Prepares a set of files ("symfs") to be used with profilers such as perf for converting binary addresses into human readable function names. Args: device: DeviceUtils instance identifying the target device. symfs_dir: Path where the symfs should be created. libraries: Set of library file names that should be included in the symfs. use_symlinks: If True, link instead of copy unstripped libraries into the symfs. This will speed up the operation, but the resulting symfs will no longer be valid if the linked files are modified, e.g., by rebuilding. Returns: The absolute path to the kernel symbols within the created symfs.
Creates a symfs directory to be used for symbolizing profiles.
[ "Creates", "a", "symfs", "directory", "to", "be", "used", "for", "symbolizing", "profiles", "." ]
def CreateSymFs(device, symfs_dir, libraries, use_symlinks=True): """Creates a symfs directory to be used for symbolizing profiles. Prepares a set of files ("symfs") to be used with profilers such as perf for converting binary addresses into human readable function names. Args: device: DeviceUtils instance identifying the target device. symfs_dir: Path where the symfs should be created. libraries: Set of library file names that should be included in the symfs. use_symlinks: If True, link instead of copy unstripped libraries into the symfs. This will speed up the operation, but the resulting symfs will no longer be valid if the linked files are modified, e.g., by rebuilding. Returns: The absolute path to the kernel symbols within the created symfs. """ logging.info('Building symfs into %s.' % symfs_dir) for lib in libraries: device_dir = os.path.dirname(lib) output_dir = os.path.join(symfs_dir, device_dir[1:]) if not os.path.exists(output_dir): os.makedirs(output_dir) output_lib = os.path.join(output_dir, os.path.basename(lib)) if lib.startswith('/data/app'): # If this is our own library instead of a system one, look for a matching # unstripped library under the out directory. unstripped_host_lib = _FindMatchingUnstrippedLibraryOnHost(device, lib) if not unstripped_host_lib: logging.warning('Could not find symbols for %s.' % lib) logging.warning('Is the correct output directory selected ' '(CHROMIUM_OUTPUT_DIR)? Did you install the APK after ' 'building?') continue if use_symlinks: if os.path.lexists(output_lib): os.remove(output_lib) os.symlink(os.path.abspath(unstripped_host_lib), output_lib) # Copy the unstripped library only if it has been changed to avoid the # delay. elif not _FileMetadataMatches(unstripped_host_lib, output_lib): logging.info('Copying %s to %s' % (unstripped_host_lib, output_lib)) shutil.copy2(unstripped_host_lib, output_lib) else: # Otherwise save a copy of the stripped system library under the symfs so # the profiler can at least use the public symbols of that library. To # speed things up, only pull files that don't match copies we already # have in the symfs. if not os.path.exists(output_lib): pull = True else: host_md5sums = md5sum.CalculateHostMd5Sums([output_lib]) try: device_md5sums = md5sum.CalculateDeviceMd5Sums([lib], device) except: logging.exception('New exception caused by DeviceUtils conversion') raise pull = True if host_md5sums and device_md5sums and output_lib in host_md5sums \ and lib in device_md5sums: pull = host_md5sums[output_lib] != device_md5sums[lib] if pull: logging.info('Pulling %s to %s', lib, output_lib) device.PullFile(lib, output_lib) # Also pull a copy of the kernel symbols. output_kallsyms = os.path.join(symfs_dir, 'kallsyms') if not os.path.exists(output_kallsyms): device.PullFile('/proc/kallsyms', output_kallsyms) return output_kallsyms
[ "def", "CreateSymFs", "(", "device", ",", "symfs_dir", ",", "libraries", ",", "use_symlinks", "=", "True", ")", ":", "logging", ".", "info", "(", "'Building symfs into %s.'", "%", "symfs_dir", ")", "for", "lib", "in", "libraries", ":", "device_dir", "=", "os", ".", "path", ".", "dirname", "(", "lib", ")", "output_dir", "=", "os", ".", "path", ".", "join", "(", "symfs_dir", ",", "device_dir", "[", "1", ":", "]", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "output_dir", ")", ":", "os", ".", "makedirs", "(", "output_dir", ")", "output_lib", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "os", ".", "path", ".", "basename", "(", "lib", ")", ")", "if", "lib", ".", "startswith", "(", "'/data/app'", ")", ":", "# If this is our own library instead of a system one, look for a matching", "# unstripped library under the out directory.", "unstripped_host_lib", "=", "_FindMatchingUnstrippedLibraryOnHost", "(", "device", ",", "lib", ")", "if", "not", "unstripped_host_lib", ":", "logging", ".", "warning", "(", "'Could not find symbols for %s.'", "%", "lib", ")", "logging", ".", "warning", "(", "'Is the correct output directory selected '", "'(CHROMIUM_OUTPUT_DIR)? Did you install the APK after '", "'building?'", ")", "continue", "if", "use_symlinks", ":", "if", "os", ".", "path", ".", "lexists", "(", "output_lib", ")", ":", "os", ".", "remove", "(", "output_lib", ")", "os", ".", "symlink", "(", "os", ".", "path", ".", "abspath", "(", "unstripped_host_lib", ")", ",", "output_lib", ")", "# Copy the unstripped library only if it has been changed to avoid the", "# delay.", "elif", "not", "_FileMetadataMatches", "(", "unstripped_host_lib", ",", "output_lib", ")", ":", "logging", ".", "info", "(", "'Copying %s to %s'", "%", "(", "unstripped_host_lib", ",", "output_lib", ")", ")", "shutil", ".", "copy2", "(", "unstripped_host_lib", ",", "output_lib", ")", "else", ":", "# Otherwise save a copy of the stripped system library under the symfs so", "# the profiler can at least use the public symbols of that library. To", "# speed things up, only pull files that don't match copies we already", "# have in the symfs.", "if", "not", "os", ".", "path", ".", "exists", "(", "output_lib", ")", ":", "pull", "=", "True", "else", ":", "host_md5sums", "=", "md5sum", ".", "CalculateHostMd5Sums", "(", "[", "output_lib", "]", ")", "try", ":", "device_md5sums", "=", "md5sum", ".", "CalculateDeviceMd5Sums", "(", "[", "lib", "]", ",", "device", ")", "except", ":", "logging", ".", "exception", "(", "'New exception caused by DeviceUtils conversion'", ")", "raise", "pull", "=", "True", "if", "host_md5sums", "and", "device_md5sums", "and", "output_lib", "in", "host_md5sums", "and", "lib", "in", "device_md5sums", ":", "pull", "=", "host_md5sums", "[", "output_lib", "]", "!=", "device_md5sums", "[", "lib", "]", "if", "pull", ":", "logging", ".", "info", "(", "'Pulling %s to %s'", ",", "lib", ",", "output_lib", ")", "device", ".", "PullFile", "(", "lib", ",", "output_lib", ")", "# Also pull a copy of the kernel symbols.", "output_kallsyms", "=", "os", ".", "path", ".", "join", "(", "symfs_dir", ",", "'kallsyms'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "output_kallsyms", ")", ":", "device", ".", "PullFile", "(", "'/proc/kallsyms'", ",", "output_kallsyms", ")", "return", "output_kallsyms" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/platform/profiler/android_profiling_helper.py#L190-L263
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/rook.py
python
task
(ctx, config)
Deploy rook-ceph cluster tasks: - kubeadm: - rook: branch: wip-foo spec: mon: count: 1 The spec item is deep-merged against the cluster.yaml. The branch, sha1, or image items are used to determine the Ceph container image.
Deploy rook-ceph cluster
[ "Deploy", "rook", "-", "ceph", "cluster" ]
def task(ctx, config): """ Deploy rook-ceph cluster tasks: - kubeadm: - rook: branch: wip-foo spec: mon: count: 1 The spec item is deep-merged against the cluster.yaml. The branch, sha1, or image items are used to determine the Ceph container image. """ if not config: config = {} assert isinstance(config, dict), \ "task only supports a dictionary for configuration" log.info('Rook start') overrides = ctx.config.get('overrides', {}) teuthology.deep_merge(config, overrides.get('ceph', {})) teuthology.deep_merge(config, overrides.get('rook', {})) log.info('Config: ' + str(config)) # set up cluster context if not hasattr(ctx, 'rook'): ctx.rook = {} if 'cluster' not in config: config['cluster'] = 'ceph' cluster_name = config['cluster'] if cluster_name not in ctx.rook: ctx.rook[cluster_name] = argparse.Namespace() ctx.rook[cluster_name].remote = list(ctx.cluster.remotes.keys())[0] # image teuth_defaults = teuth_config.get('defaults', {}) cephadm_defaults = teuth_defaults.get('cephadm', {}) containers_defaults = cephadm_defaults.get('containers', {}) container_image_name = containers_defaults.get('image', None) if 'image' in config: ctx.rook[cluster_name].image = config.get('image') else: sha1 = config.get('sha1') flavor = config.get('flavor', 'default') if sha1: if flavor == "crimson": ctx.rook[cluster_name].image = container_image_name + ':' + sha1 + '-' + flavor else: ctx.rook[cluster_name].image = container_image_name + ':' + sha1 else: # hmm, fall back to branch? branch = config.get('branch', 'master') ctx.rook[cluster_name].image = container_image_name + ':' + branch log.info('Ceph image is %s' % ctx.rook[cluster_name].image) with contextutil.nested( lambda: rook_operator(ctx, config), lambda: ceph_log(ctx, config), lambda: rook_cluster(ctx, config), lambda: rook_toolbox(ctx, config), lambda: wait_for_orch(ctx, config), lambda: rook_post_config(ctx, config), lambda: wait_for_osds(ctx, config), lambda: ceph_config_keyring(ctx, config), lambda: ceph_clients(ctx, config), ): if not hasattr(ctx, 'managers'): ctx.managers = {} ctx.managers[cluster_name] = CephManager( ctx.rook[cluster_name].remote, ctx=ctx, logger=log.getChild('ceph_manager.' + cluster_name), cluster=cluster_name, rook=True, ) try: if config.get('wait-for-healthy', True): healthy(ctx=ctx, config=config) log.info('Rook complete, yielding') yield finally: to_remove = [] ret = _shell(ctx, config, ['ceph', 'orch', 'ls', '-f', 'json'], stdout=BytesIO()) if ret.exitstatus == 0: r = json.loads(ret.stdout.getvalue().decode('utf-8')) for service in r: if service['service_type'] in ['rgw', 'mds', 'nfs', 'rbd-mirror']: _shell(ctx, config, ['ceph', 'orch', 'rm', service['service_name']]) to_remove.append(service['service_name']) with safe_while(sleep=10, tries=90, action="waiting for service removal") as proceed: while proceed(): ret = _shell(ctx, config, ['ceph', 'orch', 'ls', '-f', 'json'], stdout=BytesIO()) if ret.exitstatus == 0: r = json.loads(ret.stdout.getvalue().decode('utf-8')) still_up = [service['service_name'] for service in r] matches = set(still_up).intersection(to_remove) if not matches: break log.info('Tearing down rook')
[ "def", "task", "(", "ctx", ",", "config", ")", ":", "if", "not", "config", ":", "config", "=", "{", "}", "assert", "isinstance", "(", "config", ",", "dict", ")", ",", "\"task only supports a dictionary for configuration\"", "log", ".", "info", "(", "'Rook start'", ")", "overrides", "=", "ctx", ".", "config", ".", "get", "(", "'overrides'", ",", "{", "}", ")", "teuthology", ".", "deep_merge", "(", "config", ",", "overrides", ".", "get", "(", "'ceph'", ",", "{", "}", ")", ")", "teuthology", ".", "deep_merge", "(", "config", ",", "overrides", ".", "get", "(", "'rook'", ",", "{", "}", ")", ")", "log", ".", "info", "(", "'Config: '", "+", "str", "(", "config", ")", ")", "# set up cluster context", "if", "not", "hasattr", "(", "ctx", ",", "'rook'", ")", ":", "ctx", ".", "rook", "=", "{", "}", "if", "'cluster'", "not", "in", "config", ":", "config", "[", "'cluster'", "]", "=", "'ceph'", "cluster_name", "=", "config", "[", "'cluster'", "]", "if", "cluster_name", "not", "in", "ctx", ".", "rook", ":", "ctx", ".", "rook", "[", "cluster_name", "]", "=", "argparse", ".", "Namespace", "(", ")", "ctx", ".", "rook", "[", "cluster_name", "]", ".", "remote", "=", "list", "(", "ctx", ".", "cluster", ".", "remotes", ".", "keys", "(", ")", ")", "[", "0", "]", "# image", "teuth_defaults", "=", "teuth_config", ".", "get", "(", "'defaults'", ",", "{", "}", ")", "cephadm_defaults", "=", "teuth_defaults", ".", "get", "(", "'cephadm'", ",", "{", "}", ")", "containers_defaults", "=", "cephadm_defaults", ".", "get", "(", "'containers'", ",", "{", "}", ")", "container_image_name", "=", "containers_defaults", ".", "get", "(", "'image'", ",", "None", ")", "if", "'image'", "in", "config", ":", "ctx", ".", "rook", "[", "cluster_name", "]", ".", "image", "=", "config", ".", "get", "(", "'image'", ")", "else", ":", "sha1", "=", "config", ".", "get", "(", "'sha1'", ")", "flavor", "=", "config", ".", "get", "(", "'flavor'", ",", "'default'", ")", "if", "sha1", ":", "if", "flavor", "==", "\"crimson\"", ":", "ctx", ".", "rook", "[", "cluster_name", "]", ".", "image", "=", "container_image_name", "+", "':'", "+", "sha1", "+", "'-'", "+", "flavor", "else", ":", "ctx", ".", "rook", "[", "cluster_name", "]", ".", "image", "=", "container_image_name", "+", "':'", "+", "sha1", "else", ":", "# hmm, fall back to branch?", "branch", "=", "config", ".", "get", "(", "'branch'", ",", "'master'", ")", "ctx", ".", "rook", "[", "cluster_name", "]", ".", "image", "=", "container_image_name", "+", "':'", "+", "branch", "log", ".", "info", "(", "'Ceph image is %s'", "%", "ctx", ".", "rook", "[", "cluster_name", "]", ".", "image", ")", "with", "contextutil", ".", "nested", "(", "lambda", ":", "rook_operator", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "ceph_log", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "rook_cluster", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "rook_toolbox", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "wait_for_orch", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "rook_post_config", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "wait_for_osds", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "ceph_config_keyring", "(", "ctx", ",", "config", ")", ",", "lambda", ":", "ceph_clients", "(", "ctx", ",", "config", ")", ",", ")", ":", "if", "not", "hasattr", "(", "ctx", ",", "'managers'", ")", ":", "ctx", ".", "managers", "=", "{", "}", "ctx", ".", "managers", "[", "cluster_name", "]", "=", "CephManager", "(", "ctx", ".", "rook", "[", "cluster_name", "]", ".", "remote", ",", "ctx", "=", "ctx", ",", "logger", "=", "log", ".", "getChild", "(", "'ceph_manager.'", "+", "cluster_name", ")", ",", "cluster", "=", "cluster_name", ",", "rook", "=", "True", ",", ")", "try", ":", "if", "config", ".", "get", "(", "'wait-for-healthy'", ",", "True", ")", ":", "healthy", "(", "ctx", "=", "ctx", ",", "config", "=", "config", ")", "log", ".", "info", "(", "'Rook complete, yielding'", ")", "yield", "finally", ":", "to_remove", "=", "[", "]", "ret", "=", "_shell", "(", "ctx", ",", "config", ",", "[", "'ceph'", ",", "'orch'", ",", "'ls'", ",", "'-f'", ",", "'json'", "]", ",", "stdout", "=", "BytesIO", "(", ")", ")", "if", "ret", ".", "exitstatus", "==", "0", ":", "r", "=", "json", ".", "loads", "(", "ret", ".", "stdout", ".", "getvalue", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", "for", "service", "in", "r", ":", "if", "service", "[", "'service_type'", "]", "in", "[", "'rgw'", ",", "'mds'", ",", "'nfs'", ",", "'rbd-mirror'", "]", ":", "_shell", "(", "ctx", ",", "config", ",", "[", "'ceph'", ",", "'orch'", ",", "'rm'", ",", "service", "[", "'service_name'", "]", "]", ")", "to_remove", ".", "append", "(", "service", "[", "'service_name'", "]", ")", "with", "safe_while", "(", "sleep", "=", "10", ",", "tries", "=", "90", ",", "action", "=", "\"waiting for service removal\"", ")", "as", "proceed", ":", "while", "proceed", "(", ")", ":", "ret", "=", "_shell", "(", "ctx", ",", "config", ",", "[", "'ceph'", ",", "'orch'", ",", "'ls'", ",", "'-f'", ",", "'json'", "]", ",", "stdout", "=", "BytesIO", "(", ")", ")", "if", "ret", ".", "exitstatus", "==", "0", ":", "r", "=", "json", ".", "loads", "(", "ret", ".", "stdout", ".", "getvalue", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", "still_up", "=", "[", "service", "[", "'service_name'", "]", "for", "service", "in", "r", "]", "matches", "=", "set", "(", "still_up", ")", ".", "intersection", "(", "to_remove", ")", "if", "not", "matches", ":", "break", "log", ".", "info", "(", "'Tearing down rook'", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/rook.py#L574-L677
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py
python
ElementInfo.isEmpty
(self)
return False
Returns true iff this element is declared to have an EMPTY content model.
Returns true iff this element is declared to have an EMPTY content model.
[ "Returns", "true", "iff", "this", "element", "is", "declared", "to", "have", "an", "EMPTY", "content", "model", "." ]
def isEmpty(self): """Returns true iff this element is declared to have an EMPTY content model.""" return False
[ "def", "isEmpty", "(", "self", ")", ":", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py#L1492-L1495
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_rainbow_dash.py
python
MinitaurRainbowDash._ResetPoseForLeg
(self, leg_id, add_constraint)
Reset the initial pose for the leg. Args: leg_id: It should be 0, 1, 2, or 3, which represents the leg at front_left, back_left, front_right and back_right. add_constraint: Whether to add a constraint at the joints of two feet.
Reset the initial pose for the leg.
[ "Reset", "the", "initial", "pose", "for", "the", "leg", "." ]
def _ResetPoseForLeg(self, leg_id, add_constraint): """Reset the initial pose for the leg. Args: leg_id: It should be 0, 1, 2, or 3, which represents the leg at front_left, back_left, front_right and back_right. add_constraint: Whether to add a constraint at the joints of two feet. """ knee_friction_force = 0 half_pi = math.pi / 2.0 knee_angle = -2.1834 leg_position = minitaur.LEG_POSITION[leg_id] self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["motor_" + leg_position + "L_joint"], self._motor_direction[2 * leg_id] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_joint"], self._motor_direction[2 * leg_id] * knee_angle, targetVelocity=0) self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["motor_" + leg_position + "R_joint"], self._motor_direction[2 * leg_id + 1] * half_pi, targetVelocity=0) self._pybullet_client.resetJointState(self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_joint"], self._motor_direction[2 * leg_id + 1] * knee_angle, targetVelocity=0) if add_constraint: if leg_id < 2: self._pybullet_client.createConstraint( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_joint"], self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_joint"], self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0], KNEE_CONSTRAINT_POINT_SHORT, KNEE_CONSTRAINT_POINT_LONG) else: self._pybullet_client.createConstraint( self.quadruped, self._joint_name_to_id["knee_" + leg_position + "R_joint"], self.quadruped, self._joint_name_to_id["knee_" + leg_position + "L_joint"], self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0], KNEE_CONSTRAINT_POINT_LONG, KNEE_CONSTRAINT_POINT_SHORT) if self._accurate_motor_model_enabled or self._pd_control_enabled: # Disable the default motor in pybullet. self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "L_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["motor_" + leg_position + "R_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) else: self._SetDesiredMotorAngleByName("motor_" + leg_position + "L_joint", self._motor_direction[2 * leg_id] * half_pi) self._SetDesiredMotorAngleByName("motor_" + leg_position + "R_joint", self._motor_direction[2 * leg_id + 1] * half_pi) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "L_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force) self._pybullet_client.setJointMotorControl2( bodyIndex=self.quadruped, jointIndex=(self._joint_name_to_id["knee_" + leg_position + "R_joint"]), controlMode=self._pybullet_client.VELOCITY_CONTROL, targetVelocity=0, force=knee_friction_force)
[ "def", "_ResetPoseForLeg", "(", "self", ",", "leg_id", ",", "add_constraint", ")", ":", "knee_friction_force", "=", "0", "half_pi", "=", "math", ".", "pi", "/", "2.0", "knee_angle", "=", "-", "2.1834", "leg_position", "=", "minitaur", ".", "LEG_POSITION", "[", "leg_id", "]", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "]", "*", "half_pi", ",", "targetVelocity", "=", "0", ")", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "]", "*", "knee_angle", ",", "targetVelocity", "=", "0", ")", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "+", "1", "]", "*", "half_pi", ",", "targetVelocity", "=", "0", ")", "self", ".", "_pybullet_client", ".", "resetJointState", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "+", "1", "]", "*", "knee_angle", ",", "targetVelocity", "=", "0", ")", "if", "add_constraint", ":", "if", "leg_id", "<", "2", ":", "self", ".", "_pybullet_client", ".", "createConstraint", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ",", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ",", "self", ".", "_pybullet_client", ".", "JOINT_POINT2POINT", ",", "[", "0", ",", "0", ",", "0", "]", ",", "KNEE_CONSTRAINT_POINT_SHORT", ",", "KNEE_CONSTRAINT_POINT_LONG", ")", "else", ":", "self", ".", "_pybullet_client", ".", "createConstraint", "(", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ",", "self", ".", "quadruped", ",", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ",", "self", ".", "_pybullet_client", ".", "JOINT_POINT2POINT", ",", "[", "0", ",", "0", ",", "0", "]", ",", "KNEE_CONSTRAINT_POINT_LONG", ",", "KNEE_CONSTRAINT_POINT_SHORT", ")", "if", "self", ".", "_accurate_motor_model_enabled", "or", "self", ".", "_pd_control_enabled", ":", "# Disable the default motor in pybullet.", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"motor_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")", "else", ":", "self", ".", "_SetDesiredMotorAngleByName", "(", "\"motor_\"", "+", "leg_position", "+", "\"L_joint\"", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "]", "*", "half_pi", ")", "self", ".", "_SetDesiredMotorAngleByName", "(", "\"motor_\"", "+", "leg_position", "+", "\"R_joint\"", ",", "self", ".", "_motor_direction", "[", "2", "*", "leg_id", "+", "1", "]", "*", "half_pi", ")", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"L_joint\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")", "self", ".", "_pybullet_client", ".", "setJointMotorControl2", "(", "bodyIndex", "=", "self", ".", "quadruped", ",", "jointIndex", "=", "(", "self", ".", "_joint_name_to_id", "[", "\"knee_\"", "+", "leg_position", "+", "\"R_joint\"", "]", ")", ",", "controlMode", "=", "self", ".", "_pybullet_client", ".", "VELOCITY_CONTROL", ",", "targetVelocity", "=", "0", ",", "force", "=", "knee_friction_force", ")" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_rainbow_dash.py#L91-L170
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PGArrayEditorDialog.SetDialogValue
(*args, **kwargs)
return _propgrid.PGArrayEditorDialog_SetDialogValue(*args, **kwargs)
SetDialogValue(self, wxVariant value)
SetDialogValue(self, wxVariant value)
[ "SetDialogValue", "(", "self", "wxVariant", "value", ")" ]
def SetDialogValue(*args, **kwargs): """SetDialogValue(self, wxVariant value)""" return _propgrid.PGArrayEditorDialog_SetDialogValue(*args, **kwargs)
[ "def", "SetDialogValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGArrayEditorDialog_SetDialogValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3190-L3192
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py
python
AddODflowTool.deactivate
(self)
This call by metacanvas signals that the tool has been deactivated and can now interact with metacanvas.
This call by metacanvas signals that the tool has been deactivated and can now interact with metacanvas.
[ "This", "call", "by", "metacanvas", "signals", "that", "the", "tool", "has", "been", "deactivated", "and", "can", "now", "interact", "with", "metacanvas", "." ]
def deactivate(self): """ This call by metacanvas signals that the tool has been deactivated and can now interact with metacanvas. """ self._is_active = False self.unhighlight_zones() self._canvas.draw() self.deactivate_select()
[ "def", "deactivate", "(", "self", ")", ":", "self", ".", "_is_active", "=", "False", "self", ".", "unhighlight_zones", "(", ")", "self", ".", "_canvas", ".", "draw", "(", ")", "self", ".", "deactivate_select", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/demand/origin_to_destination_wxgui.py#L369-L378
HKUST-Aerial-Robotics/Teach-Repeat-Replan
98505a7f74b13c8b501176ff838a38423dbef536
utils/pose_utils/build/devel/_setup_util.py
python
find_env_hooks
(environ, cmake_prefix_path)
return lines
Generate shell code with found environment hooks for the all workspaces.
Generate shell code with found environment hooks for the all workspaces.
[ "Generate", "shell", "code", "with", "found", "environment", "hooks", "for", "the", "all", "workspaces", "." ]
def find_env_hooks(environ, cmake_prefix_path): ''' Generate shell code with found environment hooks for the all workspaces. ''' lines = [] lines.append(comment('found environment hooks in workspaces')) generic_env_hooks = [] generic_env_hooks_workspace = [] specific_env_hooks = [] specific_env_hooks_workspace = [] generic_env_hooks_by_filename = {} specific_env_hooks_by_filename = {} generic_env_hook_ext = 'bat' if IS_WINDOWS else 'sh' specific_env_hook_ext = environ['CATKIN_SHELL'] if not IS_WINDOWS and 'CATKIN_SHELL' in environ and environ['CATKIN_SHELL'] else None # remove non-workspace paths workspaces = [path for path in cmake_prefix_path.split(os.pathsep) if path and os.path.isfile(os.path.join(path, CATKIN_MARKER_FILE))] for workspace in reversed(workspaces): env_hook_dir = os.path.join(workspace, 'etc', 'catkin', 'profile.d') if os.path.isdir(env_hook_dir): for filename in sorted(os.listdir(env_hook_dir)): if filename.endswith('.%s' % generic_env_hook_ext): # remove previous env hook with same name if present if filename in generic_env_hooks_by_filename: i = generic_env_hooks.index(generic_env_hooks_by_filename[filename]) generic_env_hooks.pop(i) generic_env_hooks_workspace.pop(i) # append env hook generic_env_hooks.append(os.path.join(env_hook_dir, filename)) generic_env_hooks_workspace.append(workspace) generic_env_hooks_by_filename[filename] = generic_env_hooks[-1] elif specific_env_hook_ext is not None and filename.endswith('.%s' % specific_env_hook_ext): # remove previous env hook with same name if present if filename in specific_env_hooks_by_filename: i = specific_env_hooks.index(specific_env_hooks_by_filename[filename]) specific_env_hooks.pop(i) specific_env_hooks_workspace.pop(i) # append env hook specific_env_hooks.append(os.path.join(env_hook_dir, filename)) specific_env_hooks_workspace.append(workspace) specific_env_hooks_by_filename[filename] = specific_env_hooks[-1] env_hooks = generic_env_hooks + specific_env_hooks env_hooks_workspace = generic_env_hooks_workspace + specific_env_hooks_workspace count = len(env_hooks) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_COUNT', count)) for i in range(count): lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d' % i, env_hooks[i])) lines.append(assignment('_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE' % i, env_hooks_workspace[i])) return lines
[ "def", "find_env_hooks", "(", "environ", ",", "cmake_prefix_path", ")", ":", "lines", "=", "[", "]", "lines", ".", "append", "(", "comment", "(", "'found environment hooks in workspaces'", ")", ")", "generic_env_hooks", "=", "[", "]", "generic_env_hooks_workspace", "=", "[", "]", "specific_env_hooks", "=", "[", "]", "specific_env_hooks_workspace", "=", "[", "]", "generic_env_hooks_by_filename", "=", "{", "}", "specific_env_hooks_by_filename", "=", "{", "}", "generic_env_hook_ext", "=", "'bat'", "if", "IS_WINDOWS", "else", "'sh'", "specific_env_hook_ext", "=", "environ", "[", "'CATKIN_SHELL'", "]", "if", "not", "IS_WINDOWS", "and", "'CATKIN_SHELL'", "in", "environ", "and", "environ", "[", "'CATKIN_SHELL'", "]", "else", "None", "# remove non-workspace paths", "workspaces", "=", "[", "path", "for", "path", "in", "cmake_prefix_path", ".", "split", "(", "os", ".", "pathsep", ")", "if", "path", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "CATKIN_MARKER_FILE", ")", ")", "]", "for", "workspace", "in", "reversed", "(", "workspaces", ")", ":", "env_hook_dir", "=", "os", ".", "path", ".", "join", "(", "workspace", ",", "'etc'", ",", "'catkin'", ",", "'profile.d'", ")", "if", "os", ".", "path", ".", "isdir", "(", "env_hook_dir", ")", ":", "for", "filename", "in", "sorted", "(", "os", ".", "listdir", "(", "env_hook_dir", ")", ")", ":", "if", "filename", ".", "endswith", "(", "'.%s'", "%", "generic_env_hook_ext", ")", ":", "# remove previous env hook with same name if present", "if", "filename", "in", "generic_env_hooks_by_filename", ":", "i", "=", "generic_env_hooks", ".", "index", "(", "generic_env_hooks_by_filename", "[", "filename", "]", ")", "generic_env_hooks", ".", "pop", "(", "i", ")", "generic_env_hooks_workspace", ".", "pop", "(", "i", ")", "# append env hook", "generic_env_hooks", ".", "append", "(", "os", ".", "path", ".", "join", "(", "env_hook_dir", ",", "filename", ")", ")", "generic_env_hooks_workspace", ".", "append", "(", "workspace", ")", "generic_env_hooks_by_filename", "[", "filename", "]", "=", "generic_env_hooks", "[", "-", "1", "]", "elif", "specific_env_hook_ext", "is", "not", "None", "and", "filename", ".", "endswith", "(", "'.%s'", "%", "specific_env_hook_ext", ")", ":", "# remove previous env hook with same name if present", "if", "filename", "in", "specific_env_hooks_by_filename", ":", "i", "=", "specific_env_hooks", ".", "index", "(", "specific_env_hooks_by_filename", "[", "filename", "]", ")", "specific_env_hooks", ".", "pop", "(", "i", ")", "specific_env_hooks_workspace", ".", "pop", "(", "i", ")", "# append env hook", "specific_env_hooks", ".", "append", "(", "os", ".", "path", ".", "join", "(", "env_hook_dir", ",", "filename", ")", ")", "specific_env_hooks_workspace", ".", "append", "(", "workspace", ")", "specific_env_hooks_by_filename", "[", "filename", "]", "=", "specific_env_hooks", "[", "-", "1", "]", "env_hooks", "=", "generic_env_hooks", "+", "specific_env_hooks", "env_hooks_workspace", "=", "generic_env_hooks_workspace", "+", "specific_env_hooks_workspace", "count", "=", "len", "(", "env_hooks", ")", "lines", ".", "append", "(", "assignment", "(", "'_CATKIN_ENVIRONMENT_HOOKS_COUNT'", ",", "count", ")", ")", "for", "i", "in", "range", "(", "count", ")", ":", "lines", ".", "append", "(", "assignment", "(", "'_CATKIN_ENVIRONMENT_HOOKS_%d'", "%", "i", ",", "env_hooks", "[", "i", "]", ")", ")", "lines", ".", "append", "(", "assignment", "(", "'_CATKIN_ENVIRONMENT_HOOKS_%d_WORKSPACE'", "%", "i", ",", "env_hooks_workspace", "[", "i", "]", ")", ")", "return", "lines" ]
https://github.com/HKUST-Aerial-Robotics/Teach-Repeat-Replan/blob/98505a7f74b13c8b501176ff838a38423dbef536/utils/pose_utils/build/devel/_setup_util.py#L195-L244
gimli-org/gimli
17aa2160de9b15ababd9ef99e89b1bc3277bbb23
pygimli/solver/solver.py
python
checkCFL
(times, mesh, vMax, verbose=False)
return c
Check Courant-Friedrichs-Lewy condition. For advection and flow problems. CFL Number should be lower then 1 to ensure stability. Parameters ----------
Check Courant-Friedrichs-Lewy condition.
[ "Check", "Courant", "-", "Friedrichs", "-", "Lewy", "condition", "." ]
def checkCFL(times, mesh, vMax, verbose=False): """Check Courant-Friedrichs-Lewy condition. For advection and flow problems. CFL Number should be lower then 1 to ensure stability. Parameters ---------- """ if pg.isScalar(times): dt = times else: dt = times[1] - times[0] dx = min(mesh.h()) # min(entity.shape().h() # if mesh.dimension() == 1: # dx = min(mesh.cellSizes()) # else: # dx = min(mesh.boundarySizes()) c = vMax * dt / dx if c > 1: pg.warn("Courant-Friedrichs-Lewy Number:", c, "but should be lower 1 to ensure movement inside a cell " "per timestep. (" "vMax =", vMax, "dt =", dt, "dx =", dx, "dt <", dx/vMax, " | N > ", int(dt/(dx/vMax))+1, ")") if verbose: pg.info("Courant-Friedrichs-Lewy Number:", c) return c
[ "def", "checkCFL", "(", "times", ",", "mesh", ",", "vMax", ",", "verbose", "=", "False", ")", ":", "if", "pg", ".", "isScalar", "(", "times", ")", ":", "dt", "=", "times", "else", ":", "dt", "=", "times", "[", "1", "]", "-", "times", "[", "0", "]", "dx", "=", "min", "(", "mesh", ".", "h", "(", ")", ")", "# min(entity.shape().h()", "# if mesh.dimension() == 1:", "# dx = min(mesh.cellSizes())", "# else:", "# dx = min(mesh.boundarySizes())", "c", "=", "vMax", "*", "dt", "/", "dx", "if", "c", ">", "1", ":", "pg", ".", "warn", "(", "\"Courant-Friedrichs-Lewy Number:\"", ",", "c", ",", "\"but should be lower 1 to ensure movement inside a cell \"", "\"per timestep. (\"", "\"vMax =\"", ",", "vMax", ",", "\"dt =\"", ",", "dt", ",", "\"dx =\"", ",", "dx", ",", "\"dt <\"", ",", "dx", "/", "vMax", ",", "\" | N > \"", ",", "int", "(", "dt", "/", "(", "dx", "/", "vMax", ")", ")", "+", "1", ",", "\")\"", ")", "if", "verbose", ":", "pg", ".", "info", "(", "\"Courant-Friedrichs-Lewy Number:\"", ",", "c", ")", "return", "c" ]
https://github.com/gimli-org/gimli/blob/17aa2160de9b15ababd9ef99e89b1bc3277bbb23/pygimli/solver/solver.py#L2512-L2545
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/plat-riscos/riscospath.py
python
walk
(top, func, arg)
Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.
Directory tree walk with callback function.
[ "Directory", "tree", "walk", "with", "callback", "function", "." ]
def walk(top, func, arg): """Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.""" try: names= os.listdir(top) except os.error: return func(arg, top, names) for name in names: name= join(top, name) if isdir(name) and not islink(name): walk(name, func, arg)
[ "def", "walk", "(", "top", ",", "func", ",", "arg", ")", ":", "try", ":", "names", "=", "os", ".", "listdir", "(", "top", ")", "except", "os", ".", "error", ":", "return", "func", "(", "arg", ",", "top", ",", "names", ")", "for", "name", "in", "names", ":", "name", "=", "join", "(", "top", ",", "name", ")", "if", "isdir", "(", "name", ")", "and", "not", "islink", "(", "name", ")", ":", "walk", "(", "name", ",", "func", ",", "arg", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/plat-riscos/riscospath.py#L355-L378
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/sim/simulation.py
python
DefaultActuatorEmulator.process
(self,commands,dt)
return
Commands: a dictionary of values outputted from the controller module, or None if no command was issued.
Commands: a dictionary of values outputted from the controller module, or None if no command was issued.
[ "Commands", ":", "a", "dictionary", "of", "values", "outputted", "from", "the", "controller", "module", "or", "None", "if", "no", "command", "was", "issued", "." ]
def process(self,commands,dt): """Commands: a dictionary of values outputted from the controller module, or None if no command was issued. """ if commands == None: return c = self.controller defaultVals = set(['torquecmd','qcmd','dqcmd','tcmd']) if 'qcmd' in commands: dqcmd = commands['dqcmd'] if 'dqcmd' in commands else [0.0]*len(commands['qcmd']) if 'torquecmd' in commands: c.setPIDCommand(commands['qcmd'],dqcmd,commands['torquecmd']) else: c.setPIDCommand(commands['qcmd'],dqcmd) elif 'dqcmd' in commands: assert 'tcmd' in commands c.setVelocity(commands['dqcmd'],commands['tcmd']) elif 'torquecmd' in commands: c.setTorque(commands['torquecmd']) for (k,v) in commands.iteritems(): if k not in defaultVals: print "Sending command",k,v,"to low level controller" c.sendCommand(k,v) return
[ "def", "process", "(", "self", ",", "commands", ",", "dt", ")", ":", "if", "commands", "==", "None", ":", "return", "c", "=", "self", ".", "controller", "defaultVals", "=", "set", "(", "[", "'torquecmd'", ",", "'qcmd'", ",", "'dqcmd'", ",", "'tcmd'", "]", ")", "if", "'qcmd'", "in", "commands", ":", "dqcmd", "=", "commands", "[", "'dqcmd'", "]", "if", "'dqcmd'", "in", "commands", "else", "[", "0.0", "]", "*", "len", "(", "commands", "[", "'qcmd'", "]", ")", "if", "'torquecmd'", "in", "commands", ":", "c", ".", "setPIDCommand", "(", "commands", "[", "'qcmd'", "]", ",", "dqcmd", ",", "commands", "[", "'torquecmd'", "]", ")", "else", ":", "c", ".", "setPIDCommand", "(", "commands", "[", "'qcmd'", "]", ",", "dqcmd", ")", "elif", "'dqcmd'", "in", "commands", ":", "assert", "'tcmd'", "in", "commands", "c", ".", "setVelocity", "(", "commands", "[", "'dqcmd'", "]", ",", "commands", "[", "'tcmd'", "]", ")", "elif", "'torquecmd'", "in", "commands", ":", "c", ".", "setTorque", "(", "commands", "[", "'torquecmd'", "]", ")", "for", "(", "k", ",", "v", ")", "in", "commands", ".", "iteritems", "(", ")", ":", "if", "k", "not", "in", "defaultVals", ":", "print", "\"Sending command\"", ",", "k", ",", "v", ",", "\"to low level controller\"", "c", ".", "sendCommand", "(", "k", ",", "v", ")", "return" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/sim/simulation.py#L100-L121
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/caffe/net_spec.py
python
to_proto
(*tops)
return net
Generate a NetParameter that contains all layers needed to compute all arguments.
Generate a NetParameter that contains all layers needed to compute all arguments.
[ "Generate", "a", "NetParameter", "that", "contains", "all", "layers", "needed", "to", "compute", "all", "arguments", "." ]
def to_proto(*tops): """Generate a NetParameter that contains all layers needed to compute all arguments.""" layers = OrderedDict() autonames = Counter() for top in tops: top.fn._to_proto(layers, {}, autonames) net = caffe_pb2.NetParameter() net.layer.extend(layers.values()) return net
[ "def", "to_proto", "(", "*", "tops", ")", ":", "layers", "=", "OrderedDict", "(", ")", "autonames", "=", "Counter", "(", ")", "for", "top", "in", "tops", ":", "top", ".", "fn", ".", "_to_proto", "(", "layers", ",", "{", "}", ",", "autonames", ")", "net", "=", "caffe_pb2", ".", "NetParameter", "(", ")", "net", ".", "layer", ".", "extend", "(", "layers", ".", "values", "(", ")", ")", "return", "net" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/caffe/net_spec.py#L21-L31
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
ConfigBase_Create
(*args)
return _misc_.ConfigBase_Create(*args)
ConfigBase_Create() -> ConfigBase Create and return a new global config object. This function will create the "best" implementation of wx.Config available for the current platform.
ConfigBase_Create() -> ConfigBase
[ "ConfigBase_Create", "()", "-", ">", "ConfigBase" ]
def ConfigBase_Create(*args): """ ConfigBase_Create() -> ConfigBase Create and return a new global config object. This function will create the "best" implementation of wx.Config available for the current platform. """ return _misc_.ConfigBase_Create(*args)
[ "def", "ConfigBase_Create", "(", "*", "args", ")", ":", "return", "_misc_", ".", "ConfigBase_Create", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3467-L3475
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
xmlNode.hasNsProp
(self, name, nameSpace)
return __tmp
Search for an attribute associated to a node This attribute has to be anchored in the namespace specified. This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. Note that a namespace of None indicates to use the default namespace.
Search for an attribute associated to a node This attribute has to be anchored in the namespace specified. This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. Note that a namespace of None indicates to use the default namespace.
[ "Search", "for", "an", "attribute", "associated", "to", "a", "node", "This", "attribute", "has", "to", "be", "anchored", "in", "the", "namespace", "specified", ".", "This", "does", "the", "entity", "substitution", ".", "This", "function", "looks", "in", "DTD", "attribute", "declaration", "for", "#FIXED", "or", "default", "declaration", "values", "unless", "DTD", "use", "has", "been", "turned", "off", ".", "Note", "that", "a", "namespace", "of", "None", "indicates", "to", "use", "the", "default", "namespace", "." ]
def hasNsProp(self, name, nameSpace): """Search for an attribute associated to a node This attribute has to be anchored in the namespace specified. This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. Note that a namespace of None indicates to use the default namespace. """ ret = libxml2mod.xmlHasNsProp(self._o, name, nameSpace) if ret is None:return None __tmp = xmlAttr(_obj=ret) return __tmp
[ "def", "hasNsProp", "(", "self", ",", "name", ",", "nameSpace", ")", ":", "ret", "=", "libxml2mod", ".", "xmlHasNsProp", "(", "self", ".", "_o", ",", "name", ",", "nameSpace", ")", "if", "ret", "is", "None", ":", "return", "None", "__tmp", "=", "xmlAttr", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L3270-L3280
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
build-support/iwyu/fix_includes.py
python
_GetSymbolNameFromForwardDeclareLine
(line)
return symbol_name
Given a forward declare line to add from iwyu output, get symbol. Two possibilities: In or not in namespace(s). If in namespaces, then return foo::bar::sym. Else just sym.
Given a forward declare line to add from iwyu output, get symbol.
[ "Given", "a", "forward", "declare", "line", "to", "add", "from", "iwyu", "output", "get", "symbol", "." ]
def _GetSymbolNameFromForwardDeclareLine(line): """Given a forward declare line to add from iwyu output, get symbol. Two possibilities: In or not in namespace(s). If in namespaces, then return foo::bar::sym. Else just sym. """ iwyu_namespace_re = re.compile(r'namespace ([^{]*) { ') symbolname_re = re.compile(r'([A-Za-z0-9_]+)') # Turn anonymous namespaces into their proper symbol representation. namespaces_in_line = iwyu_namespace_re.findall(line.replace( "namespace {", "namespace (anonymous namespace) {")) symbols_in_line = symbolname_re.findall(line) symbol_name = symbols_in_line[-1] if (namespaces_in_line): symbol_name = '::'.join(namespaces_in_line) + '::' + symbol_name return symbol_name
[ "def", "_GetSymbolNameFromForwardDeclareLine", "(", "line", ")", ":", "iwyu_namespace_re", "=", "re", ".", "compile", "(", "r'namespace ([^{]*) { '", ")", "symbolname_re", "=", "re", ".", "compile", "(", "r'([A-Za-z0-9_]+)'", ")", "# Turn anonymous namespaces into their proper symbol representation.", "namespaces_in_line", "=", "iwyu_namespace_re", ".", "findall", "(", "line", ".", "replace", "(", "\"namespace {\"", ",", "\"namespace (anonymous namespace) {\"", ")", ")", "symbols_in_line", "=", "symbolname_re", ".", "findall", "(", "line", ")", "symbol_name", "=", "symbols_in_line", "[", "-", "1", "]", "if", "(", "namespaces_in_line", ")", ":", "symbol_name", "=", "'::'", ".", "join", "(", "namespaces_in_line", ")", "+", "'::'", "+", "symbol_name", "return", "symbol_name" ]
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/iwyu/fix_includes.py#L2074-L2090
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/site_compare/operators/equals.py
python
Compare
(file1, file2, **kwargs)
Compares two images to see if they're identical. Args: file1: path to first image to compare file2: path to second image to compare kwargs: unused for this operator Returns: None if the images are identical A tuple of (errorstring, image) if they're not
Compares two images to see if they're identical.
[ "Compares", "two", "images", "to", "see", "if", "they", "re", "identical", "." ]
def Compare(file1, file2, **kwargs): """Compares two images to see if they're identical. Args: file1: path to first image to compare file2: path to second image to compare kwargs: unused for this operator Returns: None if the images are identical A tuple of (errorstring, image) if they're not """ kwargs = kwargs # unused parameter im1 = Image.open(file1) im2 = Image.open(file2) if im1.size != im2.size: return ("The images are of different size (%s vs %s)" % (im1.size, im2.size), im1) diff = ImageChops.difference(im1, im2) if max(diff.getextrema()) != (0, 0): return ("The images differ", diff) else: return None
[ "def", "Compare", "(", "file1", ",", "file2", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "kwargs", "# unused parameter", "im1", "=", "Image", ".", "open", "(", "file1", ")", "im2", "=", "Image", ".", "open", "(", "file2", ")", "if", "im1", ".", "size", "!=", "im2", ".", "size", ":", "return", "(", "\"The images are of different size (%s vs %s)\"", "%", "(", "im1", ".", "size", ",", "im2", ".", "size", ")", ",", "im1", ")", "diff", "=", "ImageChops", ".", "difference", "(", "im1", ",", "im2", ")", "if", "max", "(", "diff", ".", "getextrema", "(", ")", ")", "!=", "(", "0", ",", "0", ")", ":", "return", "(", "\"The images differ\"", ",", "diff", ")", "else", ":", "return", "None" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/site_compare/operators/equals.py#L11-L37
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/config/configurable.py
python
Configurable.class_config_rst_doc
(cls)
return '\n'.join(lines)
Generate rST documentation for this class' config options. Excludes traits defined on parent classes.
Generate rST documentation for this class' config options.
[ "Generate", "rST", "documentation", "for", "this", "class", "config", "options", "." ]
def class_config_rst_doc(cls): """Generate rST documentation for this class' config options. Excludes traits defined on parent classes. """ lines = [] classname = cls.__name__ for k, trait in sorted(cls.class_traits(config=True).items()): ttype = trait.__class__.__name__ termline = classname + '.' + trait.name # Choices or type if 'Enum' in ttype: # include Enum choices termline += ' : ' + trait.info_rst() else: termline += ' : ' + ttype lines.append(termline) # Default value try: dvr = trait.default_value_repr() except Exception: dvr = None # ignore defaults we can't construct if dvr is not None: if len(dvr) > 64: dvr = dvr[:61]+'...' # Double up backslashes, so they get to the rendered docs dvr = dvr.replace("\\n", "\\\\n") lines.append(indent("Default: ``%s``" % dvr)) lines.append("") help = trait.help or 'No description' lines.append(indent(dedent(help))) # Blank line lines.append('') return '\n'.join(lines)
[ "def", "class_config_rst_doc", "(", "cls", ")", ":", "lines", "=", "[", "]", "classname", "=", "cls", ".", "__name__", "for", "k", ",", "trait", "in", "sorted", "(", "cls", ".", "class_traits", "(", "config", "=", "True", ")", ".", "items", "(", ")", ")", ":", "ttype", "=", "trait", ".", "__class__", ".", "__name__", "termline", "=", "classname", "+", "'.'", "+", "trait", ".", "name", "# Choices or type", "if", "'Enum'", "in", "ttype", ":", "# include Enum choices", "termline", "+=", "' : '", "+", "trait", ".", "info_rst", "(", ")", "else", ":", "termline", "+=", "' : '", "+", "ttype", "lines", ".", "append", "(", "termline", ")", "# Default value", "try", ":", "dvr", "=", "trait", ".", "default_value_repr", "(", ")", "except", "Exception", ":", "dvr", "=", "None", "# ignore defaults we can't construct", "if", "dvr", "is", "not", "None", ":", "if", "len", "(", "dvr", ")", ">", "64", ":", "dvr", "=", "dvr", "[", ":", "61", "]", "+", "'...'", "# Double up backslashes, so they get to the rendered docs", "dvr", "=", "dvr", ".", "replace", "(", "\"\\\\n\"", ",", "\"\\\\\\\\n\"", ")", "lines", ".", "append", "(", "indent", "(", "\"Default: ``%s``\"", "%", "dvr", ")", ")", "lines", ".", "append", "(", "\"\"", ")", "help", "=", "trait", ".", "help", "or", "'No description'", "lines", ".", "append", "(", "indent", "(", "dedent", "(", "help", ")", ")", ")", "# Blank line", "lines", ".", "append", "(", "''", ")", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/config/configurable.py#L392-L431
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2_extras/sessions.py
python
SessionStore.__init__
(self, request, config=None)
Initializes the session store. :param request: A :class:`webapp2.Request` instance. :param config: A dictionary of configuration values to be overridden. See the available keys in :data:`default_config`.
Initializes the session store.
[ "Initializes", "the", "session", "store", "." ]
def __init__(self, request, config=None): """Initializes the session store. :param request: A :class:`webapp2.Request` instance. :param config: A dictionary of configuration values to be overridden. See the available keys in :data:`default_config`. """ self.request = request # Base configuration. self.config = request.app.config.load_config(self.config_key, default_values=default_config, user_values=config, required_keys=('secret_key',)) # Tracked sessions. self.sessions = {}
[ "def", "__init__", "(", "self", ",", "request", ",", "config", "=", "None", ")", ":", "self", ".", "request", "=", "request", "# Base configuration.", "self", ".", "config", "=", "request", ".", "app", ".", "config", ".", "load_config", "(", "self", ".", "config_key", ",", "default_values", "=", "default_config", ",", "user_values", "=", "config", ",", "required_keys", "=", "(", "'secret_key'", ",", ")", ")", "# Tracked sessions.", "self", ".", "sessions", "=", "{", "}" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2_extras/sessions.py#L295-L310
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py
python
GmmAlgorithm._define_full_covariance_probs
(self, shard_id, shard)
Defines the full covariance probabilties per example in a class. Updates a matrix with dimension num_examples X num_classes. Args: shard_id: id of the current shard. shard: current data shard, 1 X num_examples X dimensions.
Defines the full covariance probabilties per example in a class.
[ "Defines", "the", "full", "covariance", "probabilties", "per", "example", "in", "a", "class", "." ]
def _define_full_covariance_probs(self, shard_id, shard): """Defines the full covariance probabilties per example in a class. Updates a matrix with dimension num_examples X num_classes. Args: shard_id: id of the current shard. shard: current data shard, 1 X num_examples X dimensions. """ diff = shard - self._means cholesky = tf.batch_cholesky(self._covs + self._min_var) log_det_covs = 2.0 * tf.reduce_sum(tf.log( tf.batch_matrix_diag_part(cholesky)), 1) x_mu_cov = tf.square(tf.batch_matrix_triangular_solve( cholesky, tf.transpose(diff, perm=[0, 2, 1]), lower=True)) diag_m = tf.transpose(tf.reduce_sum(x_mu_cov, 1)) self._probs[shard_id] = -0.5 * ( diag_m + tf.to_float(self._dimensions) * tf.log(2 * np.pi) + log_det_covs)
[ "def", "_define_full_covariance_probs", "(", "self", ",", "shard_id", ",", "shard", ")", ":", "diff", "=", "shard", "-", "self", ".", "_means", "cholesky", "=", "tf", ".", "batch_cholesky", "(", "self", ".", "_covs", "+", "self", ".", "_min_var", ")", "log_det_covs", "=", "2.0", "*", "tf", ".", "reduce_sum", "(", "tf", ".", "log", "(", "tf", ".", "batch_matrix_diag_part", "(", "cholesky", ")", ")", ",", "1", ")", "x_mu_cov", "=", "tf", ".", "square", "(", "tf", ".", "batch_matrix_triangular_solve", "(", "cholesky", ",", "tf", ".", "transpose", "(", "diff", ",", "perm", "=", "[", "0", ",", "2", ",", "1", "]", ")", ",", "lower", "=", "True", ")", ")", "diag_m", "=", "tf", ".", "transpose", "(", "tf", ".", "reduce_sum", "(", "x_mu_cov", ",", "1", ")", ")", "self", ".", "_probs", "[", "shard_id", "]", "=", "-", "0.5", "*", "(", "diag_m", "+", "tf", ".", "to_float", "(", "self", ".", "_dimensions", ")", "*", "tf", ".", "log", "(", "2", "*", "np", ".", "pi", ")", "+", "log_det_covs", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L220-L239
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py
python
_LogicalStream.send_ping
(self, body='')
Overrides Stream.send_ping
Overrides Stream.send_ping
[ "Overrides", "Stream", ".", "send_ping" ]
def send_ping(self, body=''): """Overrides Stream.send_ping""" self._logger.debug('Sending ping on logical channel %d: %r' % (self._request.channel_id, body)) self._write_inner_frame(common.OPCODE_PING, body, end=True) self._ping_queue.append(body)
[ "def", "send_ping", "(", "self", ",", "body", "=", "''", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Sending ping on logical channel %d: %r'", "%", "(", "self", ".", "_request", ".", "channel_id", ",", "body", ")", ")", "self", ".", "_write_inner_frame", "(", "common", ".", "OPCODE_PING", ",", "body", ",", "end", "=", "True", ")", "self", ".", "_ping_queue", ".", "append", "(", "body", ")" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/mux.py#L1046-L1053
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBTypeMemberFunction.GetArgumentTypeAtIndex
(self, *args)
return _lldb.SBTypeMemberFunction_GetArgumentTypeAtIndex(self, *args)
GetArgumentTypeAtIndex(self, uint32_t arg0) -> SBType
GetArgumentTypeAtIndex(self, uint32_t arg0) -> SBType
[ "GetArgumentTypeAtIndex", "(", "self", "uint32_t", "arg0", ")", "-", ">", "SBType" ]
def GetArgumentTypeAtIndex(self, *args): """GetArgumentTypeAtIndex(self, uint32_t arg0) -> SBType""" return _lldb.SBTypeMemberFunction_GetArgumentTypeAtIndex(self, *args)
[ "def", "GetArgumentTypeAtIndex", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBTypeMemberFunction_GetArgumentTypeAtIndex", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L10236-L10238
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_cocoa/gizmos.py
python
TreeListCtrl.SetItemPyData
(*args, **kwargs)
return _gizmos.TreeListCtrl_SetItemPyData(*args, **kwargs)
SetItemPyData(self, TreeItemId item, PyObject obj)
SetItemPyData(self, TreeItemId item, PyObject obj)
[ "SetItemPyData", "(", "self", "TreeItemId", "item", "PyObject", "obj", ")" ]
def SetItemPyData(*args, **kwargs): """SetItemPyData(self, TreeItemId item, PyObject obj)""" return _gizmos.TreeListCtrl_SetItemPyData(*args, **kwargs)
[ "def", "SetItemPyData", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_SetItemPyData", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_cocoa/gizmos.py#L679-L681
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/external/bazel_tools/tools/android/incremental_install.py
python
Adb.Push
(self, local, remote)
return self._ExecParallel(["push", local, remote])
Invoke 'adb push' in parallel.
Invoke 'adb push' in parallel.
[ "Invoke", "adb", "push", "in", "parallel", "." ]
def Push(self, local, remote): """Invoke 'adb push' in parallel.""" return self._ExecParallel(["push", local, remote])
[ "def", "Push", "(", "self", ",", "local", ",", "remote", ")", ":", "return", "self", ".", "_ExecParallel", "(", "[", "\"push\"", ",", "local", ",", "remote", "]", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/external/bazel_tools/tools/android/incremental_install.py#L194-L196
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/_multivariate.py
python
wishart_gen.__call__
(self, df=None, scale=None, seed=None)
return wishart_frozen(df, scale, seed)
Create a frozen Wishart distribution. See `wishart_frozen` for more information.
Create a frozen Wishart distribution.
[ "Create", "a", "frozen", "Wishart", "distribution", "." ]
def __call__(self, df=None, scale=None, seed=None): """ Create a frozen Wishart distribution. See `wishart_frozen` for more information. """ return wishart_frozen(df, scale, seed)
[ "def", "__call__", "(", "self", ",", "df", "=", "None", ",", "scale", "=", "None", ",", "seed", "=", "None", ")", ":", "return", "wishart_frozen", "(", "df", ",", "scale", ",", "seed", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L1528-L1535
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Misc.bindtags
(self, tagList=None)
Set or get the list of bindtags for this widget. With no argument return the list of all bindtags associated with this widget. With a list of strings as argument the bindtags are set to this list. The bindtags determine in which order events are processed (see bind).
Set or get the list of bindtags for this widget.
[ "Set", "or", "get", "the", "list", "of", "bindtags", "for", "this", "widget", "." ]
def bindtags(self, tagList=None): """Set or get the list of bindtags for this widget. With no argument return the list of all bindtags associated with this widget. With a list of strings as argument the bindtags are set to this list. The bindtags determine in which order events are processed (see bind).""" if tagList is None: return self.tk.splitlist( self.tk.call('bindtags', self._w)) else: self.tk.call('bindtags', self._w, tagList)
[ "def", "bindtags", "(", "self", ",", "tagList", "=", "None", ")", ":", "if", "tagList", "is", "None", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "'bindtags'", ",", "self", ".", "_w", ")", ")", "else", ":", "self", ".", "tk", ".", "call", "(", "'bindtags'", ",", "self", ".", "_w", ",", "tagList", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L1183-L1194
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/metrics/confusion_matrix.py
python
_calculate_fnr
(fn, p)
return fn, p
Calculate fnr.
Calculate fnr.
[ "Calculate", "fnr", "." ]
def _calculate_fnr(fn, p): """Calculate fnr.""" return fn, p
[ "def", "_calculate_fnr", "(", "fn", ",", "p", ")", ":", "return", "fn", ",", "p" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/metrics/confusion_matrix.py#L484-L486
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/ltisys.py
python
StateSpace.__mul__
(self, other)
return StateSpace(np.asarray(a, dtype=common_dtype), np.asarray(b, dtype=common_dtype), np.asarray(c, dtype=common_dtype), np.asarray(d, dtype=common_dtype))
Post-multiply another system or a scalar Handles multiplication of systems in the sense of a frequency domain multiplication. That means, given two systems E1(s) and E2(s), their multiplication, H(s) = E1(s) * E2(s), means that applying H(s) to U(s) is equivalent to first applying E2(s), and then E1(s). Notes ----- For SISO systems the order of system application does not matter. However, for MIMO systems, where the two systems are matrices, the order above ensures standard Matrix multiplication rules apply.
Post-multiply another system or a scalar
[ "Post", "-", "multiply", "another", "system", "or", "a", "scalar" ]
def __mul__(self, other): """ Post-multiply another system or a scalar Handles multiplication of systems in the sense of a frequency domain multiplication. That means, given two systems E1(s) and E2(s), their multiplication, H(s) = E1(s) * E2(s), means that applying H(s) to U(s) is equivalent to first applying E2(s), and then E1(s). Notes ----- For SISO systems the order of system application does not matter. However, for MIMO systems, where the two systems are matrices, the order above ensures standard Matrix multiplication rules apply. """ if not self._check_binop_other(other): return NotImplemented if isinstance(other, StateSpace): # Disallow mix of discrete and continuous systems. if type(other) is not type(self): return NotImplemented if self.dt != other.dt: raise TypeError('Cannot multiply systems with different `dt`.') n1 = self.A.shape[0] n2 = other.A.shape[0] # Interconnection of systems # x1' = A1 x1 + B1 u1 # y1 = C1 x1 + D1 u1 # x2' = A2 x2 + B2 y1 # y2 = C2 x2 + D2 y1 # # Plugging in with u1 = y2 yields # [x1'] [A1 B1*C2 ] [x1] [B1*D2] # [x2'] = [0 A2 ] [x2] + [B2 ] u2 # [x1] # y2 = [C1 D1*C2] [x2] + D1*D2 u2 a = np.vstack((np.hstack((self.A, np.dot(self.B, other.C))), np.hstack((zeros((n2, n1)), other.A)))) b = np.vstack((np.dot(self.B, other.D), other.B)) c = np.hstack((self.C, np.dot(self.D, other.C))) d = np.dot(self.D, other.D) else: # Assume that other is a scalar / matrix # For post multiplication the input gets scaled a = self.A b = np.dot(self.B, other) c = self.C d = np.dot(self.D, other) common_dtype = np.find_common_type((a.dtype, b.dtype, c.dtype, d.dtype), ()) return StateSpace(np.asarray(a, dtype=common_dtype), np.asarray(b, dtype=common_dtype), np.asarray(c, dtype=common_dtype), np.asarray(d, dtype=common_dtype))
[ "def", "__mul__", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "_check_binop_other", "(", "other", ")", ":", "return", "NotImplemented", "if", "isinstance", "(", "other", ",", "StateSpace", ")", ":", "# Disallow mix of discrete and continuous systems.", "if", "type", "(", "other", ")", "is", "not", "type", "(", "self", ")", ":", "return", "NotImplemented", "if", "self", ".", "dt", "!=", "other", ".", "dt", ":", "raise", "TypeError", "(", "'Cannot multiply systems with different `dt`.'", ")", "n1", "=", "self", ".", "A", ".", "shape", "[", "0", "]", "n2", "=", "other", ".", "A", ".", "shape", "[", "0", "]", "# Interconnection of systems", "# x1' = A1 x1 + B1 u1", "# y1 = C1 x1 + D1 u1", "# x2' = A2 x2 + B2 y1", "# y2 = C2 x2 + D2 y1", "#", "# Plugging in with u1 = y2 yields", "# [x1'] [A1 B1*C2 ] [x1] [B1*D2]", "# [x2'] = [0 A2 ] [x2] + [B2 ] u2", "# [x1]", "# y2 = [C1 D1*C2] [x2] + D1*D2 u2", "a", "=", "np", ".", "vstack", "(", "(", "np", ".", "hstack", "(", "(", "self", ".", "A", ",", "np", ".", "dot", "(", "self", ".", "B", ",", "other", ".", "C", ")", ")", ")", ",", "np", ".", "hstack", "(", "(", "zeros", "(", "(", "n2", ",", "n1", ")", ")", ",", "other", ".", "A", ")", ")", ")", ")", "b", "=", "np", ".", "vstack", "(", "(", "np", ".", "dot", "(", "self", ".", "B", ",", "other", ".", "D", ")", ",", "other", ".", "B", ")", ")", "c", "=", "np", ".", "hstack", "(", "(", "self", ".", "C", ",", "np", ".", "dot", "(", "self", ".", "D", ",", "other", ".", "C", ")", ")", ")", "d", "=", "np", ".", "dot", "(", "self", ".", "D", ",", "other", ".", "D", ")", "else", ":", "# Assume that other is a scalar / matrix", "# For post multiplication the input gets scaled", "a", "=", "self", ".", "A", "b", "=", "np", ".", "dot", "(", "self", ".", "B", ",", "other", ")", "c", "=", "self", ".", "C", "d", "=", "np", ".", "dot", "(", "self", ".", "D", ",", "other", ")", "common_dtype", "=", "np", ".", "find_common_type", "(", "(", "a", ".", "dtype", ",", "b", ".", "dtype", ",", "c", ".", "dtype", ",", "d", ".", "dtype", ")", ",", "(", ")", ")", "return", "StateSpace", "(", "np", ".", "asarray", "(", "a", ",", "dtype", "=", "common_dtype", ")", ",", "np", ".", "asarray", "(", "b", ",", "dtype", "=", "common_dtype", ")", ",", "np", ".", "asarray", "(", "c", ",", "dtype", "=", "common_dtype", ")", ",", "np", ".", "asarray", "(", "d", ",", "dtype", "=", "common_dtype", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/ltisys.py#L1350-L1407
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/amp/grad_scaler.py
python
GradScaler.unscale
(self, grad_tensors: Iterable[Tensor])
return self
r"""Unscale all ``grad_tensors``'s grad. Args: grad_tensors: Tensors needed to unscale grads. Should be all tensors that are affected by ``target`` tensor in GradManager's backward.
r"""Unscale all ``grad_tensors``'s grad.
[ "r", "Unscale", "all", "grad_tensors", "s", "grad", "." ]
def unscale(self, grad_tensors: Iterable[Tensor]): r"""Unscale all ``grad_tensors``'s grad. Args: grad_tensors: Tensors needed to unscale grads. Should be all tensors that are affected by ``target`` tensor in GradManager's backward. """ if self.growth_interval == 0: # use float64 for better precision inv_scale = Tensor(1.0 / self.scale_factor) for tensor in grad_tensors: if tensor is None or getattr(tensor, "grad", None) is None: continue tensor.grad *= inv_scale return self # to support tracing, _check_gradients should be applied to every grad. if self._check_gradients( [x.grad for x in grad_tensors], 1.0 / self.scale_factor ): self._found_non_finite = True for tensor in grad_tensors: if tensor is None or getattr(tensor, "grad", None) is None: continue tensor.grad = None return self
[ "def", "unscale", "(", "self", ",", "grad_tensors", ":", "Iterable", "[", "Tensor", "]", ")", ":", "if", "self", ".", "growth_interval", "==", "0", ":", "# use float64 for better precision", "inv_scale", "=", "Tensor", "(", "1.0", "/", "self", ".", "scale_factor", ")", "for", "tensor", "in", "grad_tensors", ":", "if", "tensor", "is", "None", "or", "getattr", "(", "tensor", ",", "\"grad\"", ",", "None", ")", "is", "None", ":", "continue", "tensor", ".", "grad", "*=", "inv_scale", "return", "self", "# to support tracing, _check_gradients should be applied to every grad.", "if", "self", ".", "_check_gradients", "(", "[", "x", ".", "grad", "for", "x", "in", "grad_tensors", "]", ",", "1.0", "/", "self", ".", "scale_factor", ")", ":", "self", ".", "_found_non_finite", "=", "True", "for", "tensor", "in", "grad_tensors", ":", "if", "tensor", "is", "None", "or", "getattr", "(", "tensor", ",", "\"grad\"", ",", "None", ")", "is", "None", ":", "continue", "tensor", ".", "grad", "=", "None", "return", "self" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/amp/grad_scaler.py#L124-L149
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py
python
FancyURLopener.http_error_302
(self, url, fp, errcode, errmsg, headers, data=None)
Error 302 -- relocated (temporarily).
Error 302 -- relocated (temporarily).
[ "Error", "302", "--", "relocated", "(", "temporarily", ")", "." ]
def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): """Error 302 -- relocated (temporarily).""" self.tries += 1 try: if self.maxtries and self.tries >= self.maxtries: if hasattr(self, "http_error_500"): meth = self.http_error_500 else: meth = self.http_error_default return meth(url, fp, 500, "Internal Server Error: Redirect Recursion", headers) result = self.redirect_internal(url, fp, errcode, errmsg, headers, data) return result finally: self.tries = 0
[ "def", "http_error_302", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "self", ".", "tries", "+=", "1", "try", ":", "if", "self", ".", "maxtries", "and", "self", ".", "tries", ">=", "self", ".", "maxtries", ":", "if", "hasattr", "(", "self", ",", "\"http_error_500\"", ")", ":", "meth", "=", "self", ".", "http_error_500", "else", ":", "meth", "=", "self", ".", "http_error_default", "return", "meth", "(", "url", ",", "fp", ",", "500", ",", "\"Internal Server Error: Redirect Recursion\"", ",", "headers", ")", "result", "=", "self", ".", "redirect_internal", "(", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", ")", "return", "result", "finally", ":", "self", ".", "tries", "=", "0" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py#L2154-L2170
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/command/register.py
python
register.send_metadata
(self)
Send the metadata to the package index server. Well, do the following: 1. figure who the user is, and then 2. send the data as a Basic auth'ed POST. First we try to read the username/password from $HOME/.pypirc, which is a ConfigParser-formatted file with a section [distutils] containing username and password entries (both in clear text). Eg: [distutils] index-servers = pypi [pypi] username: fred password: sekrit Otherwise, to figure who the user is, we offer the user three choices: 1. use existing login, 2. register as a new user, or 3. set the password to a random string and email the user.
Send the metadata to the package index server.
[ "Send", "the", "metadata", "to", "the", "package", "index", "server", "." ]
def send_metadata(self): ''' Send the metadata to the package index server. Well, do the following: 1. figure who the user is, and then 2. send the data as a Basic auth'ed POST. First we try to read the username/password from $HOME/.pypirc, which is a ConfigParser-formatted file with a section [distutils] containing username and password entries (both in clear text). Eg: [distutils] index-servers = pypi [pypi] username: fred password: sekrit Otherwise, to figure who the user is, we offer the user three choices: 1. use existing login, 2. register as a new user, or 3. set the password to a random string and email the user. ''' # see if we can short-cut and get the username/password from the # config if self.has_config: choice = '1' username = self.username password = self.password else: choice = 'x' username = password = '' # get the user's login info choices = '1 2 3 4'.split() while choice not in choices: self.announce('''\ We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: ''', log.INFO) choice = input() if not choice: choice = '1' elif choice not in choices: print('Please choose one of the four options!') if choice == '1': # get the username and password while not username: username = input('Username: ') while not password: password = getpass.getpass('Password: ') # set up the authentication auth = urllib.request.HTTPPasswordMgr() host = urllib.parse.urlparse(self.repository)[1] auth.add_password(self.realm, host, username, password) # send the info to the server and report the result code, result = self.post_to_server(self.build_post_data('submit'), auth) self.announce('Server response (%s): %s' % (code, result), log.INFO) # possibly save the login if code == 200: if self.has_config: # sharing the password in the distribution instance # so the upload command can reuse it self.distribution.password = password else: self.announce(('I can store your PyPI login so future ' 'submissions will be faster.'), log.INFO) self.announce('(the login will be stored in %s)' % \ self._get_rc_file(), log.INFO) choice = 'X' while choice.lower() not in 'yn': choice = input('Save your login (y/N)?') if not choice: choice = 'n' if choice.lower() == 'y': self._store_pypirc(username, password) elif choice == '2': data = {':action': 'user'} data['name'] = data['password'] = data['email'] = '' data['confirm'] = None while not data['name']: data['name'] = input('Username: ') while data['password'] != data['confirm']: while not data['password']: data['password'] = getpass.getpass('Password: ') while not data['confirm']: data['confirm'] = getpass.getpass(' Confirm: ') if data['password'] != data['confirm']: data['password'] = '' data['confirm'] = None print("Password and confirm don't match!") while not data['email']: data['email'] = input(' EMail: ') code, result = self.post_to_server(data) if code != 200: log.info('Server response (%s): %s', code, result) else: log.info('You will receive an email shortly.') log.info(('Follow the instructions in it to ' 'complete registration.')) elif choice == '3': data = {':action': 'password_reset'} data['email'] = '' while not data['email']: data['email'] = input('Your email address: ') code, result = self.post_to_server(data) log.info('Server response (%s): %s', code, result)
[ "def", "send_metadata", "(", "self", ")", ":", "# see if we can short-cut and get the username/password from the", "# config", "if", "self", ".", "has_config", ":", "choice", "=", "'1'", "username", "=", "self", ".", "username", "password", "=", "self", ".", "password", "else", ":", "choice", "=", "'x'", "username", "=", "password", "=", "''", "# get the user's login info", "choices", "=", "'1 2 3 4'", ".", "split", "(", ")", "while", "choice", "not", "in", "choices", ":", "self", ".", "announce", "(", "'''\\\nWe need to know who you are, so please choose either:\n 1. use your existing login,\n 2. register as a new user,\n 3. have the server generate a new password for you (and email it to you), or\n 4. quit\nYour selection [default 1]: '''", ",", "log", ".", "INFO", ")", "choice", "=", "input", "(", ")", "if", "not", "choice", ":", "choice", "=", "'1'", "elif", "choice", "not", "in", "choices", ":", "print", "(", "'Please choose one of the four options!'", ")", "if", "choice", "==", "'1'", ":", "# get the username and password", "while", "not", "username", ":", "username", "=", "input", "(", "'Username: '", ")", "while", "not", "password", ":", "password", "=", "getpass", ".", "getpass", "(", "'Password: '", ")", "# set up the authentication", "auth", "=", "urllib", ".", "request", ".", "HTTPPasswordMgr", "(", ")", "host", "=", "urllib", ".", "parse", ".", "urlparse", "(", "self", ".", "repository", ")", "[", "1", "]", "auth", ".", "add_password", "(", "self", ".", "realm", ",", "host", ",", "username", ",", "password", ")", "# send the info to the server and report the result", "code", ",", "result", "=", "self", ".", "post_to_server", "(", "self", ".", "build_post_data", "(", "'submit'", ")", ",", "auth", ")", "self", ".", "announce", "(", "'Server response (%s): %s'", "%", "(", "code", ",", "result", ")", ",", "log", ".", "INFO", ")", "# possibly save the login", "if", "code", "==", "200", ":", "if", "self", ".", "has_config", ":", "# sharing the password in the distribution instance", "# so the upload command can reuse it", "self", ".", "distribution", ".", "password", "=", "password", "else", ":", "self", ".", "announce", "(", "(", "'I can store your PyPI login so future '", "'submissions will be faster.'", ")", ",", "log", ".", "INFO", ")", "self", ".", "announce", "(", "'(the login will be stored in %s)'", "%", "self", ".", "_get_rc_file", "(", ")", ",", "log", ".", "INFO", ")", "choice", "=", "'X'", "while", "choice", ".", "lower", "(", ")", "not", "in", "'yn'", ":", "choice", "=", "input", "(", "'Save your login (y/N)?'", ")", "if", "not", "choice", ":", "choice", "=", "'n'", "if", "choice", ".", "lower", "(", ")", "==", "'y'", ":", "self", ".", "_store_pypirc", "(", "username", ",", "password", ")", "elif", "choice", "==", "'2'", ":", "data", "=", "{", "':action'", ":", "'user'", "}", "data", "[", "'name'", "]", "=", "data", "[", "'password'", "]", "=", "data", "[", "'email'", "]", "=", "''", "data", "[", "'confirm'", "]", "=", "None", "while", "not", "data", "[", "'name'", "]", ":", "data", "[", "'name'", "]", "=", "input", "(", "'Username: '", ")", "while", "data", "[", "'password'", "]", "!=", "data", "[", "'confirm'", "]", ":", "while", "not", "data", "[", "'password'", "]", ":", "data", "[", "'password'", "]", "=", "getpass", ".", "getpass", "(", "'Password: '", ")", "while", "not", "data", "[", "'confirm'", "]", ":", "data", "[", "'confirm'", "]", "=", "getpass", ".", "getpass", "(", "' Confirm: '", ")", "if", "data", "[", "'password'", "]", "!=", "data", "[", "'confirm'", "]", ":", "data", "[", "'password'", "]", "=", "''", "data", "[", "'confirm'", "]", "=", "None", "print", "(", "\"Password and confirm don't match!\"", ")", "while", "not", "data", "[", "'email'", "]", ":", "data", "[", "'email'", "]", "=", "input", "(", "' EMail: '", ")", "code", ",", "result", "=", "self", ".", "post_to_server", "(", "data", ")", "if", "code", "!=", "200", ":", "log", ".", "info", "(", "'Server response (%s): %s'", ",", "code", ",", "result", ")", "else", ":", "log", ".", "info", "(", "'You will receive an email shortly.'", ")", "log", ".", "info", "(", "(", "'Follow the instructions in it to '", "'complete registration.'", ")", ")", "elif", "choice", "==", "'3'", ":", "data", "=", "{", "':action'", ":", "'password_reset'", "}", "data", "[", "'email'", "]", "=", "''", "while", "not", "data", "[", "'email'", "]", ":", "data", "[", "'email'", "]", "=", "input", "(", "'Your email address: '", ")", "code", ",", "result", "=", "self", ".", "post_to_server", "(", "data", ")", "log", ".", "info", "(", "'Server response (%s): %s'", ",", "code", ",", "result", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/register.py#L99-L219
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py
python
FitPropertyBrowser.move_x_range
(self, start_x, end_x)
Let the tool know that the Fit range has been changed in the FitPropertyBrowser. :param start_x: New value of StartX :param end_x: New value of EndX
Let the tool know that the Fit range has been changed in the FitPropertyBrowser. :param start_x: New value of StartX :param end_x: New value of EndX
[ "Let", "the", "tool", "know", "that", "the", "Fit", "range", "has", "been", "changed", "in", "the", "FitPropertyBrowser", ".", ":", "param", "start_x", ":", "New", "value", "of", "StartX", ":", "param", "end_x", ":", "New", "value", "of", "EndX" ]
def move_x_range(self, start_x, end_x): """ Let the tool know that the Fit range has been changed in the FitPropertyBrowser. :param start_x: New value of StartX :param end_x: New value of EndX """ if self.tool is not None: new_range = sorted([start_x, end_x]) bounds = self.tool.fit_range.get_bounds() if bounds[0] <= new_range[0] and bounds[1] >= new_range[1]: self.tool.set_fit_range(new_range[0], new_range[1]) else: self.set_fit_range(self.tool.fit_range.get_range())
[ "def", "move_x_range", "(", "self", ",", "start_x", ",", "end_x", ")", ":", "if", "self", ".", "tool", "is", "not", "None", ":", "new_range", "=", "sorted", "(", "[", "start_x", ",", "end_x", "]", ")", "bounds", "=", "self", ".", "tool", ".", "fit_range", ".", "get_bounds", "(", ")", "if", "bounds", "[", "0", "]", "<=", "new_range", "[", "0", "]", "and", "bounds", "[", "1", "]", ">=", "new_range", "[", "1", "]", ":", "self", ".", "tool", ".", "set_fit_range", "(", "new_range", "[", "0", "]", ",", "new_range", "[", "1", "]", ")", "else", ":", "self", ".", "set_fit_range", "(", "self", ".", "tool", ".", "fit_range", ".", "get_range", "(", ")", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/fitpropertybrowser/fitpropertybrowser.py#L289-L301
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
ThirdParty/cinema/paraview/tpl/cinema_python/images/querymaker_specb.py
python
QueryMaker_SpecB.translateQuery
(self, query, colorDefinitions={})
return allLayers
Receives a UI query and returns a set of LayerRasters consisting of all the different layers to composite. See the base class documentation for detail.
Receives a UI query and returns a set of LayerRasters consisting of all the different layers to composite. See the base class documentation for detail.
[ "Receives", "a", "UI", "query", "and", "returns", "a", "set", "of", "LayerRasters", "consisting", "of", "all", "the", "different", "layers", "to", "composite", ".", "See", "the", "base", "class", "documentation", "for", "detail", "." ]
def translateQuery(self, query, colorDefinitions={}): ''' Receives a UI query and returns a set of LayerRasters consisting of all the different layers to composite. See the base class documentation for detail. ''' # Create a common base LayerRasters (time and camera). baseLayer = self._QueryMaker__createBaseLayerFromQuery(query) # Create all the LayerRasters (TODO cache layers and other db info to # avoid re-creating them every time). allLayers = self.__generateQueriedLayers(query, baseLayer) self._QueryMaker__loadLayers(allLayers) return allLayers
[ "def", "translateQuery", "(", "self", ",", "query", ",", "colorDefinitions", "=", "{", "}", ")", ":", "# Create a common base LayerRasters (time and camera).", "baseLayer", "=", "self", ".", "_QueryMaker__createBaseLayerFromQuery", "(", "query", ")", "# Create all the LayerRasters (TODO cache layers and other db info to", "# avoid re-creating them every time).", "allLayers", "=", "self", ".", "__generateQueriedLayers", "(", "query", ",", "baseLayer", ")", "self", ".", "_QueryMaker__loadLayers", "(", "allLayers", ")", "return", "allLayers" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/images/querymaker_specb.py#L243-L256
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteList
(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary)
Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style.
Write a variable definition that is a list of values.
[ "Write", "a", "variable", "definition", "that", "is", "a", "list", "of", "values", "." ]
def WriteList(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values))
[ "def", "WriteList", "(", "self", ",", "value_list", ",", "variable", "=", "None", ",", "prefix", "=", "''", ",", "quoter", "=", "QuoteIfNecessary", ")", ":", "values", "=", "''", "if", "value_list", ":", "value_list", "=", "[", "quoter", "(", "prefix", "+", "l", ")", "for", "l", "in", "value_list", "]", "values", "=", "' \\\\\\n\\t'", "+", "' \\\\\\n\\t'", ".", "join", "(", "value_list", ")", "self", ".", "fp", ".", "write", "(", "'%s :=%s\\n\\n'", "%", "(", "variable", ",", "values", ")", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py#L1625-L1637
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
ConfigBase.GetAppName
(*args, **kwargs)
return _misc_.ConfigBase_GetAppName(*args, **kwargs)
GetAppName(self) -> String
GetAppName(self) -> String
[ "GetAppName", "(", "self", ")", "-", ">", "String" ]
def GetAppName(*args, **kwargs): """GetAppName(self) -> String""" return _misc_.ConfigBase_GetAppName(*args, **kwargs)
[ "def", "GetAppName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_GetAppName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3413-L3415
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/zipapp.py
python
create_archive
(source, target=None, interpreter=None, main=None, filter=None, compressed=False)
Create an application archive from SOURCE. The SOURCE can be the name of a directory, or a filename or a file-like object referring to an existing archive. The content of SOURCE is packed into an application archive in TARGET, which can be a filename or a file-like object. If SOURCE is a directory, TARGET can be omitted and will default to the name of SOURCE with .pyz appended. The created application archive will have a shebang line specifying that it should run with INTERPRETER (there will be no shebang line if INTERPRETER is None), and a __main__.py which runs MAIN (if MAIN is not specified, an existing __main__.py will be used). It is an error to specify MAIN for anything other than a directory source with no __main__.py, and it is an error to omit MAIN if the directory has no __main__.py.
Create an application archive from SOURCE.
[ "Create", "an", "application", "archive", "from", "SOURCE", "." ]
def create_archive(source, target=None, interpreter=None, main=None, filter=None, compressed=False): """Create an application archive from SOURCE. The SOURCE can be the name of a directory, or a filename or a file-like object referring to an existing archive. The content of SOURCE is packed into an application archive in TARGET, which can be a filename or a file-like object. If SOURCE is a directory, TARGET can be omitted and will default to the name of SOURCE with .pyz appended. The created application archive will have a shebang line specifying that it should run with INTERPRETER (there will be no shebang line if INTERPRETER is None), and a __main__.py which runs MAIN (if MAIN is not specified, an existing __main__.py will be used). It is an error to specify MAIN for anything other than a directory source with no __main__.py, and it is an error to omit MAIN if the directory has no __main__.py. """ # Are we copying an existing archive? source_is_file = False if hasattr(source, 'read') and hasattr(source, 'readline'): source_is_file = True else: source = pathlib.Path(source) if source.is_file(): source_is_file = True if source_is_file: _copy_archive(source, target, interpreter) return # We are creating a new archive from a directory. if not source.exists(): raise ZipAppError("Source does not exist") has_main = (source / '__main__.py').is_file() if main and has_main: raise ZipAppError( "Cannot specify entry point if the source has __main__.py") if not (main or has_main): raise ZipAppError("Archive has no entry point") main_py = None if main: # Check that main has the right format. mod, sep, fn = main.partition(':') mod_ok = all(part.isidentifier() for part in mod.split('.')) fn_ok = all(part.isidentifier() for part in fn.split('.')) if not (sep == ':' and mod_ok and fn_ok): raise ZipAppError("Invalid entry point: " + main) main_py = MAIN_TEMPLATE.format(module=mod, fn=fn) if target is None: target = source.with_suffix('.pyz') elif not hasattr(target, 'write'): target = pathlib.Path(target) with _maybe_open(target, 'wb') as fd: _write_file_prefix(fd, interpreter) compression = (zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED) with zipfile.ZipFile(fd, 'w', compression=compression) as z: for child in source.rglob('*'): arcname = child.relative_to(source) if filter is None or filter(arcname): z.write(child, arcname.as_posix()) if main_py: z.writestr('__main__.py', main_py.encode('utf-8')) if interpreter and not hasattr(target, 'write'): target.chmod(target.stat().st_mode | stat.S_IEXEC)
[ "def", "create_archive", "(", "source", ",", "target", "=", "None", ",", "interpreter", "=", "None", ",", "main", "=", "None", ",", "filter", "=", "None", ",", "compressed", "=", "False", ")", ":", "# Are we copying an existing archive?", "source_is_file", "=", "False", "if", "hasattr", "(", "source", ",", "'read'", ")", "and", "hasattr", "(", "source", ",", "'readline'", ")", ":", "source_is_file", "=", "True", "else", ":", "source", "=", "pathlib", ".", "Path", "(", "source", ")", "if", "source", ".", "is_file", "(", ")", ":", "source_is_file", "=", "True", "if", "source_is_file", ":", "_copy_archive", "(", "source", ",", "target", ",", "interpreter", ")", "return", "# We are creating a new archive from a directory.", "if", "not", "source", ".", "exists", "(", ")", ":", "raise", "ZipAppError", "(", "\"Source does not exist\"", ")", "has_main", "=", "(", "source", "/", "'__main__.py'", ")", ".", "is_file", "(", ")", "if", "main", "and", "has_main", ":", "raise", "ZipAppError", "(", "\"Cannot specify entry point if the source has __main__.py\"", ")", "if", "not", "(", "main", "or", "has_main", ")", ":", "raise", "ZipAppError", "(", "\"Archive has no entry point\"", ")", "main_py", "=", "None", "if", "main", ":", "# Check that main has the right format.", "mod", ",", "sep", ",", "fn", "=", "main", ".", "partition", "(", "':'", ")", "mod_ok", "=", "all", "(", "part", ".", "isidentifier", "(", ")", "for", "part", "in", "mod", ".", "split", "(", "'.'", ")", ")", "fn_ok", "=", "all", "(", "part", ".", "isidentifier", "(", ")", "for", "part", "in", "fn", ".", "split", "(", "'.'", ")", ")", "if", "not", "(", "sep", "==", "':'", "and", "mod_ok", "and", "fn_ok", ")", ":", "raise", "ZipAppError", "(", "\"Invalid entry point: \"", "+", "main", ")", "main_py", "=", "MAIN_TEMPLATE", ".", "format", "(", "module", "=", "mod", ",", "fn", "=", "fn", ")", "if", "target", "is", "None", ":", "target", "=", "source", ".", "with_suffix", "(", "'.pyz'", ")", "elif", "not", "hasattr", "(", "target", ",", "'write'", ")", ":", "target", "=", "pathlib", ".", "Path", "(", "target", ")", "with", "_maybe_open", "(", "target", ",", "'wb'", ")", "as", "fd", ":", "_write_file_prefix", "(", "fd", ",", "interpreter", ")", "compression", "=", "(", "zipfile", ".", "ZIP_DEFLATED", "if", "compressed", "else", "zipfile", ".", "ZIP_STORED", ")", "with", "zipfile", ".", "ZipFile", "(", "fd", ",", "'w'", ",", "compression", "=", "compression", ")", "as", "z", ":", "for", "child", "in", "source", ".", "rglob", "(", "'*'", ")", ":", "arcname", "=", "child", ".", "relative_to", "(", "source", ")", "if", "filter", "is", "None", "or", "filter", "(", "arcname", ")", ":", "z", ".", "write", "(", "child", ",", "arcname", ".", "as_posix", "(", ")", ")", "if", "main_py", ":", "z", ".", "writestr", "(", "'__main__.py'", ",", "main_py", ".", "encode", "(", "'utf-8'", ")", ")", "if", "interpreter", "and", "not", "hasattr", "(", "target", ",", "'write'", ")", ":", "target", ".", "chmod", "(", "target", ".", "stat", "(", ")", ".", "st_mode", "|", "stat", ".", "S_IEXEC", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/zipapp.py#L76-L147
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
Clipboard.Get
(*args, **kwargs)
return _misc_.Clipboard_Get(*args, **kwargs)
Get() -> Clipboard Returns global instance (wxTheClipboard) of the object.
Get() -> Clipboard
[ "Get", "()", "-", ">", "Clipboard" ]
def Get(*args, **kwargs): """ Get() -> Clipboard Returns global instance (wxTheClipboard) of the object. """ return _misc_.Clipboard_Get(*args, **kwargs)
[ "def", "Get", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Clipboard_Get", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L5906-L5912
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/masked/timectrl.py
python
TimeCtrl.SetInsertionPoint
(self, pos)
This override records the specified position and associated cell before calling base class' function. This is necessary to handle the optional spin button, because the insertion point is lost when the focus shifts to the spin button.
This override records the specified position and associated cell before calling base class' function. This is necessary to handle the optional spin button, because the insertion point is lost when the focus shifts to the spin button.
[ "This", "override", "records", "the", "specified", "position", "and", "associated", "cell", "before", "calling", "base", "class", "function", ".", "This", "is", "necessary", "to", "handle", "the", "optional", "spin", "button", "because", "the", "insertion", "point", "is", "lost", "when", "the", "focus", "shifts", "to", "the", "spin", "button", "." ]
def SetInsertionPoint(self, pos): """ This override records the specified position and associated cell before calling base class' function. This is necessary to handle the optional spin button, because the insertion point is lost when the focus shifts to the spin button. """ ## dbg('TimeCtrl::SetInsertionPoint', pos, indent=1) BaseMaskedTextCtrl.SetInsertionPoint(self, pos) # (causes EVT_TEXT event to fire) self.__posCurrent = self.GetInsertionPoint()
[ "def", "SetInsertionPoint", "(", "self", ",", "pos", ")", ":", "## dbg('TimeCtrl::SetInsertionPoint', pos, indent=1)", "BaseMaskedTextCtrl", ".", "SetInsertionPoint", "(", "self", ",", "pos", ")", "# (causes EVT_TEXT event to fire)", "self", ".", "__posCurrent", "=", "self", ".", "GetInsertionPoint", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/masked/timectrl.py#L1126-L1135
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/PRESUBMIT.py
python
_CheckHeadersHaveIncludeGuards
(input_api, output_api)
Ensures that all header files have include guards.
Ensures that all header files have include guards.
[ "Ensures", "that", "all", "header", "files", "have", "include", "guards", "." ]
def _CheckHeadersHaveIncludeGuards(input_api, output_api): """Ensures that all header files have include guards.""" file_inclusion_pattern = r'src/.+\.h' def FilterFile(affected_file): black_list = (_EXCLUDED_PATHS + input_api.DEFAULT_BLACK_LIST) return input_api.FilterSourceFile( affected_file, white_list=(file_inclusion_pattern, ), black_list=black_list) leading_src_pattern = input_api.re.compile(r'^src/') dash_dot_slash_pattern = input_api.re.compile(r'[-./]') def PathToGuardMacro(path): """Guards should be of the form V8_PATH_TO_FILE_WITHOUT_SRC_H_.""" x = input_api.re.sub(leading_src_pattern, 'v8_', path) x = input_api.re.sub(dash_dot_slash_pattern, '_', x) x = x.upper() + "_" return x problems = [] for f in input_api.AffectedSourceFiles(FilterFile): local_path = f.LocalPath() guard_macro = PathToGuardMacro(local_path) guard_patterns = [ input_api.re.compile(r'^#ifndef ' + guard_macro + '$'), input_api.re.compile(r'^#define ' + guard_macro + '$'), input_api.re.compile(r'^#endif // ' + guard_macro + '$')] skip_check_pattern = input_api.re.compile( r'^// PRESUBMIT_INTENTIONALLY_MISSING_INCLUDE_GUARD') found_patterns = [ False, False, False ] file_omitted = False for line in f.NewContents(): for i in range(len(guard_patterns)): if guard_patterns[i].match(line): found_patterns[i] = True if skip_check_pattern.match(line): file_omitted = True break if not file_omitted and not all(found_patterns): problems.append( '%s: Missing include guard \'%s\'' % (local_path, guard_macro)) if problems: return [output_api.PresubmitError( 'You added one or more header files without an appropriate\n' 'include guard. Add the include guard {#ifndef,#define,#endif}\n' 'triplet or omit the check entirely through the magic comment:\n' '"// PRESUBMIT_INTENTIONALLY_MISSING_INCLUDE_GUARD".', problems)] else: return []
[ "def", "_CheckHeadersHaveIncludeGuards", "(", "input_api", ",", "output_api", ")", ":", "file_inclusion_pattern", "=", "r'src/.+\\.h'", "def", "FilterFile", "(", "affected_file", ")", ":", "black_list", "=", "(", "_EXCLUDED_PATHS", "+", "input_api", ".", "DEFAULT_BLACK_LIST", ")", "return", "input_api", ".", "FilterSourceFile", "(", "affected_file", ",", "white_list", "=", "(", "file_inclusion_pattern", ",", ")", ",", "black_list", "=", "black_list", ")", "leading_src_pattern", "=", "input_api", ".", "re", ".", "compile", "(", "r'^src/'", ")", "dash_dot_slash_pattern", "=", "input_api", ".", "re", ".", "compile", "(", "r'[-./]'", ")", "def", "PathToGuardMacro", "(", "path", ")", ":", "\"\"\"Guards should be of the form V8_PATH_TO_FILE_WITHOUT_SRC_H_.\"\"\"", "x", "=", "input_api", ".", "re", ".", "sub", "(", "leading_src_pattern", ",", "'v8_'", ",", "path", ")", "x", "=", "input_api", ".", "re", ".", "sub", "(", "dash_dot_slash_pattern", ",", "'_'", ",", "x", ")", "x", "=", "x", ".", "upper", "(", ")", "+", "\"_\"", "return", "x", "problems", "=", "[", "]", "for", "f", "in", "input_api", ".", "AffectedSourceFiles", "(", "FilterFile", ")", ":", "local_path", "=", "f", ".", "LocalPath", "(", ")", "guard_macro", "=", "PathToGuardMacro", "(", "local_path", ")", "guard_patterns", "=", "[", "input_api", ".", "re", ".", "compile", "(", "r'^#ifndef '", "+", "guard_macro", "+", "'$'", ")", ",", "input_api", ".", "re", ".", "compile", "(", "r'^#define '", "+", "guard_macro", "+", "'$'", ")", ",", "input_api", ".", "re", ".", "compile", "(", "r'^#endif // '", "+", "guard_macro", "+", "'$'", ")", "]", "skip_check_pattern", "=", "input_api", ".", "re", ".", "compile", "(", "r'^// PRESUBMIT_INTENTIONALLY_MISSING_INCLUDE_GUARD'", ")", "found_patterns", "=", "[", "False", ",", "False", ",", "False", "]", "file_omitted", "=", "False", "for", "line", "in", "f", ".", "NewContents", "(", ")", ":", "for", "i", "in", "range", "(", "len", "(", "guard_patterns", ")", ")", ":", "if", "guard_patterns", "[", "i", "]", ".", "match", "(", "line", ")", ":", "found_patterns", "[", "i", "]", "=", "True", "if", "skip_check_pattern", ".", "match", "(", "line", ")", ":", "file_omitted", "=", "True", "break", "if", "not", "file_omitted", "and", "not", "all", "(", "found_patterns", ")", ":", "problems", ".", "append", "(", "'%s: Missing include guard \\'%s\\''", "%", "(", "local_path", ",", "guard_macro", ")", ")", "if", "problems", ":", "return", "[", "output_api", ".", "PresubmitError", "(", "'You added one or more header files without an appropriate\\n'", "'include guard. Add the include guard {#ifndef,#define,#endif}\\n'", "'triplet or omit the check entirely through the magic comment:\\n'", "'\"// PRESUBMIT_INTENTIONALLY_MISSING_INCLUDE_GUARD\".'", ",", "problems", ")", "]", "else", ":", "return", "[", "]" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/PRESUBMIT.py#L156-L209
CoolProp/CoolProp
381c8535e5dec3eec27ad430ebbfff8bc9dfc008
dev/scripts/fit_ancillary_ODRPACK.py
python
saturation_density
(Ref, ClassName, form='A', LV='L', perc_error_allowed=0.3, fName=None, add_critical=True)
return the_string
Parameters ---------- Ref : string The fluid name for the fluid that will be used to generate the saturation data ClassName : The name of the class that will be used in the C++ code form : string If ``'A'``, use a term of the form
[]
def saturation_density(Ref, ClassName, form='A', LV='L', perc_error_allowed=0.3, fName=None, add_critical=True): """ Parameters ---------- Ref : string The fluid name for the fluid that will be used to generate the saturation data ClassName : The name of the class that will be used in the C++ code form : string If ``'A'``, use a term of the form """ if fName is None: Tc = Props(Ref, 'Tcrit') pc = Props(Ref, 'pcrit') rhoc = Props(Ref, 'rhocrit') Tmin = Props(Ref, 'Tmin') print("%s %s %s" % (Ref, Tmin, Props(Ref, 'Ttriple'))) TT = np.linspace(Tmin, Tc - 1, 1000) TT = list(TT) # Add temperatures around the critical temperature if add_critical: for dT in [1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1]: TT.append(Tc - dT) TT = np.array(sorted(TT)) p = Props('P', 'T', TT, 'Q', 0, Ref) rhoL = Props('D', 'T', TT, 'Q', 0, Ref) rhoV = Props('D', 'T', TT, 'Q', 1, Ref) else: Tc = 423.27 pc = 3533 rhoc = 470 Tmin = 273 lines = open(fName, 'r').readlines() TT, p, rhoL, rhoV = [], [], [], [] for line in lines: _T, _p, _rhoL, _rhoV = line.split(' ') TT.append(float(_T)) p.append(float(_p)) rhoL.append(float(_rhoL)) rhoV.append(float(_rhoV)) TT = np.array(TT) # Start with a large library of potential powers n = [i / 6.0 for i in range(1, 200)] # +[0.35+i/200.0 for i in range(1,70)]+[0.05+0.01*i for i in range(1,70)] x = 1.0 - TT / Tc if LV == 'L': rho_EOS = rhoL elif LV == 'V': rho_EOS = rhoV else: raise ValueError if form == 'A': y = np.array(rho_EOS) / rhoc - 1 elif form == 'B': y = (np.log(rho_EOS) - np.log(rhoc)) * TT / Tc else: raise ValueError max_abserror = 0 while len(n) > 3: print("%s %s" % (max_abserror, len(n))) def f_p(B, x): # B is a vector of the parameters. # x is an array of the current x values. return sum([_B * x**(_n) for _B, _n in zip(B, n)]) linear = Model(f_p) mydata = Data(x, y) myodr = ODR(mydata, linear, beta0=[0] * len(n)) myoutput = myodr.run() beta = myoutput.beta sd = myoutput.sd_beta if form == 'A': rho_fit = (f_p(myoutput.beta, x) + 1) * rhoc elif form == 'B': rho_fit = np.exp(f_p(myoutput.beta, x) * Tc / TT) * rhoc else: raise ValueError print('first,last %s %s %s %s %s %s' % (TT[0], TT[-1], rho_fit[0], rho_fit[-1], rho_EOS[0], rho_EOS[-1])) max_abserror = np.max(np.abs(rho_fit / rho_EOS - 1)) * 100 dropped_indices = [i for i in range(len(n)) if abs(sd[i]) < 1e-15] if dropped_indices: for i in reversed(sorted(dropped_indices)): n.pop(i) print('popping... %s terms remaining' % len(n)) continue if max_abserror > perc_error_allowed: break # The last good run will be used else: print(max_abserror) Ncoeffs = str(list(myoutput.beta)).lstrip('[').rstrip(']') tcoeffs = str(n).lstrip('[').rstrip(']') maxerror = max_abserror if form == 'A': code_template = textwrap.dedent( """ for (int i=1; i<={count:d}; i++) {{ summer += N[i]*pow(theta,t[i]); }} return reduce.rho*(summer+1); """.format(count=len(n)) ) elif form == 'B': code_template = textwrap.dedent( """ for (int i=1; i<={count:d}; i++) {{ summer += N[i]*pow(theta,t[i]); }} return reduce.rho*exp(reduce.T/T*summer); """.format(count=len(n)) ) else: raise ValueError # Find the least significant entry (the one with the largest relative standard error) # and remove it n.pop(np.argmax(np.abs(sd / beta))) # Remove elements that are not template = textwrap.dedent( """ double {name:s}Class::rhosat{LV:s}(double T) {{ // Maximum absolute error is {error:f} % between {Tmin:f} K and {Tmax:f} K const double t[] = {{0, {tcoeffs:s}}}; const double N[] = {{0, {Ncoeffs:s}}}; double summer=0,theta; theta=1-T/reduce.T; \t{code:s} }} """) the_string = template.format(tcoeffs=tcoeffs, Ncoeffs=Ncoeffs, name=ClassName, Tmin=Tmin, Tmax=TT[-1], error=maxerror, code=code_template, LV=LV ) f = open('anc.txt', 'a') f.write(the_string) f.close() return the_string
[ "def", "saturation_density", "(", "Ref", ",", "ClassName", ",", "form", "=", "'A'", ",", "LV", "=", "'L'", ",", "perc_error_allowed", "=", "0.3", ",", "fName", "=", "None", ",", "add_critical", "=", "True", ")", ":", "if", "fName", "is", "None", ":", "Tc", "=", "Props", "(", "Ref", ",", "'Tcrit'", ")", "pc", "=", "Props", "(", "Ref", ",", "'pcrit'", ")", "rhoc", "=", "Props", "(", "Ref", ",", "'rhocrit'", ")", "Tmin", "=", "Props", "(", "Ref", ",", "'Tmin'", ")", "print", "(", "\"%s %s %s\"", "%", "(", "Ref", ",", "Tmin", ",", "Props", "(", "Ref", ",", "'Ttriple'", ")", ")", ")", "TT", "=", "np", ".", "linspace", "(", "Tmin", ",", "Tc", "-", "1", ",", "1000", ")", "TT", "=", "list", "(", "TT", ")", "# Add temperatures around the critical temperature", "if", "add_critical", ":", "for", "dT", "in", "[", "1e-10", ",", "1e-9", ",", "1e-8", ",", "1e-7", ",", "1e-6", ",", "1e-5", ",", "1e-4", ",", "1e-3", ",", "1e-2", ",", "1e-1", "]", ":", "TT", ".", "append", "(", "Tc", "-", "dT", ")", "TT", "=", "np", ".", "array", "(", "sorted", "(", "TT", ")", ")", "p", "=", "Props", "(", "'P'", ",", "'T'", ",", "TT", ",", "'Q'", ",", "0", ",", "Ref", ")", "rhoL", "=", "Props", "(", "'D'", ",", "'T'", ",", "TT", ",", "'Q'", ",", "0", ",", "Ref", ")", "rhoV", "=", "Props", "(", "'D'", ",", "'T'", ",", "TT", ",", "'Q'", ",", "1", ",", "Ref", ")", "else", ":", "Tc", "=", "423.27", "pc", "=", "3533", "rhoc", "=", "470", "Tmin", "=", "273", "lines", "=", "open", "(", "fName", ",", "'r'", ")", ".", "readlines", "(", ")", "TT", ",", "p", ",", "rhoL", ",", "rhoV", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "for", "line", "in", "lines", ":", "_T", ",", "_p", ",", "_rhoL", ",", "_rhoV", "=", "line", ".", "split", "(", "' '", ")", "TT", ".", "append", "(", "float", "(", "_T", ")", ")", "p", ".", "append", "(", "float", "(", "_p", ")", ")", "rhoL", ".", "append", "(", "float", "(", "_rhoL", ")", ")", "rhoV", ".", "append", "(", "float", "(", "_rhoV", ")", ")", "TT", "=", "np", ".", "array", "(", "TT", ")", "# Start with a large library of potential powers", "n", "=", "[", "i", "/", "6.0", "for", "i", "in", "range", "(", "1", ",", "200", ")", "]", "# +[0.35+i/200.0 for i in range(1,70)]+[0.05+0.01*i for i in range(1,70)]", "x", "=", "1.0", "-", "TT", "/", "Tc", "if", "LV", "==", "'L'", ":", "rho_EOS", "=", "rhoL", "elif", "LV", "==", "'V'", ":", "rho_EOS", "=", "rhoV", "else", ":", "raise", "ValueError", "if", "form", "==", "'A'", ":", "y", "=", "np", ".", "array", "(", "rho_EOS", ")", "/", "rhoc", "-", "1", "elif", "form", "==", "'B'", ":", "y", "=", "(", "np", ".", "log", "(", "rho_EOS", ")", "-", "np", ".", "log", "(", "rhoc", ")", ")", "*", "TT", "/", "Tc", "else", ":", "raise", "ValueError", "max_abserror", "=", "0", "while", "len", "(", "n", ")", ">", "3", ":", "print", "(", "\"%s %s\"", "%", "(", "max_abserror", ",", "len", "(", "n", ")", ")", ")", "def", "f_p", "(", "B", ",", "x", ")", ":", "# B is a vector of the parameters.", "# x is an array of the current x values.", "return", "sum", "(", "[", "_B", "*", "x", "**", "(", "_n", ")", "for", "_B", ",", "_n", "in", "zip", "(", "B", ",", "n", ")", "]", ")", "linear", "=", "Model", "(", "f_p", ")", "mydata", "=", "Data", "(", "x", ",", "y", ")", "myodr", "=", "ODR", "(", "mydata", ",", "linear", ",", "beta0", "=", "[", "0", "]", "*", "len", "(", "n", ")", ")", "myoutput", "=", "myodr", ".", "run", "(", ")", "beta", "=", "myoutput", ".", "beta", "sd", "=", "myoutput", ".", "sd_beta", "if", "form", "==", "'A'", ":", "rho_fit", "=", "(", "f_p", "(", "myoutput", ".", "beta", ",", "x", ")", "+", "1", ")", "*", "rhoc", "elif", "form", "==", "'B'", ":", "rho_fit", "=", "np", ".", "exp", "(", "f_p", "(", "myoutput", ".", "beta", ",", "x", ")", "*", "Tc", "/", "TT", ")", "*", "rhoc", "else", ":", "raise", "ValueError", "print", "(", "'first,last %s %s %s %s %s %s'", "%", "(", "TT", "[", "0", "]", ",", "TT", "[", "-", "1", "]", ",", "rho_fit", "[", "0", "]", ",", "rho_fit", "[", "-", "1", "]", ",", "rho_EOS", "[", "0", "]", ",", "rho_EOS", "[", "-", "1", "]", ")", ")", "max_abserror", "=", "np", ".", "max", "(", "np", ".", "abs", "(", "rho_fit", "/", "rho_EOS", "-", "1", ")", ")", "*", "100", "dropped_indices", "=", "[", "i", "for", "i", "in", "range", "(", "len", "(", "n", ")", ")", "if", "abs", "(", "sd", "[", "i", "]", ")", "<", "1e-15", "]", "if", "dropped_indices", ":", "for", "i", "in", "reversed", "(", "sorted", "(", "dropped_indices", ")", ")", ":", "n", ".", "pop", "(", "i", ")", "print", "(", "'popping... %s terms remaining'", "%", "len", "(", "n", ")", ")", "continue", "if", "max_abserror", ">", "perc_error_allowed", ":", "break", "# The last good run will be used", "else", ":", "print", "(", "max_abserror", ")", "Ncoeffs", "=", "str", "(", "list", "(", "myoutput", ".", "beta", ")", ")", ".", "lstrip", "(", "'['", ")", ".", "rstrip", "(", "']'", ")", "tcoeffs", "=", "str", "(", "n", ")", ".", "lstrip", "(", "'['", ")", ".", "rstrip", "(", "']'", ")", "maxerror", "=", "max_abserror", "if", "form", "==", "'A'", ":", "code_template", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n for (int i=1; i<={count:d}; i++)\n {{\n summer += N[i]*pow(theta,t[i]);\n }}\n return reduce.rho*(summer+1);\n \"\"\"", ".", "format", "(", "count", "=", "len", "(", "n", ")", ")", ")", "elif", "form", "==", "'B'", ":", "code_template", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n for (int i=1; i<={count:d}; i++)\n {{\n summer += N[i]*pow(theta,t[i]);\n }}\n return reduce.rho*exp(reduce.T/T*summer);\n \"\"\"", ".", "format", "(", "count", "=", "len", "(", "n", ")", ")", ")", "else", ":", "raise", "ValueError", "# Find the least significant entry (the one with the largest relative standard error)", "# and remove it", "n", ".", "pop", "(", "np", ".", "argmax", "(", "np", ".", "abs", "(", "sd", "/", "beta", ")", ")", ")", "# Remove elements that are not", "template", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n double {name:s}Class::rhosat{LV:s}(double T)\n {{\n // Maximum absolute error is {error:f} % between {Tmin:f} K and {Tmax:f} K\n const double t[] = {{0, {tcoeffs:s}}};\n const double N[] = {{0, {Ncoeffs:s}}};\n double summer=0,theta;\n theta=1-T/reduce.T;\n \\t{code:s}\n }}\n \"\"\"", ")", "the_string", "=", "template", ".", "format", "(", "tcoeffs", "=", "tcoeffs", ",", "Ncoeffs", "=", "Ncoeffs", ",", "name", "=", "ClassName", ",", "Tmin", "=", "Tmin", ",", "Tmax", "=", "TT", "[", "-", "1", "]", ",", "error", "=", "maxerror", ",", "code", "=", "code_template", ",", "LV", "=", "LV", ")", "f", "=", "open", "(", "'anc.txt'", ",", "'a'", ")", "f", ".", "write", "(", "the_string", ")", "f", ".", "close", "(", ")", "return", "the_string" ]
https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/dev/scripts/fit_ancillary_ODRPACK.py#L22-L181
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/CoSimulationApplication/CoSimulationApplication.py
python
__ModuleInitDetail
()
Create a DataCommunicator that only contains rank zero and is undefined in other ranks This is necessary for solvers that can only run in serial It is defined as a function to avoid polluting the Kratos namespace with local variables.
Create a DataCommunicator that only contains rank zero and is undefined in other ranks This is necessary for solvers that can only run in serial It is defined as a function to avoid polluting the Kratos namespace with local variables.
[ "Create", "a", "DataCommunicator", "that", "only", "contains", "rank", "zero", "and", "is", "undefined", "in", "other", "ranks", "This", "is", "necessary", "for", "solvers", "that", "can", "only", "run", "in", "serial", "It", "is", "defined", "as", "a", "function", "to", "avoid", "polluting", "the", "Kratos", "namespace", "with", "local", "variables", "." ]
def __ModuleInitDetail(): """ Create a DataCommunicator that only contains rank zero and is undefined in other ranks This is necessary for solvers that can only run in serial It is defined as a function to avoid polluting the Kratos namespace with local variables. """ import KratosMultiphysics as KM if KM.IsDistributedRun(): from KratosMultiphysics.mpi import DataCommunicatorFactory data_comm_name = "co_simulation_data_comm_rank_zero" world_data_comm = KM.ParallelEnvironment.GetDataCommunicator("World") ranks = [0] DataCommunicatorFactory.CreateFromRanksAndRegister(world_data_comm, ranks, data_comm_name)
[ "def", "__ModuleInitDetail", "(", ")", ":", "import", "KratosMultiphysics", "as", "KM", "if", "KM", ".", "IsDistributedRun", "(", ")", ":", "from", "KratosMultiphysics", ".", "mpi", "import", "DataCommunicatorFactory", "data_comm_name", "=", "\"co_simulation_data_comm_rank_zero\"", "world_data_comm", "=", "KM", ".", "ParallelEnvironment", ".", "GetDataCommunicator", "(", "\"World\"", ")", "ranks", "=", "[", "0", "]", "DataCommunicatorFactory", ".", "CreateFromRanksAndRegister", "(", "world_data_comm", ",", "ranks", ",", "data_comm_name", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/CoSimulationApplication/CoSimulationApplication.py#L9-L21
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
tools/query_cmp/src/lib/compare_rrset.py
python
header_cmp
(buf, msg1, msg2, diff)
return(True)
Compare the header of msg1 and msg2. @param buf: the formatted difference for output. @type buf: dict @param diff: the key is each flag in the header, the value is True for different and False for same @type diff: dict
Compare the header of msg1 and msg2.
[ "Compare", "the", "header", "of", "msg1", "and", "msg2", "." ]
def header_cmp(buf, msg1, msg2, diff): """ Compare the header of msg1 and msg2. @param buf: the formatted difference for output. @type buf: dict @param diff: the key is each flag in the header, the value is True for different and False for same @type diff: dict """ header1 = get_header_field(msg1) header2 = get_header_field(msg2) list = ['id', 'qr', 'opcode', 'aa', 'tc', 'rd', \ 'ra', 'ad', 'cd', 'rcode', 'qdcount', 'ancount', \ 'nscount', 'arcount'] for header in list: diff[header] = header1[header] != header2[header] buf['header'] = '' for key in list: if diff[key]: buf['header'] = buf['header'] + \ '%-*s%-*s%-*s\n' % (POS_TITLE, key, \ POS_LEFT, header1[key], POS_LEFT, \ header2[key]) for key in diff.keys(): if diff[key]: return(False) return(True)
[ "def", "header_cmp", "(", "buf", ",", "msg1", ",", "msg2", ",", "diff", ")", ":", "header1", "=", "get_header_field", "(", "msg1", ")", "header2", "=", "get_header_field", "(", "msg2", ")", "list", "=", "[", "'id'", ",", "'qr'", ",", "'opcode'", ",", "'aa'", ",", "'tc'", ",", "'rd'", ",", "'ra'", ",", "'ad'", ",", "'cd'", ",", "'rcode'", ",", "'qdcount'", ",", "'ancount'", ",", "'nscount'", ",", "'arcount'", "]", "for", "header", "in", "list", ":", "diff", "[", "header", "]", "=", "header1", "[", "header", "]", "!=", "header2", "[", "header", "]", "buf", "[", "'header'", "]", "=", "''", "for", "key", "in", "list", ":", "if", "diff", "[", "key", "]", ":", "buf", "[", "'header'", "]", "=", "buf", "[", "'header'", "]", "+", "'%-*s%-*s%-*s\\n'", "%", "(", "POS_TITLE", ",", "key", ",", "POS_LEFT", ",", "header1", "[", "key", "]", ",", "POS_LEFT", ",", "header2", "[", "key", "]", ")", "for", "key", "in", "diff", ".", "keys", "(", ")", ":", "if", "diff", "[", "key", "]", ":", "return", "(", "False", ")", "return", "(", "True", ")" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/tools/query_cmp/src/lib/compare_rrset.py#L46-L77
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Base/Python/slicer/util.py
python
updateVolumeFromArray
(volumeNode, narray)
Sets voxels of a volume node from a numpy array. :raises RuntimeError: in case of failure Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, voxel values in the volume node will not change. Dimensions and data size of the source numpy array does not have to match the current content of the volume node.
Sets voxels of a volume node from a numpy array.
[ "Sets", "voxels", "of", "a", "volume", "node", "from", "a", "numpy", "array", "." ]
def updateVolumeFromArray(volumeNode, narray): """Sets voxels of a volume node from a numpy array. :raises RuntimeError: in case of failure Voxels values are deep-copied, therefore if the numpy array is modified after calling this method, voxel values in the volume node will not change. Dimensions and data size of the source numpy array does not have to match the current content of the volume node. """ vshape = tuple(reversed(narray.shape)) if len(vshape) == 3: # Scalar volume vcomponents = 1 elif len(vshape) == 4: # Vector volume vcomponents = vshape[0] vshape = vshape[1:4] else: # TODO: add support for tensor volumes raise RuntimeError("Unsupported numpy array shape: "+str(narray.shape)) vimage = volumeNode.GetImageData() if not vimage: import vtk vimage = vtk.vtkImageData() volumeNode.SetAndObserveImageData(vimage) import vtk.util.numpy_support vtype = vtk.util.numpy_support.get_vtk_array_type(narray.dtype) # Volumes with "long long" scalar type are not rendered correctly. # Probably this could be fixed in VTK or Slicer but for now just reject it. if vtype == vtk.VTK_LONG_LONG: raise RuntimeError("Unsupported numpy array type: long long") vimage.SetDimensions(vshape) vimage.AllocateScalars(vtype, vcomponents) narrayTarget = arrayFromVolume(volumeNode) narrayTarget[:] = narray # Notify the application that image data is changed # (same notifications as in vtkMRMLVolumeNode.SetImageDataConnection) import slicer volumeNode.StorableModified() volumeNode.Modified() volumeNode.InvokeEvent(slicer.vtkMRMLVolumeNode.ImageDataModifiedEvent, volumeNode)
[ "def", "updateVolumeFromArray", "(", "volumeNode", ",", "narray", ")", ":", "vshape", "=", "tuple", "(", "reversed", "(", "narray", ".", "shape", ")", ")", "if", "len", "(", "vshape", ")", "==", "3", ":", "# Scalar volume", "vcomponents", "=", "1", "elif", "len", "(", "vshape", ")", "==", "4", ":", "# Vector volume", "vcomponents", "=", "vshape", "[", "0", "]", "vshape", "=", "vshape", "[", "1", ":", "4", "]", "else", ":", "# TODO: add support for tensor volumes", "raise", "RuntimeError", "(", "\"Unsupported numpy array shape: \"", "+", "str", "(", "narray", ".", "shape", ")", ")", "vimage", "=", "volumeNode", ".", "GetImageData", "(", ")", "if", "not", "vimage", ":", "import", "vtk", "vimage", "=", "vtk", ".", "vtkImageData", "(", ")", "volumeNode", ".", "SetAndObserveImageData", "(", "vimage", ")", "import", "vtk", ".", "util", ".", "numpy_support", "vtype", "=", "vtk", ".", "util", ".", "numpy_support", ".", "get_vtk_array_type", "(", "narray", ".", "dtype", ")", "# Volumes with \"long long\" scalar type are not rendered correctly.", "# Probably this could be fixed in VTK or Slicer but for now just reject it.", "if", "vtype", "==", "vtk", ".", "VTK_LONG_LONG", ":", "raise", "RuntimeError", "(", "\"Unsupported numpy array type: long long\"", ")", "vimage", ".", "SetDimensions", "(", "vshape", ")", "vimage", ".", "AllocateScalars", "(", "vtype", ",", "vcomponents", ")", "narrayTarget", "=", "arrayFromVolume", "(", "volumeNode", ")", "narrayTarget", "[", ":", "]", "=", "narray", "# Notify the application that image data is changed", "# (same notifications as in vtkMRMLVolumeNode.SetImageDataConnection)", "import", "slicer", "volumeNode", ".", "StorableModified", "(", ")", "volumeNode", ".", "Modified", "(", ")", "volumeNode", ".", "InvokeEvent", "(", "slicer", ".", "vtkMRMLVolumeNode", ".", "ImageDataModifiedEvent", ",", "volumeNode", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Base/Python/slicer/util.py#L1950-L1997
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
DateTime_GetCurrentMonth
(*args, **kwargs)
return _misc_.DateTime_GetCurrentMonth(*args, **kwargs)
DateTime_GetCurrentMonth(int cal=Gregorian) -> int
DateTime_GetCurrentMonth(int cal=Gregorian) -> int
[ "DateTime_GetCurrentMonth", "(", "int", "cal", "=", "Gregorian", ")", "-", ">", "int" ]
def DateTime_GetCurrentMonth(*args, **kwargs): """DateTime_GetCurrentMonth(int cal=Gregorian) -> int""" return _misc_.DateTime_GetCurrentMonth(*args, **kwargs)
[ "def", "DateTime_GetCurrentMonth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_GetCurrentMonth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L4245-L4247
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/quantize_wrapper.py
python
QuantizeWrapper._weight_name
(name)
return name.split(':')[0].split('/')[-1]
Extracts the weight name from the full TensorFlow variable name. For example, returns 'kernel' for 'dense_2/kernel:0'. Args: name: TensorFlow variable name. Returns: Extracted weight name.
Extracts the weight name from the full TensorFlow variable name.
[ "Extracts", "the", "weight", "name", "from", "the", "full", "TensorFlow", "variable", "name", "." ]
def _weight_name(name): """Extracts the weight name from the full TensorFlow variable name. For example, returns 'kernel' for 'dense_2/kernel:0'. Args: name: TensorFlow variable name. Returns: Extracted weight name. """ return name.split(':')[0].split('/')[-1]
[ "def", "_weight_name", "(", "name", ")", ":", "return", "name", ".", "split", "(", "':'", ")", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/quantization/keras/quantize_wrapper.py#L79-L90
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
tools/performance/benchmark_tool.py
python
CpuSpeedSettings.set_cpu_governor
(self, governor)
Set the CPU governor to the given name string.
Set the CPU governor to the given name string.
[ "Set", "the", "CPU", "governor", "to", "the", "given", "name", "string", "." ]
def set_cpu_governor(self, governor): """Set the CPU governor to the given name string.""" sudo('cpupower', 'frequency-set', '--governor', governor)
[ "def", "set_cpu_governor", "(", "self", ",", "governor", ")", ":", "sudo", "(", "'cpupower'", ",", "'frequency-set'", ",", "'--governor'", ",", "governor", ")" ]
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/tools/performance/benchmark_tool.py#L89-L91
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/python/google/protobuf/service_reflection.py
python
_ServiceStubBuilder.__init__
(self, service_descriptor)
Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class.
Initializes an instance of the service stub class builder.
[ "Initializes", "an", "instance", "of", "the", "service", "stub", "class", "builder", "." ]
def __init__(self, service_descriptor): """Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class. """ self.descriptor = service_descriptor
[ "def", "__init__", "(", "self", ",", "service_descriptor", ")", ":", "self", ".", "descriptor", "=", "service_descriptor" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/python/google/protobuf/service_reflection.py#L242-L249
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/mailbox.py
python
Mailbox.get_message
(self, key)
Return a Message representation or raise a KeyError.
Return a Message representation or raise a KeyError.
[ "Return", "a", "Message", "representation", "or", "raise", "a", "KeyError", "." ]
def get_message(self, key): """Return a Message representation or raise a KeyError.""" raise NotImplementedError('Method must be implemented by subclass')
[ "def", "get_message", "(", "self", ",", "key", ")", ":", "raise", "NotImplementedError", "(", "'Method must be implemented by subclass'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mailbox.py#L78-L80
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/jinja2/debug.py
python
ProcessedTraceback.render_as_text
(self, limit=None)
return ''.join(lines).rstrip()
Return a string with the traceback.
Return a string with the traceback.
[ "Return", "a", "string", "with", "the", "traceback", "." ]
def render_as_text(self, limit=None): """Return a string with the traceback.""" lines = traceback.format_exception(self.exc_type, self.exc_value, self.frames[0], limit=limit) return ''.join(lines).rstrip()
[ "def", "render_as_text", "(", "self", ",", "limit", "=", "None", ")", ":", "lines", "=", "traceback", ".", "format_exception", "(", "self", ".", "exc_type", ",", "self", ".", "exc_value", ",", "self", ".", "frames", "[", "0", "]", ",", "limit", "=", "limit", ")", "return", "''", ".", "join", "(", "lines", ")", ".", "rstrip", "(", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/debug.py#L97-L101
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/interpolate/_fitpack_impl.py
python
bisplev
(x, y, tck, dx=0, dy=0)
return z[0][0]
Evaluate a bivariate B-spline and its derivatives. Return a rank-2 array of spline function values (or spline derivative values) at points given by the cross-product of the rank-1 arrays `x` and `y`. In special cases, return an array or just a float if either `x` or `y` or both are floats. Based on BISPEV from FITPACK. Parameters ---------- x, y : ndarray Rank-1 arrays specifying the domain over which to evaluate the spline or its derivative. tck : tuple A sequence of length 5 returned by `bisplrep` containing the knot locations, the coefficients, and the degree of the spline: [tx, ty, c, kx, ky]. dx, dy : int, optional The orders of the partial derivatives in `x` and `y` respectively. Returns ------- vals : ndarray The B-spline or its derivative evaluated over the set formed by the cross-product of `x` and `y`. See Also -------- splprep, splrep, splint, sproot, splev UnivariateSpline, BivariateSpline Notes ----- See `bisplrep` to generate the `tck` representation. References ---------- .. [1] Dierckx P. : An algorithm for surface fitting with spline functions Ima J. Numer. Anal. 1 (1981) 267-283. .. [2] Dierckx P. : An algorithm for surface fitting with spline functions report tw50, Dept. Computer Science,K.U.Leuven, 1980. .. [3] Dierckx P. : Curve and surface fitting with splines, Monographs on Numerical Analysis, Oxford University Press, 1993.
Evaluate a bivariate B-spline and its derivatives.
[ "Evaluate", "a", "bivariate", "B", "-", "spline", "and", "its", "derivatives", "." ]
def bisplev(x, y, tck, dx=0, dy=0): """ Evaluate a bivariate B-spline and its derivatives. Return a rank-2 array of spline function values (or spline derivative values) at points given by the cross-product of the rank-1 arrays `x` and `y`. In special cases, return an array or just a float if either `x` or `y` or both are floats. Based on BISPEV from FITPACK. Parameters ---------- x, y : ndarray Rank-1 arrays specifying the domain over which to evaluate the spline or its derivative. tck : tuple A sequence of length 5 returned by `bisplrep` containing the knot locations, the coefficients, and the degree of the spline: [tx, ty, c, kx, ky]. dx, dy : int, optional The orders of the partial derivatives in `x` and `y` respectively. Returns ------- vals : ndarray The B-spline or its derivative evaluated over the set formed by the cross-product of `x` and `y`. See Also -------- splprep, splrep, splint, sproot, splev UnivariateSpline, BivariateSpline Notes ----- See `bisplrep` to generate the `tck` representation. References ---------- .. [1] Dierckx P. : An algorithm for surface fitting with spline functions Ima J. Numer. Anal. 1 (1981) 267-283. .. [2] Dierckx P. : An algorithm for surface fitting with spline functions report tw50, Dept. Computer Science,K.U.Leuven, 1980. .. [3] Dierckx P. : Curve and surface fitting with splines, Monographs on Numerical Analysis, Oxford University Press, 1993. """ tx, ty, c, kx, ky = tck if not (0 <= dx < kx): raise ValueError("0 <= dx = %d < kx = %d must hold" % (dx, kx)) if not (0 <= dy < ky): raise ValueError("0 <= dy = %d < ky = %d must hold" % (dy, ky)) x, y = map(atleast_1d, [x, y]) if (len(x.shape) != 1) or (len(y.shape) != 1): raise ValueError("First two entries should be rank-1 arrays.") z, ier = _fitpack._bispev(tx, ty, c, kx, ky, x, y, dx, dy) if ier == 10: raise ValueError("Invalid input data") if ier: raise TypeError("An error occurred") z.shape = len(x), len(y) if len(z) > 1: return z if len(z[0]) > 1: return z[0] return z[0][0]
[ "def", "bisplev", "(", "x", ",", "y", ",", "tck", ",", "dx", "=", "0", ",", "dy", "=", "0", ")", ":", "tx", ",", "ty", ",", "c", ",", "kx", ",", "ky", "=", "tck", "if", "not", "(", "0", "<=", "dx", "<", "kx", ")", ":", "raise", "ValueError", "(", "\"0 <= dx = %d < kx = %d must hold\"", "%", "(", "dx", ",", "kx", ")", ")", "if", "not", "(", "0", "<=", "dy", "<", "ky", ")", ":", "raise", "ValueError", "(", "\"0 <= dy = %d < ky = %d must hold\"", "%", "(", "dy", ",", "ky", ")", ")", "x", ",", "y", "=", "map", "(", "atleast_1d", ",", "[", "x", ",", "y", "]", ")", "if", "(", "len", "(", "x", ".", "shape", ")", "!=", "1", ")", "or", "(", "len", "(", "y", ".", "shape", ")", "!=", "1", ")", ":", "raise", "ValueError", "(", "\"First two entries should be rank-1 arrays.\"", ")", "z", ",", "ier", "=", "_fitpack", ".", "_bispev", "(", "tx", ",", "ty", ",", "c", ",", "kx", ",", "ky", ",", "x", ",", "y", ",", "dx", ",", "dy", ")", "if", "ier", "==", "10", ":", "raise", "ValueError", "(", "\"Invalid input data\"", ")", "if", "ier", ":", "raise", "TypeError", "(", "\"An error occurred\"", ")", "z", ".", "shape", "=", "len", "(", "x", ")", ",", "len", "(", "y", ")", "if", "len", "(", "z", ")", ">", "1", ":", "return", "z", "if", "len", "(", "z", "[", "0", "]", ")", ">", "1", ":", "return", "z", "[", "0", "]", "return", "z", "[", "0", "]", "[", "0", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/interpolate/_fitpack_impl.py#L991-L1057
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/topics.py
python
_PublisherImpl.get_stats
(self)
return (self.resolved_name, self.message_data_sent, [(c.id, c.stat_bytes, c.stat_num_msg, not c.done) for c in conn] )
Get the stats for this topic publisher @return: stats for topic in getBusStats() publisher format:: [topicName, messageDataBytes, connStats], where connStats is:: [id, bytes, numMessages, connected]* @rtype: list
Get the stats for this topic publisher
[ "Get", "the", "stats", "for", "this", "topic", "publisher" ]
def get_stats(self): # STATS """ Get the stats for this topic publisher @return: stats for topic in getBusStats() publisher format:: [topicName, messageDataBytes, connStats], where connStats is:: [id, bytes, numMessages, connected]* @rtype: list """ # save reference to avoid lock conn = self.connections return (self.resolved_name, self.message_data_sent, [(c.id, c.stat_bytes, c.stat_num_msg, not c.done) for c in conn] )
[ "def", "get_stats", "(", "self", ")", ":", "# STATS", "# save reference to avoid lock", "conn", "=", "self", ".", "connections", "return", "(", "self", ".", "resolved_name", ",", "self", ".", "message_data_sent", ",", "[", "(", "c", ".", "id", ",", "c", ".", "stat_bytes", ",", "c", ".", "stat_num_msg", ",", "not", "c", ".", "done", ")", "for", "c", "in", "conn", "]", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/topics.py#L952-L964
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/encoding_stage.py
python
_tf_style_update_state
(update_state_fn)
return actual_initial_state_fn
Method decorator for `tf_style_adaptive_encoding_stage`.
Method decorator for `tf_style_adaptive_encoding_stage`.
[ "Method", "decorator", "for", "tf_style_adaptive_encoding_stage", "." ]
def _tf_style_update_state(update_state_fn): """Method decorator for `tf_style_adaptive_encoding_stage`.""" def actual_initial_state_fn(self, state, state_update_tensors, name=None): """Modified `update_state` method.""" values = list(state.values()) + list(state_update_tensors.values()) with tf.compat.v1.name_scope(name, self.name + UPDATE_STATE_SCOPE_SUFFIX, values): state = tf.nest.map_structure(tf.convert_to_tensor, state) state_update_tensors = tf.nest.map_structure(tf.convert_to_tensor, state_update_tensors) return update_state_fn(self, state, state_update_tensors, name=name) return actual_initial_state_fn
[ "def", "_tf_style_update_state", "(", "update_state_fn", ")", ":", "def", "actual_initial_state_fn", "(", "self", ",", "state", ",", "state_update_tensors", ",", "name", "=", "None", ")", ":", "\"\"\"Modified `update_state` method.\"\"\"", "values", "=", "list", "(", "state", ".", "values", "(", ")", ")", "+", "list", "(", "state_update_tensors", ".", "values", "(", ")", ")", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "name", ",", "self", ".", "name", "+", "UPDATE_STATE_SCOPE_SUFFIX", ",", "values", ")", ":", "state", "=", "tf", ".", "nest", ".", "map_structure", "(", "tf", ".", "convert_to_tensor", ",", "state", ")", "state_update_tensors", "=", "tf", ".", "nest", ".", "map_structure", "(", "tf", ".", "convert_to_tensor", ",", "state_update_tensors", ")", "return", "update_state_fn", "(", "self", ",", "state", ",", "state_update_tensors", ",", "name", "=", "name", ")", "return", "actual_initial_state_fn" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/tensorflow_model_optimization/python/core/internal/tensor_encoding/core/encoding_stage.py#L640-L653
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
swigibpy.py
python
EClient.replaceFA
(self, pFaDataType, cxml)
return _swigibpy.EClient_replaceFA(self, pFaDataType, cxml)
replaceFA(EClient self, faDataType pFaDataType, IBString const & cxml)
replaceFA(EClient self, faDataType pFaDataType, IBString const & cxml)
[ "replaceFA", "(", "EClient", "self", "faDataType", "pFaDataType", "IBString", "const", "&", "cxml", ")" ]
def replaceFA(self, pFaDataType, cxml): """replaceFA(EClient self, faDataType pFaDataType, IBString const & cxml)""" return _swigibpy.EClient_replaceFA(self, pFaDataType, cxml)
[ "def", "replaceFA", "(", "self", ",", "pFaDataType", ",", "cxml", ")", ":", "return", "_swigibpy", ".", "EClient_replaceFA", "(", "self", ",", "pFaDataType", ",", "cxml", ")" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1210-L1212
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_ops.py
python
angle
(input, name=None)
r"""Returns the element-wise argument of a complex (or real) tensor. Given a tensor `input`, this operation returns a tensor of type `float` that is the argument of each element in `input` considered as a complex number. The elements in `input` are considered to be complex numbers of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part. If `input` is real then *b* is zero by definition. The argument returned by this function is of the form \\(atan2(b, a)\\). If `input` is real, a tensor of all zeros is returned. For example: ``` input = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j], dtype=tf.complex64) tf.math.angle(input).numpy() # ==> array([2.0131705, 1.056345 ], dtype=float32) ``` Args: input: A `Tensor`. Must be one of the following types: `float`, `double`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32` or `float64`.
r"""Returns the element-wise argument of a complex (or real) tensor.
[ "r", "Returns", "the", "element", "-", "wise", "argument", "of", "a", "complex", "(", "or", "real", ")", "tensor", "." ]
def angle(input, name=None): r"""Returns the element-wise argument of a complex (or real) tensor. Given a tensor `input`, this operation returns a tensor of type `float` that is the argument of each element in `input` considered as a complex number. The elements in `input` are considered to be complex numbers of the form \\(a + bj\\), where *a* is the real part and *b* is the imaginary part. If `input` is real then *b* is zero by definition. The argument returned by this function is of the form \\(atan2(b, a)\\). If `input` is real, a tensor of all zeros is returned. For example: ``` input = tf.constant([-2.25 + 4.75j, 3.25 + 5.75j], dtype=tf.complex64) tf.math.angle(input).numpy() # ==> array([2.0131705, 1.056345 ], dtype=float32) ``` Args: input: A `Tensor`. Must be one of the following types: `float`, `double`, `complex64`, `complex128`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32` or `float64`. """ with ops.name_scope(name, "Angle", [input]) as name: input = ops.convert_to_tensor(input, name="input") if input.dtype.is_complex: return gen_math_ops.angle(input, Tout=input.dtype.real_dtype, name=name) else: return array_ops.where(input < 0, np.pi * array_ops.ones_like(input), array_ops.zeros_like(input))
[ "def", "angle", "(", "input", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"Angle\"", ",", "[", "input", "]", ")", "as", "name", ":", "input", "=", "ops", ".", "convert_to_tensor", "(", "input", ",", "name", "=", "\"input\"", ")", "if", "input", ".", "dtype", ".", "is_complex", ":", "return", "gen_math_ops", ".", "angle", "(", "input", ",", "Tout", "=", "input", ".", "dtype", ".", "real_dtype", ",", "name", "=", "name", ")", "else", ":", "return", "array_ops", ".", "where", "(", "input", "<", "0", ",", "np", ".", "pi", "*", "array_ops", ".", "ones_like", "(", "input", ")", ",", "array_ops", ".", "zeros_like", "(", "input", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_ops.py#L866-L901
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/instrument.py
python
Instrument.opening_timestamp
(self)
return self._opening_timestamp
Gets the opening_timestamp of this Instrument. # noqa: E501 :return: The opening_timestamp of this Instrument. # noqa: E501 :rtype: datetime
Gets the opening_timestamp of this Instrument. # noqa: E501
[ "Gets", "the", "opening_timestamp", "of", "this", "Instrument", ".", "#", "noqa", ":", "E501" ]
def opening_timestamp(self): """Gets the opening_timestamp of this Instrument. # noqa: E501 :return: The opening_timestamp of this Instrument. # noqa: E501 :rtype: datetime """ return self._opening_timestamp
[ "def", "opening_timestamp", "(", "self", ")", ":", "return", "self", ".", "_opening_timestamp" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument.py#L1759-L1766
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py
python
inspect
(logdir='', event_file='', tag='')
Main function for inspector that prints out a digest of event files. Args: logdir: A log directory that contains event files. event_file: Or, a particular event file path. tag: An optional tag name to query for. Raises: ValueError: If neither logdir and event_file are given, or both are given.
Main function for inspector that prints out a digest of event files.
[ "Main", "function", "for", "inspector", "that", "prints", "out", "a", "digest", "of", "event", "files", "." ]
def inspect(logdir='', event_file='', tag=''): """Main function for inspector that prints out a digest of event files. Args: logdir: A log directory that contains event files. event_file: Or, a particular event file path. tag: An optional tag name to query for. Raises: ValueError: If neither logdir and event_file are given, or both are given. """ if logdir and event_file: raise ValueError( 'Must specify either --logdir or --event_file, but not both.') if not (logdir or event_file): raise ValueError('Must specify either --logdir or --event_file.') print(PRINT_SEPARATOR + 'Processing event files... (this can take a few minutes)\n' + PRINT_SEPARATOR) inspection_units = get_inspection_units(logdir, event_file, tag) for unit in inspection_units: if tag: print('Event statistics for tag {} in {}:'.format(tag, unit.name)) else: # If the user is not inspecting a particular tag, also print the list of # all available tags that they can query. print('These tags are in {}:'.format(unit.name)) print_dict(get_unique_tags(unit.field_to_obs)) print(PRINT_SEPARATOR) print('Event statistics for {}:'.format(unit.name)) print_dict(get_dict_to_print(unit.field_to_obs), show_missing=(not tag)) print(PRINT_SEPARATOR)
[ "def", "inspect", "(", "logdir", "=", "''", ",", "event_file", "=", "''", ",", "tag", "=", "''", ")", ":", "if", "logdir", "and", "event_file", ":", "raise", "ValueError", "(", "'Must specify either --logdir or --event_file, but not both.'", ")", "if", "not", "(", "logdir", "or", "event_file", ")", ":", "raise", "ValueError", "(", "'Must specify either --logdir or --event_file.'", ")", "print", "(", "PRINT_SEPARATOR", "+", "'Processing event files... (this can take a few minutes)\\n'", "+", "PRINT_SEPARATOR", ")", "inspection_units", "=", "get_inspection_units", "(", "logdir", ",", "event_file", ",", "tag", ")", "for", "unit", "in", "inspection_units", ":", "if", "tag", ":", "print", "(", "'Event statistics for tag {} in {}:'", ".", "format", "(", "tag", ",", "unit", ".", "name", ")", ")", "else", ":", "# If the user is not inspecting a particular tag, also print the list of", "# all available tags that they can query.", "print", "(", "'These tags are in {}:'", ".", "format", "(", "unit", ".", "name", ")", ")", "print_dict", "(", "get_unique_tags", "(", "unit", ".", "field_to_obs", ")", ")", "print", "(", "PRINT_SEPARATOR", ")", "print", "(", "'Event statistics for {}:'", ".", "format", "(", "unit", ".", "name", ")", ")", "print_dict", "(", "get_dict_to_print", "(", "unit", ".", "field_to_obs", ")", ",", "show_missing", "=", "(", "not", "tag", ")", ")", "print", "(", "PRINT_SEPARATOR", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/summary/event_file_inspector.py#L389-L423
deepmind/streetlearn
ccf1d60b9c45154894d45a897748aee85d7eb69b
streetlearn/python/environment/instructions_base.py
python
InstructionsBase._update_shortest_path
(self, streetlearn, start_pano_id)
Update the target of the shortest paths and color panos along that path. Args: streetlearn: the streetlearn environment. start_pano_id: a string for the current pano ID, for computing the optimal path.
Update the target of the shortest paths and color panos along that path.
[ "Update", "the", "target", "of", "the", "shortest", "paths", "and", "color", "panos", "along", "that", "path", "." ]
def _update_shortest_path(self, streetlearn, start_pano_id): """Update the target of the shortest paths and color panos along that path. Args: streetlearn: the streetlearn environment. start_pano_id: a string for the current pano ID, for computing the optimal path. """ step = self._current_step + 1 logging.info(self._pano_by_step) logging.info('Reached step %d', step) if step in self._pano_by_step: target_pano_id = self._pano_by_step[step] self._shortest_path, num_panos = self._shortest_paths( streetlearn, target_pano_id, start_pano_id) logging.info('Shortest path from %s to waypoint/goal %s covers %d panos', start_pano_id, target_pano_id, num_panos)
[ "def", "_update_shortest_path", "(", "self", ",", "streetlearn", ",", "start_pano_id", ")", ":", "step", "=", "self", ".", "_current_step", "+", "1", "logging", ".", "info", "(", "self", ".", "_pano_by_step", ")", "logging", ".", "info", "(", "'Reached step %d'", ",", "step", ")", "if", "step", "in", "self", ".", "_pano_by_step", ":", "target_pano_id", "=", "self", ".", "_pano_by_step", "[", "step", "]", "self", ".", "_shortest_path", ",", "num_panos", "=", "self", ".", "_shortest_paths", "(", "streetlearn", ",", "target_pano_id", ",", "start_pano_id", ")", "logging", ".", "info", "(", "'Shortest path from %s to waypoint/goal %s covers %d panos'", ",", "start_pano_id", ",", "target_pano_id", ",", "num_panos", ")" ]
https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/environment/instructions_base.py#L237-L253
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/curses/wrapper.py
python
wrapper
(func, *args, **kwds)
Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to wrapper().
Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to wrapper().
[ "Wrapper", "function", "that", "initializes", "curses", "and", "calls", "another", "function", "restoring", "normal", "keyboard", "/", "screen", "behavior", "on", "error", ".", "The", "callable", "object", "func", "is", "then", "passed", "the", "main", "window", "stdscr", "as", "its", "first", "argument", "followed", "by", "any", "other", "arguments", "passed", "to", "wrapper", "()", "." ]
def wrapper(func, *args, **kwds): """Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to wrapper(). """ try: # Initialize curses stdscr = curses.initscr() # Turn off echoing of keys, and enter cbreak mode, # where no buffering is performed on keyboard input curses.noecho() curses.cbreak() # In keypad mode, escape sequences for special keys # (like the cursor keys) will be interpreted and # a special value like curses.KEY_LEFT will be returned stdscr.keypad(1) # Start color, too. Harmless if the terminal doesn't have # color; user can test with has_color() later on. The try/catch # works around a minor bit of over-conscientiousness in the curses # module -- the error return from C start_color() is ignorable. try: curses.start_color() except: pass return func(stdscr, *args, **kwds) finally: # Set everything back to normal if 'stdscr' in locals(): stdscr.keypad(0) curses.echo() curses.nocbreak() curses.endwin()
[ "def", "wrapper", "(", "func", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "try", ":", "# Initialize curses", "stdscr", "=", "curses", ".", "initscr", "(", ")", "# Turn off echoing of keys, and enter cbreak mode,", "# where no buffering is performed on keyboard input", "curses", ".", "noecho", "(", ")", "curses", ".", "cbreak", "(", ")", "# In keypad mode, escape sequences for special keys", "# (like the cursor keys) will be interpreted and", "# a special value like curses.KEY_LEFT will be returned", "stdscr", ".", "keypad", "(", "1", ")", "# Start color, too. Harmless if the terminal doesn't have", "# color; user can test with has_color() later on. The try/catch", "# works around a minor bit of over-conscientiousness in the curses", "# module -- the error return from C start_color() is ignorable.", "try", ":", "curses", ".", "start_color", "(", ")", "except", ":", "pass", "return", "func", "(", "stdscr", ",", "*", "args", ",", "*", "*", "kwds", ")", "finally", ":", "# Set everything back to normal", "if", "'stdscr'", "in", "locals", "(", ")", ":", "stdscr", ".", "keypad", "(", "0", ")", "curses", ".", "echo", "(", ")", "curses", ".", "nocbreak", "(", ")", "curses", ".", "endwin", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/curses/wrapper.py#L12-L50
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
python
RawTurtle._write
(self, txt, align, font)
return end
Performs the writing for write()
Performs the writing for write()
[ "Performs", "the", "writing", "for", "write", "()" ]
def _write(self, txt, align, font): """Performs the writing for write() """ item, end = self.screen._write(self._position, txt, align, font, self._pencolor) self.items.append(item) if self.undobuffer: self.undobuffer.push(("wri", item)) return end
[ "def", "_write", "(", "self", ",", "txt", ",", "align", ",", "font", ")", ":", "item", ",", "end", "=", "self", ".", "screen", ".", "_write", "(", "self", ".", "_position", ",", "txt", ",", "align", ",", "font", ",", "self", ".", "_pencolor", ")", "self", ".", "items", ".", "append", "(", "item", ")", "if", "self", ".", "undobuffer", ":", "self", ".", "undobuffer", ".", "push", "(", "(", "\"wri\"", ",", "item", ")", ")", "return", "end" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L3266-L3274
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
createEntityParserCtxt
(URL, ID, base)
return parserCtxt(_obj=ret)
Create a parser context for an external entity Automatic support for ZLIB/Compress compressed document is provided by default if found at compile-time.
Create a parser context for an external entity Automatic support for ZLIB/Compress compressed document is provided by default if found at compile-time.
[ "Create", "a", "parser", "context", "for", "an", "external", "entity", "Automatic", "support", "for", "ZLIB", "/", "Compress", "compressed", "document", "is", "provided", "by", "default", "if", "found", "at", "compile", "-", "time", "." ]
def createEntityParserCtxt(URL, ID, base): """Create a parser context for an external entity Automatic support for ZLIB/Compress compressed document is provided by default if found at compile-time. """ ret = libxml2mod.xmlCreateEntityParserCtxt(URL, ID, base) if ret is None:raise parserError('xmlCreateEntityParserCtxt() failed') return parserCtxt(_obj=ret)
[ "def", "createEntityParserCtxt", "(", "URL", ",", "ID", ",", "base", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCreateEntityParserCtxt", "(", "URL", ",", "ID", ",", "base", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlCreateEntityParserCtxt() failed'", ")", "return", "parserCtxt", "(", "_obj", "=", "ret", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L1465-L1471
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
examples/rfcn/tools/rpn_generate.py
python
parse_args
()
return args
Parse input arguments
Parse input arguments
[ "Parse", "input", "arguments" ]
def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use', default=0, type=int) parser.add_argument('--def', dest='prototxt', help='prototxt file defining the network', default=None, type=str) parser.add_argument('--net', dest='caffemodel', help='model to test', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--wait', dest='wait', help='wait until net file exists', default=True, type=bool) parser.add_argument('--imdb', dest='imdb_name', help='dataset to test', default='voc_2007_test', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Test a Fast R-CNN network'", ")", "parser", ".", "add_argument", "(", "'--gpu'", ",", "dest", "=", "'gpu_id'", ",", "help", "=", "'GPU id to use'", ",", "default", "=", "0", ",", "type", "=", "int", ")", "parser", ".", "add_argument", "(", "'--def'", ",", "dest", "=", "'prototxt'", ",", "help", "=", "'prototxt file defining the network'", ",", "default", "=", "None", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'--net'", ",", "dest", "=", "'caffemodel'", ",", "help", "=", "'model to test'", ",", "default", "=", "None", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'--cfg'", ",", "dest", "=", "'cfg_file'", ",", "help", "=", "'optional config file'", ",", "default", "=", "None", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'--wait'", ",", "dest", "=", "'wait'", ",", "help", "=", "'wait until net file exists'", ",", "default", "=", "True", ",", "type", "=", "bool", ")", "parser", ".", "add_argument", "(", "'--imdb'", ",", "dest", "=", "'imdb_name'", ",", "help", "=", "'dataset to test'", ",", "default", "=", "'voc_2007_test'", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'--set'", ",", "dest", "=", "'set_cfgs'", ",", "help", "=", "'set config keys'", ",", "default", "=", "None", ",", "nargs", "=", "argparse", ".", "REMAINDER", ")", "if", "len", "(", "sys", ".", "argv", ")", "==", "1", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "return", "args" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/rfcn/tools/rpn_generate.py#L23-L53
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListCtrl.DeleteColumn
(self, col)
return True
Deletes the specified column. :param `col`: the index of the column to delete.
Deletes the specified column.
[ "Deletes", "the", "specified", "column", "." ]
def DeleteColumn(self, col): """ Deletes the specified column. :param `col`: the index of the column to delete. """ self._mainWin.DeleteColumn(col) return True
[ "def", "DeleteColumn", "(", "self", ",", "col", ")", ":", "self", ".", "_mainWin", ".", "DeleteColumn", "(", "col", ")", "return", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L11974-L11982
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/utils.py
python
LRUCache.items
(self)
return result
Return a list of items.
Return a list of items.
[ "Return", "a", "list", "of", "items", "." ]
def items(self): """Return a list of items.""" result = [(key, self._mapping[key]) for key in list(self._queue)] result.reverse() return result
[ "def", "items", "(", "self", ")", ":", "result", "=", "[", "(", "key", ",", "self", ".", "_mapping", "[", "key", "]", ")", "for", "key", "in", "list", "(", "self", ".", "_queue", ")", "]", "result", ".", "reverse", "(", ")", "return", "result" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8_inspector/third_party/jinja2/jinja2/utils.py#L443-L447
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
ValidCtxt.validateRoot
(self, doc)
return ret
Try to validate a the root element basically it does the following check as described by the XML-1.0 recommendation: - [ VC: Root Element Type ] it doesn't try to recurse or apply other check to the element
Try to validate a the root element basically it does the following check as described by the XML-1.0 recommendation: - [ VC: Root Element Type ] it doesn't try to recurse or apply other check to the element
[ "Try", "to", "validate", "a", "the", "root", "element", "basically", "it", "does", "the", "following", "check", "as", "described", "by", "the", "XML", "-", "1", ".", "0", "recommendation", ":", "-", "[", "VC", ":", "Root", "Element", "Type", "]", "it", "doesn", "t", "try", "to", "recurse", "or", "apply", "other", "check", "to", "the", "element" ]
def validateRoot(self, doc): """Try to validate a the root element basically it does the following check as described by the XML-1.0 recommendation: - [ VC: Root Element Type ] it doesn't try to recurse or apply other check to the element """ if doc is None: doc__o = None else: doc__o = doc._o ret = libxml2mod.xmlValidateRoot(self._o, doc__o) return ret
[ "def", "validateRoot", "(", "self", ",", "doc", ")", ":", "if", "doc", "is", "None", ":", "doc__o", "=", "None", "else", ":", "doc__o", "=", "doc", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlValidateRoot", "(", "self", ".", "_o", ",", "doc__o", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L6455-L6463
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
docs/examples/use_cases/tensorflow/efficientdet/pipeline/tf/preprocessor.py
python
_compute_new_dynamic_size
(image, min_dimension, max_dimension)
return tf.stack(tf.unstack(new_size) + [num_channels])
Compute new dynamic shape for resize_to_range method.
Compute new dynamic shape for resize_to_range method.
[ "Compute", "new", "dynamic", "shape", "for", "resize_to_range", "method", "." ]
def _compute_new_dynamic_size(image, min_dimension, max_dimension): """Compute new dynamic shape for resize_to_range method.""" image_shape = tf.shape(image) orig_height = tf.to_float(image_shape[0]) orig_width = tf.to_float(image_shape[1]) num_channels = image_shape[2] orig_min_dim = tf.minimum(orig_height, orig_width) # Calculates the larger of the possible sizes min_dimension = tf.constant(min_dimension, dtype=tf.float32) large_scale_factor = min_dimension / orig_min_dim # Scaling orig_(height|width) by large_scale_factor will make the smaller # dimension equal to min_dimension, save for floating point rounding errors. # For reasonably-sized images, taking the nearest integer will reliably # eliminate this error. large_height = tf.to_int32(tf.round(orig_height * large_scale_factor)) large_width = tf.to_int32(tf.round(orig_width * large_scale_factor)) large_size = tf.stack([large_height, large_width]) if max_dimension: # Calculates the smaller of the possible sizes, use that if the larger # is too big. orig_max_dim = tf.maximum(orig_height, orig_width) max_dimension = tf.constant(max_dimension, dtype=tf.float32) small_scale_factor = max_dimension / orig_max_dim # Scaling orig_(height|width) by small_scale_factor will make the larger # dimension equal to max_dimension, save for floating point rounding # errors. For reasonably-sized images, taking the nearest integer will # reliably eliminate this error. small_height = tf.to_int32(tf.round(orig_height * small_scale_factor)) small_width = tf.to_int32(tf.round(orig_width * small_scale_factor)) small_size = tf.stack([small_height, small_width]) new_size = tf.cond( tf.to_float(tf.reduce_max(large_size)) > max_dimension, lambda: small_size, lambda: large_size, ) else: new_size = large_size return tf.stack(tf.unstack(new_size) + [num_channels])
[ "def", "_compute_new_dynamic_size", "(", "image", ",", "min_dimension", ",", "max_dimension", ")", ":", "image_shape", "=", "tf", ".", "shape", "(", "image", ")", "orig_height", "=", "tf", ".", "to_float", "(", "image_shape", "[", "0", "]", ")", "orig_width", "=", "tf", ".", "to_float", "(", "image_shape", "[", "1", "]", ")", "num_channels", "=", "image_shape", "[", "2", "]", "orig_min_dim", "=", "tf", ".", "minimum", "(", "orig_height", ",", "orig_width", ")", "# Calculates the larger of the possible sizes", "min_dimension", "=", "tf", ".", "constant", "(", "min_dimension", ",", "dtype", "=", "tf", ".", "float32", ")", "large_scale_factor", "=", "min_dimension", "/", "orig_min_dim", "# Scaling orig_(height|width) by large_scale_factor will make the smaller", "# dimension equal to min_dimension, save for floating point rounding errors.", "# For reasonably-sized images, taking the nearest integer will reliably", "# eliminate this error.", "large_height", "=", "tf", ".", "to_int32", "(", "tf", ".", "round", "(", "orig_height", "*", "large_scale_factor", ")", ")", "large_width", "=", "tf", ".", "to_int32", "(", "tf", ".", "round", "(", "orig_width", "*", "large_scale_factor", ")", ")", "large_size", "=", "tf", ".", "stack", "(", "[", "large_height", ",", "large_width", "]", ")", "if", "max_dimension", ":", "# Calculates the smaller of the possible sizes, use that if the larger", "# is too big.", "orig_max_dim", "=", "tf", ".", "maximum", "(", "orig_height", ",", "orig_width", ")", "max_dimension", "=", "tf", ".", "constant", "(", "max_dimension", ",", "dtype", "=", "tf", ".", "float32", ")", "small_scale_factor", "=", "max_dimension", "/", "orig_max_dim", "# Scaling orig_(height|width) by small_scale_factor will make the larger", "# dimension equal to max_dimension, save for floating point rounding", "# errors. For reasonably-sized images, taking the nearest integer will", "# reliably eliminate this error.", "small_height", "=", "tf", ".", "to_int32", "(", "tf", ".", "round", "(", "orig_height", "*", "small_scale_factor", ")", ")", "small_width", "=", "tf", ".", "to_int32", "(", "tf", ".", "round", "(", "orig_width", "*", "small_scale_factor", ")", ")", "small_size", "=", "tf", ".", "stack", "(", "[", "small_height", ",", "small_width", "]", ")", "new_size", "=", "tf", ".", "cond", "(", "tf", ".", "to_float", "(", "tf", ".", "reduce_max", "(", "large_size", ")", ")", ">", "max_dimension", ",", "lambda", ":", "small_size", ",", "lambda", ":", "large_size", ",", ")", "else", ":", "new_size", "=", "large_size", "return", "tf", ".", "stack", "(", "tf", ".", "unstack", "(", "new_size", ")", "+", "[", "num_channels", "]", ")" ]
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/docs/examples/use_cases/tensorflow/efficientdet/pipeline/tf/preprocessor.py#L241-L278
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/importlib/_bootstrap_external.py
python
PathFinder._path_importer_cache
(cls, path)
return finder
Get the finder for the path entry from sys.path_importer_cache. If the path entry is not in the cache, find the appropriate finder and cache it. If no finder is available, store None.
Get the finder for the path entry from sys.path_importer_cache.
[ "Get", "the", "finder", "for", "the", "path", "entry", "from", "sys", ".", "path_importer_cache", "." ]
def _path_importer_cache(cls, path): """Get the finder for the path entry from sys.path_importer_cache. If the path entry is not in the cache, find the appropriate finder and cache it. If no finder is available, store None. """ if path == '': try: path = _os.getcwd() except FileNotFoundError: # Don't cache the failure as the cwd can easily change to # a valid directory later on. return None try: finder = sys.path_importer_cache[path] except KeyError: finder = cls._path_hooks(path) sys.path_importer_cache[path] = finder return finder
[ "def", "_path_importer_cache", "(", "cls", ",", "path", ")", ":", "if", "path", "==", "''", ":", "try", ":", "path", "=", "_os", ".", "getcwd", "(", ")", "except", "FileNotFoundError", ":", "# Don't cache the failure as the cwd can easily change to", "# a valid directory later on.", "return", "None", "try", ":", "finder", "=", "sys", ".", "path_importer_cache", "[", "path", "]", "except", "KeyError", ":", "finder", "=", "cls", ".", "_path_hooks", "(", "path", ")", "sys", ".", "path_importer_cache", "[", "path", "]", "=", "finder", "return", "finder" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/_bootstrap_external.py#L1338-L1357
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/ops/sparse_ops.py
python
_multiplier_helper
(shape)
return multipliers
Returns moving offset for each dimension given shape.
Returns moving offset for each dimension given shape.
[ "Returns", "moving", "offset", "for", "each", "dimension", "given", "shape", "." ]
def _multiplier_helper(shape): """Returns moving offset for each dimension given shape.""" multipliers = [] for dim in reversed(shape): if multipliers: multipliers.append(dim * multipliers[-1]) else: multipliers.append(dim) multipliers.reverse() return multipliers
[ "def", "_multiplier_helper", "(", "shape", ")", ":", "multipliers", "=", "[", "]", "for", "dim", "in", "reversed", "(", "shape", ")", ":", "if", "multipliers", ":", "multipliers", ".", "append", "(", "dim", "*", "multipliers", "[", "-", "1", "]", ")", "else", ":", "multipliers", ".", "append", "(", "dim", ")", "multipliers", ".", "reverse", "(", ")", "return", "multipliers" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/ops/sparse_ops.py#L29-L38
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/curses/textpad.py
python
Textbox.edit
(self, validate=None)
return self.gather()
Edit in the widget window and collect the results.
Edit in the widget window and collect the results.
[ "Edit", "in", "the", "widget", "window", "and", "collect", "the", "results", "." ]
def edit(self, validate=None): "Edit in the widget window and collect the results." while 1: ch = self.win.getch() if validate: ch = validate(ch) if not ch: continue if not self.do_command(ch): break self.win.refresh() return self.gather()
[ "def", "edit", "(", "self", ",", "validate", "=", "None", ")", ":", "while", "1", ":", "ch", "=", "self", ".", "win", ".", "getch", "(", ")", "if", "validate", ":", "ch", "=", "validate", "(", "ch", ")", "if", "not", "ch", ":", "continue", "if", "not", "self", ".", "do_command", "(", "ch", ")", ":", "break", "self", ".", "win", ".", "refresh", "(", ")", "return", "self", ".", "gather", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/curses/textpad.py#L177-L188
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/misc_util.py
python
get_pkg_info
(pkgname, dirs=None)
return read_config(pkgname, dirs)
Return library info for the given package. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_info
Return library info for the given package.
[ "Return", "library", "info", "for", "the", "given", "package", "." ]
def get_pkg_info(pkgname, dirs=None): """ Return library info for the given package. Parameters ---------- pkgname : str Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirs : sequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns ------- pkginfo : class instance The `LibraryInfo` instance containing the build information. Raises ------ PkgNotFound If the package is not found. See Also -------- Configuration.add_npy_pkg_config, Configuration.add_installed_library, get_info """ from numpy.distutils.npy_pkg_config import read_config if dirs: dirs.append(get_npy_pkg_dir()) else: dirs = [get_npy_pkg_dir()] return read_config(pkgname, dirs)
[ "def", "get_pkg_info", "(", "pkgname", ",", "dirs", "=", "None", ")", ":", "from", "numpy", ".", "distutils", ".", "npy_pkg_config", "import", "read_config", "if", "dirs", ":", "dirs", ".", "append", "(", "get_npy_pkg_dir", "(", ")", ")", "else", ":", "dirs", "=", "[", "get_npy_pkg_dir", "(", ")", "]", "return", "read_config", "(", "pkgname", ",", "dirs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/distutils/misc_util.py#L2149-L2185
sdhash/sdhash
b9eff63e4e5867e910f41fd69032bbb1c94a2a5e
sdhash-ui/cherrypy/_cpdispatch.py
python
test_callable_spec
(callable, callable_args, callable_kwargs)
Inspect callable and test to see if the given args are suitable for it. When an error occurs during the handler's invoking stage there are 2 erroneous cases: 1. Too many parameters passed to a function which doesn't define one of *args or **kwargs. 2. Too little parameters are passed to the function. There are 3 sources of parameters to a cherrypy handler. 1. query string parameters are passed as keyword parameters to the handler. 2. body parameters are also passed as keyword parameters. 3. when partial matching occurs, the final path atoms are passed as positional args. Both the query string and path atoms are part of the URI. If they are incorrect, then a 404 Not Found should be raised. Conversely the body parameters are part of the request; if they are invalid a 400 Bad Request.
Inspect callable and test to see if the given args are suitable for it.
[ "Inspect", "callable", "and", "test", "to", "see", "if", "the", "given", "args", "are", "suitable", "for", "it", "." ]
def test_callable_spec(callable, callable_args, callable_kwargs): """ Inspect callable and test to see if the given args are suitable for it. When an error occurs during the handler's invoking stage there are 2 erroneous cases: 1. Too many parameters passed to a function which doesn't define one of *args or **kwargs. 2. Too little parameters are passed to the function. There are 3 sources of parameters to a cherrypy handler. 1. query string parameters are passed as keyword parameters to the handler. 2. body parameters are also passed as keyword parameters. 3. when partial matching occurs, the final path atoms are passed as positional args. Both the query string and path atoms are part of the URI. If they are incorrect, then a 404 Not Found should be raised. Conversely the body parameters are part of the request; if they are invalid a 400 Bad Request. """ show_mismatched_params = getattr( cherrypy.serving.request, 'show_mismatched_params', False) try: (args, varargs, varkw, defaults) = inspect.getargspec(callable) except TypeError: if isinstance(callable, object) and hasattr(callable, '__call__'): (args, varargs, varkw, defaults) = inspect.getargspec(callable.__call__) else: # If it wasn't one of our own types, re-raise # the original error raise if args and args[0] == 'self': args = args[1:] arg_usage = dict([(arg, 0,) for arg in args]) vararg_usage = 0 varkw_usage = 0 extra_kwargs = set() for i, value in enumerate(callable_args): try: arg_usage[args[i]] += 1 except IndexError: vararg_usage += 1 for key in callable_kwargs.keys(): try: arg_usage[key] += 1 except KeyError: varkw_usage += 1 extra_kwargs.add(key) # figure out which args have defaults. args_with_defaults = args[-len(defaults or []):] for i, val in enumerate(defaults or []): # Defaults take effect only when the arg hasn't been used yet. if arg_usage[args_with_defaults[i]] == 0: arg_usage[args_with_defaults[i]] += 1 missing_args = [] multiple_args = [] for key, usage in arg_usage.items(): if usage == 0: missing_args.append(key) elif usage > 1: multiple_args.append(key) if missing_args: # In the case where the method allows body arguments # there are 3 potential errors: # 1. not enough query string parameters -> 404 # 2. not enough body parameters -> 400 # 3. not enough path parts (partial matches) -> 404 # # We can't actually tell which case it is, # so I'm raising a 404 because that covers 2/3 of the # possibilities # # In the case where the method does not allow body # arguments it's definitely a 404. message = None if show_mismatched_params: message="Missing parameters: %s" % ",".join(missing_args) raise cherrypy.HTTPError(404, message=message) # the extra positional arguments come from the path - 404 Not Found if not varargs and vararg_usage > 0: raise cherrypy.HTTPError(404) body_params = cherrypy.serving.request.body.params or {} body_params = set(body_params.keys()) qs_params = set(callable_kwargs.keys()) - body_params if multiple_args: if qs_params.intersection(set(multiple_args)): # If any of the multiple parameters came from the query string then # it's a 404 Not Found error = 404 else: # Otherwise it's a 400 Bad Request error = 400 message = None if show_mismatched_params: message="Multiple values for parameters: "\ "%s" % ",".join(multiple_args) raise cherrypy.HTTPError(error, message=message) if not varkw and varkw_usage > 0: # If there were extra query string parameters, it's a 404 Not Found extra_qs_params = set(qs_params).intersection(extra_kwargs) if extra_qs_params: message = None if show_mismatched_params: message="Unexpected query string "\ "parameters: %s" % ", ".join(extra_qs_params) raise cherrypy.HTTPError(404, message=message) # If there were any extra body parameters, it's a 400 Not Found extra_body_params = set(body_params).intersection(extra_kwargs) if extra_body_params: message = None if show_mismatched_params: message="Unexpected body parameters: "\ "%s" % ", ".join(extra_body_params) raise cherrypy.HTTPError(400, message=message)
[ "def", "test_callable_spec", "(", "callable", ",", "callable_args", ",", "callable_kwargs", ")", ":", "show_mismatched_params", "=", "getattr", "(", "cherrypy", ".", "serving", ".", "request", ",", "'show_mismatched_params'", ",", "False", ")", "try", ":", "(", "args", ",", "varargs", ",", "varkw", ",", "defaults", ")", "=", "inspect", ".", "getargspec", "(", "callable", ")", "except", "TypeError", ":", "if", "isinstance", "(", "callable", ",", "object", ")", "and", "hasattr", "(", "callable", ",", "'__call__'", ")", ":", "(", "args", ",", "varargs", ",", "varkw", ",", "defaults", ")", "=", "inspect", ".", "getargspec", "(", "callable", ".", "__call__", ")", "else", ":", "# If it wasn't one of our own types, re-raise ", "# the original error", "raise", "if", "args", "and", "args", "[", "0", "]", "==", "'self'", ":", "args", "=", "args", "[", "1", ":", "]", "arg_usage", "=", "dict", "(", "[", "(", "arg", ",", "0", ",", ")", "for", "arg", "in", "args", "]", ")", "vararg_usage", "=", "0", "varkw_usage", "=", "0", "extra_kwargs", "=", "set", "(", ")", "for", "i", ",", "value", "in", "enumerate", "(", "callable_args", ")", ":", "try", ":", "arg_usage", "[", "args", "[", "i", "]", "]", "+=", "1", "except", "IndexError", ":", "vararg_usage", "+=", "1", "for", "key", "in", "callable_kwargs", ".", "keys", "(", ")", ":", "try", ":", "arg_usage", "[", "key", "]", "+=", "1", "except", "KeyError", ":", "varkw_usage", "+=", "1", "extra_kwargs", ".", "add", "(", "key", ")", "# figure out which args have defaults.", "args_with_defaults", "=", "args", "[", "-", "len", "(", "defaults", "or", "[", "]", ")", ":", "]", "for", "i", ",", "val", "in", "enumerate", "(", "defaults", "or", "[", "]", ")", ":", "# Defaults take effect only when the arg hasn't been used yet.", "if", "arg_usage", "[", "args_with_defaults", "[", "i", "]", "]", "==", "0", ":", "arg_usage", "[", "args_with_defaults", "[", "i", "]", "]", "+=", "1", "missing_args", "=", "[", "]", "multiple_args", "=", "[", "]", "for", "key", ",", "usage", "in", "arg_usage", ".", "items", "(", ")", ":", "if", "usage", "==", "0", ":", "missing_args", ".", "append", "(", "key", ")", "elif", "usage", ">", "1", ":", "multiple_args", ".", "append", "(", "key", ")", "if", "missing_args", ":", "# In the case where the method allows body arguments", "# there are 3 potential errors:", "# 1. not enough query string parameters -> 404", "# 2. not enough body parameters -> 400", "# 3. not enough path parts (partial matches) -> 404", "#", "# We can't actually tell which case it is, ", "# so I'm raising a 404 because that covers 2/3 of the", "# possibilities", "# ", "# In the case where the method does not allow body", "# arguments it's definitely a 404.", "message", "=", "None", "if", "show_mismatched_params", ":", "message", "=", "\"Missing parameters: %s\"", "%", "\",\"", ".", "join", "(", "missing_args", ")", "raise", "cherrypy", ".", "HTTPError", "(", "404", ",", "message", "=", "message", ")", "# the extra positional arguments come from the path - 404 Not Found", "if", "not", "varargs", "and", "vararg_usage", ">", "0", ":", "raise", "cherrypy", ".", "HTTPError", "(", "404", ")", "body_params", "=", "cherrypy", ".", "serving", ".", "request", ".", "body", ".", "params", "or", "{", "}", "body_params", "=", "set", "(", "body_params", ".", "keys", "(", ")", ")", "qs_params", "=", "set", "(", "callable_kwargs", ".", "keys", "(", ")", ")", "-", "body_params", "if", "multiple_args", ":", "if", "qs_params", ".", "intersection", "(", "set", "(", "multiple_args", ")", ")", ":", "# If any of the multiple parameters came from the query string then", "# it's a 404 Not Found", "error", "=", "404", "else", ":", "# Otherwise it's a 400 Bad Request", "error", "=", "400", "message", "=", "None", "if", "show_mismatched_params", ":", "message", "=", "\"Multiple values for parameters: \"", "\"%s\"", "%", "\",\"", ".", "join", "(", "multiple_args", ")", "raise", "cherrypy", ".", "HTTPError", "(", "error", ",", "message", "=", "message", ")", "if", "not", "varkw", "and", "varkw_usage", ">", "0", ":", "# If there were extra query string parameters, it's a 404 Not Found", "extra_qs_params", "=", "set", "(", "qs_params", ")", ".", "intersection", "(", "extra_kwargs", ")", "if", "extra_qs_params", ":", "message", "=", "None", "if", "show_mismatched_params", ":", "message", "=", "\"Unexpected query string \"", "\"parameters: %s\"", "%", "\", \"", ".", "join", "(", "extra_qs_params", ")", "raise", "cherrypy", ".", "HTTPError", "(", "404", ",", "message", "=", "message", ")", "# If there were any extra body parameters, it's a 400 Not Found", "extra_body_params", "=", "set", "(", "body_params", ")", ".", "intersection", "(", "extra_kwargs", ")", "if", "extra_body_params", ":", "message", "=", "None", "if", "show_mismatched_params", ":", "message", "=", "\"Unexpected body parameters: \"", "\"%s\"", "%", "\", \"", ".", "join", "(", "extra_body_params", ")", "raise", "cherrypy", ".", "HTTPError", "(", "400", ",", "message", "=", "message", ")" ]
https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/_cpdispatch.py#L46-L172
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert/run_classifier.py
python
_truncate_seq_pair
(tokens_a, tokens_b, max_length)
Truncates a sequence pair in place to the maximum length.
Truncates a sequence pair in place to the maximum length.
[ "Truncates", "a", "sequence", "pair", "in", "place", "to", "the", "maximum", "length", "." ]
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that's truncated likely contains more information than a longer sequence. while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop()
[ "def", "_truncate_seq_pair", "(", "tokens_a", ",", "tokens_b", ",", "max_length", ")", ":", "# This is a simple heuristic which will always truncate the longer sequence", "# one token at a time. This makes more sense than truncating an equal percent", "# of tokens from each, since if one sequence is very short then each token", "# that's truncated likely contains more information than a longer sequence.", "while", "True", ":", "total_length", "=", "len", "(", "tokens_a", ")", "+", "len", "(", "tokens_b", ")", "if", "total_length", "<=", "max_length", ":", "break", "if", "len", "(", "tokens_a", ")", ">", "len", "(", "tokens_b", ")", ":", "tokens_a", ".", "pop", "(", ")", "else", ":", "tokens_b", ".", "pop", "(", ")" ]
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert/run_classifier.py#L557-L571
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/internals/blocks.py
python
CategoricalBlock._try_coerce_result
(self, result)
return result
reverse of try_coerce_args
reverse of try_coerce_args
[ "reverse", "of", "try_coerce_args" ]
def _try_coerce_result(self, result): """ reverse of try_coerce_args """ # GH12564: CategoricalBlock is 1-dim only # while returned results could be any dim if ((not is_categorical_dtype(result)) and isinstance(result, np.ndarray)): result = _block_shape(result, ndim=self.ndim) return result
[ "def", "_try_coerce_result", "(", "self", ",", "result", ")", ":", "# GH12564: CategoricalBlock is 1-dim only", "# while returned results could be any dim", "if", "(", "(", "not", "is_categorical_dtype", "(", "result", ")", ")", "and", "isinstance", "(", "result", ",", "np", ".", "ndarray", ")", ")", ":", "result", "=", "_block_shape", "(", "result", ",", "ndim", "=", "self", ".", "ndim", ")", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/blocks.py#L2952-L2961
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/nn_ops.py
python
LSTM.__init__
(self, input_size, hidden_size, num_layers, has_bias, bidirectional, dropout)
Initialize LSTM.
Initialize LSTM.
[ "Initialize", "LSTM", "." ]
def __init__(self, input_size, hidden_size, num_layers, has_bias, bidirectional, dropout): """Initialize LSTM.""" self.input_size = validator.check_positive_int(input_size, "input_size", self.name) self.hidden_size = validator.check_positive_int(hidden_size, "hidden_size", self.name) self.num_layers = validator.check_positive_int(num_layers, "num_layers", self.name) self.has_bias = validator.check_value_type("has_bias", has_bias, (bool,), self.name) self.bidirectional = validator.check_value_type("bidirectional", bidirectional, (bool,), self.name) self.dropout = validator.check_value_type("dropout", dropout, [float], self.name) self.dropout = validator.check_float_range(dropout, 0, 1, Rel.INC_BOTH, 'dropout', self.name) if bidirectional: self.num_directions = 2 else: self.num_directions = 1
[ "def", "__init__", "(", "self", ",", "input_size", ",", "hidden_size", ",", "num_layers", ",", "has_bias", ",", "bidirectional", ",", "dropout", ")", ":", "self", ".", "input_size", "=", "validator", ".", "check_positive_int", "(", "input_size", ",", "\"input_size\"", ",", "self", ".", "name", ")", "self", ".", "hidden_size", "=", "validator", ".", "check_positive_int", "(", "hidden_size", ",", "\"hidden_size\"", ",", "self", ".", "name", ")", "self", ".", "num_layers", "=", "validator", ".", "check_positive_int", "(", "num_layers", ",", "\"num_layers\"", ",", "self", ".", "name", ")", "self", ".", "has_bias", "=", "validator", ".", "check_value_type", "(", "\"has_bias\"", ",", "has_bias", ",", "(", "bool", ",", ")", ",", "self", ".", "name", ")", "self", ".", "bidirectional", "=", "validator", ".", "check_value_type", "(", "\"bidirectional\"", ",", "bidirectional", ",", "(", "bool", ",", ")", ",", "self", ".", "name", ")", "self", ".", "dropout", "=", "validator", ".", "check_value_type", "(", "\"dropout\"", ",", "dropout", ",", "[", "float", "]", ",", "self", ".", "name", ")", "self", ".", "dropout", "=", "validator", ".", "check_float_range", "(", "dropout", ",", "0", ",", "1", ",", "Rel", ".", "INC_BOTH", ",", "'dropout'", ",", "self", ".", "name", ")", "if", "bidirectional", ":", "self", ".", "num_directions", "=", "2", "else", ":", "self", ".", "num_directions", "=", "1" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/nn_ops.py#L3707-L3720
yrnkrn/zapcc
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
tools/clang/bindings/python/clang/cindex.py
python
Cursor.tls_kind
(self)
return TLSKind.from_id(self._tls_kind)
Return the thread-local storage (TLS) kind of this cursor.
Return the thread-local storage (TLS) kind of this cursor.
[ "Return", "the", "thread", "-", "local", "storage", "(", "TLS", ")", "kind", "of", "this", "cursor", "." ]
def tls_kind(self): """Return the thread-local storage (TLS) kind of this cursor.""" if not hasattr(self, '_tls_kind'): self._tls_kind = conf.lib.clang_getCursorTLSKind(self) return TLSKind.from_id(self._tls_kind)
[ "def", "tls_kind", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_tls_kind'", ")", ":", "self", ".", "_tls_kind", "=", "conf", ".", "lib", ".", "clang_getCursorTLSKind", "(", "self", ")", "return", "TLSKind", ".", "from_id", "(", "self", ".", "_tls_kind", ")" ]
https://github.com/yrnkrn/zapcc/blob/c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50/tools/clang/bindings/python/clang/cindex.py#L1569-L1574
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/dataset.py
python
DataSet._exif_overrides_file
(self)
return os.path.join(self.data_path, 'exif_overrides.json')
Path to the EXIF overrides file.
Path to the EXIF overrides file.
[ "Path", "to", "the", "EXIF", "overrides", "file", "." ]
def _exif_overrides_file(self): """Path to the EXIF overrides file.""" return os.path.join(self.data_path, 'exif_overrides.json')
[ "def", "_exif_overrides_file", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "data_path", ",", "'exif_overrides.json'", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/dataset.py#L670-L672
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/fourwaysplitter.py
python
FourWaySplitter.OnSize
(self, event)
Handles the ``wx.EVT_SIZE`` event for :class:`FourWaySplitter`. :param `event`: a :class:`SizeEvent` event to be processed.
Handles the ``wx.EVT_SIZE`` event for :class:`FourWaySplitter`.
[ "Handles", "the", "wx", ".", "EVT_SIZE", "event", "for", ":", "class", ":", "FourWaySplitter", "." ]
def OnSize(self, event): """ Handles the ``wx.EVT_SIZE`` event for :class:`FourWaySplitter`. :param `event`: a :class:`SizeEvent` event to be processed. """ parent = wx.GetTopLevelParent(self) if parent.IsIconized(): event.Skip() return self._SizeWindows()
[ "def", "OnSize", "(", "self", ",", "event", ")", ":", "parent", "=", "wx", ".", "GetTopLevelParent", "(", "self", ")", "if", "parent", ".", "IsIconized", "(", ")", ":", "event", ".", "Skip", "(", ")", "return", "self", ".", "_SizeWindows", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/fourwaysplitter.py#L859-L871
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/WebOb/webob/response.py
python
Response.encode_content
(self, encoding='gzip', lazy=False)
Encode the content with the given encoding (only gzip and identity are supported).
Encode the content with the given encoding (only gzip and identity are supported).
[ "Encode", "the", "content", "with", "the", "given", "encoding", "(", "only", "gzip", "and", "identity", "are", "supported", ")", "." ]
def encode_content(self, encoding='gzip', lazy=False): """ Encode the content with the given encoding (only gzip and identity are supported). """ assert encoding in ('identity', 'gzip'), \ "Unknown encoding: %r" % encoding if encoding == 'identity': self.decode_content() return if self.content_encoding == 'gzip': return if lazy: self.app_iter = gzip_app_iter(self._app_iter) self.content_length = None else: self.app_iter = list(gzip_app_iter(self._app_iter)) self.content_length = sum(map(len, self._app_iter)) self.content_encoding = 'gzip'
[ "def", "encode_content", "(", "self", ",", "encoding", "=", "'gzip'", ",", "lazy", "=", "False", ")", ":", "assert", "encoding", "in", "(", "'identity'", ",", "'gzip'", ")", ",", "\"Unknown encoding: %r\"", "%", "encoding", "if", "encoding", "==", "'identity'", ":", "self", ".", "decode_content", "(", ")", "return", "if", "self", ".", "content_encoding", "==", "'gzip'", ":", "return", "if", "lazy", ":", "self", ".", "app_iter", "=", "gzip_app_iter", "(", "self", ".", "_app_iter", ")", "self", ".", "content_length", "=", "None", "else", ":", "self", ".", "app_iter", "=", "list", "(", "gzip_app_iter", "(", "self", ".", "_app_iter", ")", ")", "self", ".", "content_length", "=", "sum", "(", "map", "(", "len", ",", "self", ".", "_app_iter", ")", ")", "self", ".", "content_encoding", "=", "'gzip'" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/WebOb/webob/response.py#L950-L968
msracver/Deep-Image-Analogy
632b9287b42552e32dad64922967c8c9ec7fc4d3
scripts/cpp_lint.py
python
FindPreviousMatchingAngleBracket
(clean_lines, linenum, init_prefix)
return False
Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists.
Find the corresponding < that started a template.
[ "Find", "the", "corresponding", "<", "that", "started", "a", "template", "." ]
def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): """Find the corresponding < that started a template. Args: clean_lines: A CleansedLines instance containing the file. linenum: Current line number. init_prefix: Part of the current line before the initial >. Returns: True if a matching bracket exists. """ line = init_prefix nesting_stack = ['>'] while True: # Find the previous operator match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) if match: # Found an operator, update nesting stack operator = match.group(2) line = match.group(1) if nesting_stack[-1] == '>': # Expecting opening angle bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator == '<': nesting_stack.pop() if not nesting_stack: # Found matching angle bracket return True elif operator == ',': # Got a comma before a bracket, this is most likely a # template argument. The opening angle bracket is probably # there if we look for it, so just return early here. return True else: # Got some other operator. return False else: # Expecting opening parenthesis or opening bracket if operator in ('>', ')', ']'): nesting_stack.append(operator) elif operator in ('(', '['): nesting_stack.pop() else: # Scan the previous line linenum -= 1 if linenum < 0: break line = clean_lines.elided[linenum] # Exhausted all earlier lines and still no matching angle bracket. return False
[ "def", "FindPreviousMatchingAngleBracket", "(", "clean_lines", ",", "linenum", ",", "init_prefix", ")", ":", "line", "=", "init_prefix", "nesting_stack", "=", "[", "'>'", "]", "while", "True", ":", "# Find the previous operator", "match", "=", "Search", "(", "r'^(.*)([<>(),;\\[\\]])[^<>(),;\\[\\]]*$'", ",", "line", ")", "if", "match", ":", "# Found an operator, update nesting stack", "operator", "=", "match", ".", "group", "(", "2", ")", "line", "=", "match", ".", "group", "(", "1", ")", "if", "nesting_stack", "[", "-", "1", "]", "==", "'>'", ":", "# Expecting opening angle bracket", "if", "operator", "in", "(", "'>'", ",", "')'", ",", "']'", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "==", "'<'", ":", "nesting_stack", ".", "pop", "(", ")", "if", "not", "nesting_stack", ":", "# Found matching angle bracket", "return", "True", "elif", "operator", "==", "','", ":", "# Got a comma before a bracket, this is most likely a", "# template argument. The opening angle bracket is probably", "# there if we look for it, so just return early here.", "return", "True", "else", ":", "# Got some other operator.", "return", "False", "else", ":", "# Expecting opening parenthesis or opening bracket", "if", "operator", "in", "(", "'>'", ",", "')'", ",", "']'", ")", ":", "nesting_stack", ".", "append", "(", "operator", ")", "elif", "operator", "in", "(", "'('", ",", "'['", ")", ":", "nesting_stack", ".", "pop", "(", ")", "else", ":", "# Scan the previous line", "linenum", "-=", "1", "if", "linenum", "<", "0", ":", "break", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Exhausted all earlier lines and still no matching angle bracket.", "return", "False" ]
https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L2586-L2640
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_logic_utils.py
python
or_clauses2
(clauses1,clauses2)
return clauses1 + clauses2
Take the logical or of two clause sets.
Take the logical or of two clause sets.
[ "Take", "the", "logical", "or", "of", "two", "clause", "sets", "." ]
def or_clauses2(clauses1,clauses2): """ Take the logical or of two clause sets. """ if not clauses1 or not clauses2: return [] if [] in clauses1: return clauses2 if [] in clauses2: return clauses1 used = used_symbols_clauses(clauses1 + clauses2); v = bool_const(UniqueRenamer('__ts',used)()) clauses1 = [[Literal(1,v)] + c for c in clauses1] clauses2 = [[Literal(0,v)] + c for c in clauses2] return clauses1 + clauses2
[ "def", "or_clauses2", "(", "clauses1", ",", "clauses2", ")", ":", "if", "not", "clauses1", "or", "not", "clauses2", ":", "return", "[", "]", "if", "[", "]", "in", "clauses1", ":", "return", "clauses2", "if", "[", "]", "in", "clauses2", ":", "return", "clauses1", "used", "=", "used_symbols_clauses", "(", "clauses1", "+", "clauses2", ")", "v", "=", "bool_const", "(", "UniqueRenamer", "(", "'__ts'", ",", "used", ")", "(", ")", ")", "clauses1", "=", "[", "[", "Literal", "(", "1", ",", "v", ")", "]", "+", "c", "for", "c", "in", "clauses1", "]", "clauses2", "=", "[", "[", "Literal", "(", "0", ",", "v", ")", "]", "+", "c", "for", "c", "in", "clauses2", "]", "return", "clauses1", "+", "clauses2" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_logic_utils.py#L1115-L1127
cvmfs/cvmfs
4637bdb5153178eadf885c1acf37bdc5c685bf8a
cpplint.py
python
CheckCStyleCast
(filename, clean_lines, linenum, cast_type, pattern, error)
return True
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise.
Checks for a C-style cast by looking for the pattern.
[ "Checks", "for", "a", "C", "-", "style", "cast", "by", "looking", "for", "the", "pattern", "." ]
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ line = clean_lines.elided[linenum] match = Search(pattern, line) if not match: return False # Exclude lines with keywords that tend to look like casts context = line[0:match.start(1) - 1] if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): return False # Try expanding current context to see if we one level of # parentheses inside a macro. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 5), -1): context = clean_lines.elided[i] + context if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): return False # operator++(int) and operator--(int) if context.endswith(' operator++') or context.endswith(' operator--'): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # [](int) -> bool { # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # Function((function_pointer_arg)(int), int param) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); raw_line = clean_lines.raw_lines[linenum] if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True
[ "def", "CheckCStyleCast", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "cast_type", ",", "pattern", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "match", "=", "Search", "(", "pattern", ",", "line", ")", "if", "not", "match", ":", "return", "False", "# Exclude lines with keywords that tend to look like casts", "context", "=", "line", "[", "0", ":", "match", ".", "start", "(", "1", ")", "-", "1", "]", "if", "Match", "(", "r'.*\\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\\s*$'", ",", "context", ")", ":", "return", "False", "# Try expanding current context to see if we one level of", "# parentheses inside a macro.", "if", "linenum", ">", "0", ":", "for", "i", "in", "xrange", "(", "linenum", "-", "1", ",", "max", "(", "0", ",", "linenum", "-", "5", ")", ",", "-", "1", ")", ":", "context", "=", "clean_lines", ".", "elided", "[", "i", "]", "+", "context", "if", "Match", "(", "r'.*\\b[_A-Z][_A-Z0-9]*\\s*\\((?:\\([^()]*\\)|[^()])*$'", ",", "context", ")", ":", "return", "False", "# operator++(int) and operator--(int)", "if", "context", ".", "endswith", "(", "' operator++'", ")", "or", "context", ".", "endswith", "(", "' operator--'", ")", ":", "return", "False", "# A single unnamed argument for a function tends to look like old", "# style cast. If we see those, don't issue warnings for deprecated", "# casts, instead issue warnings for unnamed arguments where", "# appropriate.", "#", "# These are things that we want warnings for, since the style guide", "# explicitly require all parameters to be named:", "# Function(int);", "# Function(int) {", "# ConstMember(int) const;", "# ConstMember(int) const {", "# ExceptionMember(int) throw (...);", "# ExceptionMember(int) throw (...) {", "# PureVirtual(int) = 0;", "# [](int) -> bool {", "#", "# These are functions of some sort, where the compiler would be fine", "# if they had named parameters, but people often omit those", "# identifiers to reduce clutter:", "# (FunctionPointer)(int);", "# (FunctionPointer)(int) = value;", "# Function((function_pointer_arg)(int))", "# Function((function_pointer_arg)(int), int param)", "# <TemplateArgument(int)>;", "# <(FunctionPointerTemplateArgument)(int)>;", "remainder", "=", "line", "[", "match", ".", "end", "(", "0", ")", ":", "]", "if", "Match", "(", "r'^\\s*(?:;|const\\b|throw\\b|final\\b|override\\b|[=>{),]|->)'", ",", "remainder", ")", ":", "# Looks like an unnamed parameter.", "# Don't warn on any kind of template arguments.", "if", "Match", "(", "r'^\\s*>'", ",", "remainder", ")", ":", "return", "False", "# Don't warn on assignments to function pointers, but keep warnings for", "# unnamed parameters to pure virtual functions. Note that this pattern", "# will also pass on assignments of \"0\" to function pointers, but the", "# preferred values for those would be \"nullptr\" or \"NULL\".", "matched_zero", "=", "Match", "(", "r'^\\s=\\s*(\\S+)\\s*;'", ",", "remainder", ")", "if", "matched_zero", "and", "matched_zero", ".", "group", "(", "1", ")", "!=", "'0'", ":", "return", "False", "# Don't warn on function pointer declarations. For this we need", "# to check what came before the \"(type)\" string.", "if", "Match", "(", "r'.*\\)\\s*$'", ",", "line", "[", "0", ":", "match", ".", "start", "(", "0", ")", "]", ")", ":", "return", "False", "# Don't warn if the parameter is named with block comments, e.g.:", "# Function(int /*unused_param*/);", "raw_line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "if", "'/*'", "in", "raw_line", ":", "return", "False", "# Passed all filters, issue warning here.", "error", "(", "filename", ",", "linenum", ",", "'readability/function'", ",", "3", ",", "'All parameters should be named in a function'", ")", "return", "True", "# At this point, all that should be left is actual casts.", "error", "(", "filename", ",", "linenum", ",", "'readability/casting'", ",", "4", ",", "'Using C-style cast. Use %s<%s>(...) instead'", "%", "(", "cast_type", ",", "match", ".", "group", "(", "1", ")", ")", ")", "return", "True" ]
https://github.com/cvmfs/cvmfs/blob/4637bdb5153178eadf885c1acf37bdc5c685bf8a/cpplint.py#L5344-L5445
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
Examples/Image/Detection/FastRCNN/BrainScript/fastRCNN/imdb.py
python
imdb.competition_mode
(self, on)
Turn competition mode on or off.
Turn competition mode on or off.
[ "Turn", "competition", "mode", "on", "or", "off", "." ]
def competition_mode(self, on): """Turn competition mode on or off.""" pass
[ "def", "competition_mode", "(", "self", ",", "on", ")", ":", "pass" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/Examples/Image/Detection/FastRCNN/BrainScript/fastRCNN/imdb.py#L199-L201
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/mojo/public/tools/bindings/pylib/mojom/generate/translate.py
python
_Parameter
(module, parsed_param, interface)
return parameter
Args: module: {mojom.Module} Module currently being constructed. parsed_param: {ast.Parameter} Parsed parameter. union: {mojom.Interface} Interface this parameter belongs to. Returns: {mojom.Parameter} AST parameter.
Args: module: {mojom.Module} Module currently being constructed. parsed_param: {ast.Parameter} Parsed parameter. union: {mojom.Interface} Interface this parameter belongs to.
[ "Args", ":", "module", ":", "{", "mojom", ".", "Module", "}", "Module", "currently", "being", "constructed", ".", "parsed_param", ":", "{", "ast", ".", "Parameter", "}", "Parsed", "parameter", ".", "union", ":", "{", "mojom", ".", "Interface", "}", "Interface", "this", "parameter", "belongs", "to", "." ]
def _Parameter(module, parsed_param, interface): """ Args: module: {mojom.Module} Module currently being constructed. parsed_param: {ast.Parameter} Parsed parameter. union: {mojom.Interface} Interface this parameter belongs to. Returns: {mojom.Parameter} AST parameter. """ parameter = mojom.Parameter() parameter.mojom_name = parsed_param.mojom_name parameter.kind = _Kind( module.kinds, _MapKind(parsed_param.typename), (module.mojom_namespace, interface.mojom_name)) parameter.ordinal = ( parsed_param.ordinal.value if parsed_param.ordinal else None) parameter.default = None # TODO(tibell): We never have these. Remove field? parameter.attributes = _AttributeListToDict(parsed_param.attribute_list) return parameter
[ "def", "_Parameter", "(", "module", ",", "parsed_param", ",", "interface", ")", ":", "parameter", "=", "mojom", ".", "Parameter", "(", ")", "parameter", ".", "mojom_name", "=", "parsed_param", ".", "mojom_name", "parameter", ".", "kind", "=", "_Kind", "(", "module", ".", "kinds", ",", "_MapKind", "(", "parsed_param", ".", "typename", ")", ",", "(", "module", ".", "mojom_namespace", ",", "interface", ".", "mojom_name", ")", ")", "parameter", ".", "ordinal", "=", "(", "parsed_param", ".", "ordinal", ".", "value", "if", "parsed_param", ".", "ordinal", "else", "None", ")", "parameter", ".", "default", "=", "None", "# TODO(tibell): We never have these. Remove field?", "parameter", ".", "attributes", "=", "_AttributeListToDict", "(", "parsed_param", ".", "attribute_list", ")", "return", "parameter" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/mojo/public/tools/bindings/pylib/mojom/generate/translate.py#L365-L384
hszhao/PSPNet
cf7e5a99ba37e46118026e96be5821a9bc63bde0
scripts/cpp_lint.py
python
_ClassifyInclude
(fileinfo, include, is_system)
return _OTHER_HEADER
Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER
Figures out what kind of header 'include' is.
[ "Figures", "out", "what", "kind", "of", "header", "include", "is", "." ]
def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_cpp_h = include in _CPP_HEADERS if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) if target_base == include_base and ( include_dir == target_dir or include_dir == os.path.normpath(target_dir + '/../public')): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER
[ "def", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ":", "# This is a list of all standard c++ header files, except", "# those already checked for above.", "is_cpp_h", "=", "include", "in", "_CPP_HEADERS", "if", "is_system", ":", "if", "is_cpp_h", ":", "return", "_CPP_SYS_HEADER", "else", ":", "return", "_C_SYS_HEADER", "# If the target file and the include we're checking share a", "# basename when we drop common extensions, and the include", "# lives in . , then it's likely to be owned by the target file.", "target_dir", ",", "target_base", "=", "(", "os", ".", "path", ".", "split", "(", "_DropCommonSuffixes", "(", "fileinfo", ".", "RepositoryName", "(", ")", ")", ")", ")", "include_dir", ",", "include_base", "=", "os", ".", "path", ".", "split", "(", "_DropCommonSuffixes", "(", "include", ")", ")", "if", "target_base", "==", "include_base", "and", "(", "include_dir", "==", "target_dir", "or", "include_dir", "==", "os", ".", "path", ".", "normpath", "(", "target_dir", "+", "'/../public'", ")", ")", ":", "return", "_LIKELY_MY_HEADER", "# If the target and include share some initial basename", "# component, it's possible the target is implementing the", "# include, so it's allowed to be first, but we'll never", "# complain if it's not there.", "target_first_component", "=", "_RE_FIRST_COMPONENT", ".", "match", "(", "target_base", ")", "include_first_component", "=", "_RE_FIRST_COMPONENT", ".", "match", "(", "include_base", ")", "if", "(", "target_first_component", "and", "include_first_component", "and", "target_first_component", ".", "group", "(", "0", ")", "==", "include_first_component", ".", "group", "(", "0", ")", ")", ":", "return", "_POSSIBLE_MY_HEADER", "return", "_OTHER_HEADER" ]
https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L3620-L3676
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py
python
BaseContainer.__ne__
(self, other)
return not self == other
Checks if another instance isn't equal to this one.
Checks if another instance isn't equal to this one.
[ "Checks", "if", "another", "instance", "isn", "t", "equal", "to", "this", "one", "." ]
def __ne__(self, other): """Checks if another instance isn't equal to this one.""" # The concrete classes should define __eq__. return not self == other
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "# The concrete classes should define __eq__.", "return", "not", "self", "==", "other" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py#L70-L73
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/range-sum-query-immutable.py
python
NumArray.__init__
(self, nums)
initialize your data structure here. :type nums: List[int]
initialize your data structure here. :type nums: List[int]
[ "initialize", "your", "data", "structure", "here", ".", ":", "type", "nums", ":", "List", "[", "int", "]" ]
def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.accu = [0] for num in nums: self.accu.append(self.accu[-1] + num),
[ "def", "__init__", "(", "self", ",", "nums", ")", ":", "self", ".", "accu", "=", "[", "0", "]", "for", "num", "in", "nums", ":", "self", ".", "accu", ".", "append", "(", "self", ".", "accu", "[", "-", "1", "]", "+", "num", ")", "," ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/range-sum-query-immutable.py#L6-L13
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
priority_queue/minheap.py
python
MinHeap.get_min
(self)
return self.data[1]
get_min returns the minimum value (i.e. root) in the heap, without removing it. Returns None, if the heap is empty.
get_min returns the minimum value (i.e. root) in the heap, without removing it. Returns None, if the heap is empty.
[ "get_min", "returns", "the", "minimum", "value", "(", "i", ".", "e", ".", "root", ")", "in", "the", "heap", "without", "removing", "it", ".", "Returns", "None", "if", "the", "heap", "is", "empty", "." ]
def get_min(self): """ get_min returns the minimum value (i.e. root) in the heap, without removing it. Returns None, if the heap is empty. """ if self.is_empty(): return None return self.data[1]
[ "def", "get_min", "(", "self", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "return", "None", "return", "self", ".", "data", "[", "1", "]" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/priority_queue/minheap.py#L28-L34
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pexpect/pexpect/screen.py
python
screen.cursor_unsave
(self)
Restores cursor position after a Save Cursor.
Restores cursor position after a Save Cursor.
[ "Restores", "cursor", "position", "after", "a", "Save", "Cursor", "." ]
def cursor_unsave (self): # <ESC>[u '''Restores cursor position after a Save Cursor.''' self.cursor_restore_attrs()
[ "def", "cursor_unsave", "(", "self", ")", ":", "# <ESC>[u", "self", ".", "cursor_restore_attrs", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pexpect/pexpect/screen.py#L323-L326
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py
python
resolve_ssl_version
(candidate)
return candidate
like resolve_cert_reqs
like resolve_cert_reqs
[ "like", "resolve_cert_reqs" ]
def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_SSLv23 if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'PROTOCOL_' + candidate) return res return candidate
[ "def", "resolve_ssl_version", "(", "candidate", ")", ":", "if", "candidate", "is", "None", ":", "return", "PROTOCOL_SSLv23", "if", "isinstance", "(", "candidate", ",", "str", ")", ":", "res", "=", "getattr", "(", "ssl", ",", "candidate", ",", "None", ")", "if", "res", "is", "None", ":", "res", "=", "getattr", "(", "ssl", ",", "'PROTOCOL_'", "+", "candidate", ")", "return", "res", "return", "candidate" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py#L165-L178
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/connectionpool.py
python
HTTPConnectionPool.close
(self)
Close all pooled connections and disable the pool.
Close all pooled connections and disable the pool.
[ "Close", "all", "pooled", "connections", "and", "disable", "the", "pool", "." ]
def close(self): """ Close all pooled connections and disable the pool. """ if self.pool is None: return # Disable access to the pool old_pool, self.pool = self.pool, None try: while True: conn = old_pool.get(block=False) if conn: conn.close() except queue.Empty: pass
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "pool", "is", "None", ":", "return", "# Disable access to the pool", "old_pool", ",", "self", ".", "pool", "=", "self", ".", "pool", ",", "None", "try", ":", "while", "True", ":", "conn", "=", "old_pool", ".", "get", "(", "block", "=", "False", ")", "if", "conn", ":", "conn", ".", "close", "(", ")", "except", "queue", ".", "Empty", ":", "pass" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/connectionpool.py#L479-L495
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiNotebook.ShowWindowMenu
(*args, **kwargs)
return _aui.AuiNotebook_ShowWindowMenu(*args, **kwargs)
ShowWindowMenu(self) -> bool
ShowWindowMenu(self) -> bool
[ "ShowWindowMenu", "(", "self", ")", "-", ">", "bool" ]
def ShowWindowMenu(*args, **kwargs): """ShowWindowMenu(self) -> bool""" return _aui.AuiNotebook_ShowWindowMenu(*args, **kwargs)
[ "def", "ShowWindowMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiNotebook_ShowWindowMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1373-L1375
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Place.place_forget
(self)
Unmap this widget.
Unmap this widget.
[ "Unmap", "this", "widget", "." ]
def place_forget(self): """Unmap this widget.""" self.tk.call('place', 'forget', self._w)
[ "def", "place_forget", "(", "self", ")", ":", "self", ".", "tk", ".", "call", "(", "'place'", ",", "'forget'", ",", "self", ".", "_w", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1921-L1923
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/debug/cli/analyzer_cli.py
python
DebugAnalyzer.get_tensor_filter
(self, filter_name)
return self._tensor_filters[filter_name]
Retrieve filter function by name. Args: filter_name: Name of the filter set during add_tensor_filter() call. Returns: The callable associated with the filter name. Raises: ValueError: If there is no tensor filter of the specified filter name.
Retrieve filter function by name.
[ "Retrieve", "filter", "function", "by", "name", "." ]
def get_tensor_filter(self, filter_name): """Retrieve filter function by name. Args: filter_name: Name of the filter set during add_tensor_filter() call. Returns: The callable associated with the filter name. Raises: ValueError: If there is no tensor filter of the specified filter name. """ if filter_name not in self._tensor_filters: raise ValueError("There is no tensor filter named \"%s\"" % filter_name) return self._tensor_filters[filter_name]
[ "def", "get_tensor_filter", "(", "self", ",", "filter_name", ")", ":", "if", "filter_name", "not", "in", "self", ".", "_tensor_filters", ":", "raise", "ValueError", "(", "\"There is no tensor filter named \\\"%s\\\"\"", "%", "filter_name", ")", "return", "self", ".", "_tensor_filters", "[", "filter_name", "]" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/analyzer_cli.py#L447-L463
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py
python
merge_processors
(processors: List[Processor])
return _MergedProcessor(processors)
Merge multiple `Processor` objects into one.
Merge multiple `Processor` objects into one.
[ "Merge", "multiple", "Processor", "objects", "into", "one", "." ]
def merge_processors(processors: List[Processor]) -> Processor: """ Merge multiple `Processor` objects into one. """ if len(processors) == 0: return DummyProcessor() if len(processors) == 1: return processors[0] # Nothing to merge. return _MergedProcessor(processors)
[ "def", "merge_processors", "(", "processors", ":", "List", "[", "Processor", "]", ")", "->", "Processor", ":", "if", "len", "(", "processors", ")", "==", "0", ":", "return", "DummyProcessor", "(", ")", "if", "len", "(", "processors", ")", "==", "1", ":", "return", "processors", "[", "0", "]", "# Nothing to merge.", "return", "_MergedProcessor", "(", "processors", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py#L965-L975
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
xpathContext.xpathRegisterAllFunctions
(self)
Registers all default XPath functions in this context
Registers all default XPath functions in this context
[ "Registers", "all", "default", "XPath", "functions", "in", "this", "context" ]
def xpathRegisterAllFunctions(self): """Registers all default XPath functions in this context """ libxml2mod.xmlXPathRegisterAllFunctions(self._o)
[ "def", "xpathRegisterAllFunctions", "(", "self", ")", ":", "libxml2mod", ".", "xmlXPathRegisterAllFunctions", "(", "self", ".", "_o", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L7366-L7368
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/base64.py
python
b64decode
(s, altchars=None, validate=False)
return binascii.a2b_base64(s)
Decode the Base64 encoded bytes-like object or ASCII string s. Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. The result is returned as a bytes object. A binascii.Error is raised if s is incorrectly padded. If validate is False (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If validate is True, these non-alphabet characters in the input result in a binascii.Error.
Decode the Base64 encoded bytes-like object or ASCII string s.
[ "Decode", "the", "Base64", "encoded", "bytes", "-", "like", "object", "or", "ASCII", "string", "s", "." ]
def b64decode(s, altchars=None, validate=False): """Decode the Base64 encoded bytes-like object or ASCII string s. Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters. The result is returned as a bytes object. A binascii.Error is raised if s is incorrectly padded. If validate is False (the default), characters that are neither in the normal base-64 alphabet nor the alternative alphabet are discarded prior to the padding check. If validate is True, these non-alphabet characters in the input result in a binascii.Error. """ s = _bytes_from_decode_data(s) if altchars is not None: altchars = _bytes_from_decode_data(altchars) assert len(altchars) == 2, repr(altchars) s = s.translate(bytes.maketrans(altchars, b'+/')) if validate and not re.fullmatch(b'[A-Za-z0-9+/]*={0,2}', s): raise binascii.Error('Non-base64 digit found') return binascii.a2b_base64(s)
[ "def", "b64decode", "(", "s", ",", "altchars", "=", "None", ",", "validate", "=", "False", ")", ":", "s", "=", "_bytes_from_decode_data", "(", "s", ")", "if", "altchars", "is", "not", "None", ":", "altchars", "=", "_bytes_from_decode_data", "(", "altchars", ")", "assert", "len", "(", "altchars", ")", "==", "2", ",", "repr", "(", "altchars", ")", "s", "=", "s", ".", "translate", "(", "bytes", ".", "maketrans", "(", "altchars", ",", "b'+/'", ")", ")", "if", "validate", "and", "not", "re", ".", "fullmatch", "(", "b'[A-Za-z0-9+/]*={0,2}'", ",", "s", ")", ":", "raise", "binascii", ".", "Error", "(", "'Non-base64 digit found'", ")", "return", "binascii", ".", "a2b_base64", "(", "s", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/base64.py#L65-L87
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py
python
_AddSerializeToStringMethod
(message_descriptor, cls)
Helper for _AddMessageMethods().
Helper for _AddMessageMethods().
[ "Helper", "for", "_AddMessageMethods", "()", "." ]
def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( 'Message is missing required fields: ' + ','.join(self.FindInitializationErrors())) return self.SerializePartialToString() cls.SerializeToString = SerializeToString
[ "def", "_AddSerializeToStringMethod", "(", "message_descriptor", ",", "cls", ")", ":", "def", "SerializeToString", "(", "self", ")", ":", "# Check if the message has all of its required fields set.", "errors", "=", "[", "]", "if", "not", "self", ".", "IsInitialized", "(", ")", ":", "raise", "message_mod", ".", "EncodeError", "(", "'Message is missing required fields: '", "+", "','", ".", "join", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", ")", "return", "self", ".", "SerializePartialToString", "(", ")", "cls", ".", "SerializeToString", "=", "SerializeToString" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L787-L798
yuxng/PoseCNN
9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04
lib/gt_single_data_layer/layer.py
python
GtSingleDataLayer._shuffle_roidb_inds
(self)
Randomly permute the training roidb.
Randomly permute the training roidb.
[ "Randomly", "permute", "the", "training", "roidb", "." ]
def _shuffle_roidb_inds(self): """Randomly permute the training roidb.""" self._perm = np.random.permutation(np.arange(len(self._roidb))) #print self._roidb[self._perm[14]]['meta_data'] #print self._roidb[self._perm[15]]['meta_data'] #print self._roidb[self._perm[16]]['meta_data'] self._cur = 0
[ "def", "_shuffle_roidb_inds", "(", "self", ")", ":", "self", ".", "_perm", "=", "np", ".", "random", ".", "permutation", "(", "np", ".", "arange", "(", "len", "(", "self", ".", "_roidb", ")", ")", ")", "#print self._roidb[self._perm[14]]['meta_data']", "#print self._roidb[self._perm[15]]['meta_data']", "#print self._roidb[self._perm[16]]['meta_data']", "self", ".", "_cur", "=", "0" ]
https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/gt_single_data_layer/layer.py#L27-L33
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/fractions.py
python
Fraction._richcmp
(self, other, op)
Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators.
Helper for comparison operators, for internal use only.
[ "Helper", "for", "comparison", "operators", "for", "internal", "use", "only", "." ]
def _richcmp(self, other, op): """Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. """ # convert other to a Rational instance where reasonable. if isinstance(other, Rational): return op(self._numerator * other.denominator, self._denominator * other.numerator) # comparisons with complex should raise a TypeError, for consistency # with int<->complex, float<->complex, and complex<->complex comparisons. if isinstance(other, complex): raise TypeError("no ordering relation is defined for complex numbers") if isinstance(other, float): if math.isnan(other) or math.isinf(other): return op(0.0, other) else: return op(self, self.from_float(other)) else: return NotImplemented
[ "def", "_richcmp", "(", "self", ",", "other", ",", "op", ")", ":", "# convert other to a Rational instance where reasonable.", "if", "isinstance", "(", "other", ",", "Rational", ")", ":", "return", "op", "(", "self", ".", "_numerator", "*", "other", ".", "denominator", ",", "self", ".", "_denominator", "*", "other", ".", "numerator", ")", "# comparisons with complex should raise a TypeError, for consistency", "# with int<->complex, float<->complex, and complex<->complex comparisons.", "if", "isinstance", "(", "other", ",", "complex", ")", ":", "raise", "TypeError", "(", "\"no ordering relation is defined for complex numbers\"", ")", "if", "isinstance", "(", "other", ",", "float", ")", ":", "if", "math", ".", "isnan", "(", "other", ")", "or", "math", ".", "isinf", "(", "other", ")", ":", "return", "op", "(", "0.0", ",", "other", ")", "else", ":", "return", "op", "(", "self", ",", "self", ".", "from_float", "(", "other", ")", ")", "else", ":", "return", "NotImplemented" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/fractions.py#L546-L570