nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py | python | PreprocessFilePath | (ctx, input, alias_invalid_callback, alias_not_enabled_callback) | Perform a preprocess to a path to perform the following:
* Substitute any alias (@<ALIAS>@) with the alias value
* Convert relative paths to absolute paths using the base_path as the pivot (if set)
:param ctx: Context
:param input_path: Relative, absolute, or aliased pathj
:param base_path: Base path to resolve relative paths if supplied. If not, relative paths stay relative
:param return_filenode: Flag to return a Node object instead of an absolute path
:return: The processed path | Perform a preprocess to a path to perform the following: | [
"Perform",
"a",
"preprocess",
"to",
"a",
"path",
"to",
"perform",
"the",
"following",
":"
] | def PreprocessFilePath(ctx, input, alias_invalid_callback, alias_not_enabled_callback):
"""
Perform a preprocess to a path to perform the following:
* Substitute any alias (@<ALIAS>@) with the alias value
* Convert relative paths to absolute paths using the base_path as the pivot (if set)
:param ctx: Context
:param input_path: Relative, absolute, or aliased pathj
:param base_path: Base path to resolve relative paths if supplied. If not, relative paths stay relative
:param return_filenode: Flag to return a Node object instead of an absolute path
:return: The processed path
"""
if isinstance(input, Node.Node):
input_path = input.abspath()
else:
input_path = input
# Perform alias check first
alias_match_groups = REGEX_PATH_ALIAS.search(input_path)
if alias_match_groups:
# Alias pattern detected, evaluate the alias
alias_key = alias_match_groups.group(1)
if alias_key == "ENGINE":
# Apply the @ENGINE@ Alias
processed_path = os.path.normpath(input_path.replace('@{}@'.format(alias_key), ctx.engine_node.abspath()))
return processed_path
elif alias_key == "PROJECT":
# Apply the @PROJECT@ Alias
processed_path = os.path.normpath(input_path.replace('@{}@'.format(alias_key), Context.launch_dir))
return processed_path
elif alias_key.startswith(FILE_ALIAS_3P_PREFIX):
# Apply a third party alias reference
third_party_identifier = alias_key.replace(FILE_ALIAS_3P_PREFIX, "").strip()
resolved_path, enabled, roles, optional = ctx.tp.get_third_party_path(None, third_party_identifier)
# If the path was not resolved, it could be an invalid alias (missing from the SetupAssistantConfig.json
if not resolved_path:
alias_invalid_callback(alias_key)
# If the path was resolved, we still need to make sure the 3rd party is enabled based on the roles
if not enabled and not optional:
sdk_roles = ctx.get_sdk_setup_assistant_roles_for_sdk(third_party_identifier)
alias_not_enabled_callback(alias_key, sdk_roles)
processed_path = os.path.normpath(input_path.replace('@{}@'.format(alias_key), resolved_path))
return processed_path
else:
return input_path
else:
return input_path | [
"def",
"PreprocessFilePath",
"(",
"ctx",
",",
"input",
",",
"alias_invalid_callback",
",",
"alias_not_enabled_callback",
")",
":",
"if",
"isinstance",
"(",
"input",
",",
"Node",
".",
"Node",
")",
":",
"input_path",
"=",
"input",
".",
"abspath",
"(",
")",
"else",
":",
"input_path",
"=",
"input",
"# Perform alias check first",
"alias_match_groups",
"=",
"REGEX_PATH_ALIAS",
".",
"search",
"(",
"input_path",
")",
"if",
"alias_match_groups",
":",
"# Alias pattern detected, evaluate the alias",
"alias_key",
"=",
"alias_match_groups",
".",
"group",
"(",
"1",
")",
"if",
"alias_key",
"==",
"\"ENGINE\"",
":",
"# Apply the @ENGINE@ Alias",
"processed_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"input_path",
".",
"replace",
"(",
"'@{}@'",
".",
"format",
"(",
"alias_key",
")",
",",
"ctx",
".",
"engine_node",
".",
"abspath",
"(",
")",
")",
")",
"return",
"processed_path",
"elif",
"alias_key",
"==",
"\"PROJECT\"",
":",
"# Apply the @PROJECT@ Alias",
"processed_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"input_path",
".",
"replace",
"(",
"'@{}@'",
".",
"format",
"(",
"alias_key",
")",
",",
"Context",
".",
"launch_dir",
")",
")",
"return",
"processed_path",
"elif",
"alias_key",
".",
"startswith",
"(",
"FILE_ALIAS_3P_PREFIX",
")",
":",
"# Apply a third party alias reference",
"third_party_identifier",
"=",
"alias_key",
".",
"replace",
"(",
"FILE_ALIAS_3P_PREFIX",
",",
"\"\"",
")",
".",
"strip",
"(",
")",
"resolved_path",
",",
"enabled",
",",
"roles",
",",
"optional",
"=",
"ctx",
".",
"tp",
".",
"get_third_party_path",
"(",
"None",
",",
"third_party_identifier",
")",
"# If the path was not resolved, it could be an invalid alias (missing from the SetupAssistantConfig.json",
"if",
"not",
"resolved_path",
":",
"alias_invalid_callback",
"(",
"alias_key",
")",
"# If the path was resolved, we still need to make sure the 3rd party is enabled based on the roles",
"if",
"not",
"enabled",
"and",
"not",
"optional",
":",
"sdk_roles",
"=",
"ctx",
".",
"get_sdk_setup_assistant_roles_for_sdk",
"(",
"third_party_identifier",
")",
"alias_not_enabled_callback",
"(",
"alias_key",
",",
"sdk_roles",
")",
"processed_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"input_path",
".",
"replace",
"(",
"'@{}@'",
".",
"format",
"(",
"alias_key",
")",
",",
"resolved_path",
")",
")",
"return",
"processed_path",
"else",
":",
"return",
"input_path",
"else",
":",
"return",
"input_path"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/lmbrwaflib/lumberyard.py#L846-L901 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/io/formats/latex.py | python | RowStringConverter._header_row_num | (self) | return self.header_levels if self.fmt.header else 0 | Number of rows in header. | Number of rows in header. | [
"Number",
"of",
"rows",
"in",
"header",
"."
] | def _header_row_num(self) -> int:
"""Number of rows in header."""
return self.header_levels if self.fmt.header else 0 | [
"def",
"_header_row_num",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"header_levels",
"if",
"self",
".",
"fmt",
".",
"header",
"else",
"0"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/latex.py#L120-L122 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/specs/python/params_ops.py | python | Lf | (lo, hi) | return math.exp(random.uniform(math.log(lo), math.log(hi))) | Log-uniform distributed floatint point number. | Log-uniform distributed floatint point number. | [
"Log",
"-",
"uniform",
"distributed",
"floatint",
"point",
"number",
"."
] | def Lf(lo, hi):
"""Log-uniform distributed floatint point number."""
return math.exp(random.uniform(math.log(lo), math.log(hi))) | [
"def",
"Lf",
"(",
"lo",
",",
"hi",
")",
":",
"return",
"math",
".",
"exp",
"(",
"random",
".",
"uniform",
"(",
"math",
".",
"log",
"(",
"lo",
")",
",",
"math",
".",
"log",
"(",
"hi",
")",
")",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/specs/python/params_ops.py#L71-L73 | |
naver/sling | 5671cd445a2caae0b4dd0332299e4cfede05062c | webkit/Tools/Scripts/webkitpy/common/system/path.py | python | _convert_path | (platform, path) | return _unixypath_to_uri(path) | Handles any os-specific path separators, mappings, etc. | Handles any os-specific path separators, mappings, etc. | [
"Handles",
"any",
"os",
"-",
"specific",
"path",
"separators",
"mappings",
"etc",
"."
] | def _convert_path(platform, path):
"""Handles any os-specific path separators, mappings, etc."""
if platform.is_cygwin():
return _winpath_to_uri(cygpath(path))
if platform.is_win():
return _winpath_to_uri(path)
return _unixypath_to_uri(path) | [
"def",
"_convert_path",
"(",
"platform",
",",
"path",
")",
":",
"if",
"platform",
".",
"is_cygwin",
"(",
")",
":",
"return",
"_winpath_to_uri",
"(",
"cygpath",
"(",
"path",
")",
")",
"if",
"platform",
".",
"is_win",
"(",
")",
":",
"return",
"_winpath_to_uri",
"(",
"path",
")",
"return",
"_unixypath_to_uri",
"(",
"path",
")"
] | https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/common/system/path.py#L131-L137 | |
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/util/decorators.py | python | advance_logger | (loglevel) | A decorator that log performance infos of a function call at runtime
Args:
loglevel (str): "DEBUG" or "INFO"(case ignored), log level | A decorator that log performance infos of a function call at runtime | [
"A",
"decorator",
"that",
"log",
"performance",
"infos",
"of",
"a",
"function",
"call",
"at",
"runtime"
] | def advance_logger(loglevel):
"""
A decorator that log performance infos of a function call at runtime
Args:
loglevel (str): "DEBUG" or "INFO"(case ignored), log level
"""
def _get_line_number():
return inspect.currentframe().f_back.f_back.f_lineno
def _basic_log(fn, result, *args, **kwargs):
print "function = " + fn.__name__,
print " arguments = {0} {1}".format(args, kwargs)
print " return = {0}".format(result)
def _info_log_decorator(fn):
@wraps(fn)
def _wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
_basic_log(fn, result, args, kwargs)
return _wrapper
def _debug_log_decorator(fn):
@wraps(fn)
def _wrapper(*args, **kwargs):
ts = time.time()
result = fn(*args, **kwargs)
te = time.time()
_basic_log(fn, result, args, kwargs)
print " time = %.6f sec" % (te-ts)
print " called_from_line : " + str(_get_line_number())
return _wrapper
if loglevel.lower == "debug":
return _debug_log_decorator
else:
return _info_log_decorator | [
"def",
"advance_logger",
"(",
"loglevel",
")",
":",
"def",
"_get_line_number",
"(",
")",
":",
"return",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
".",
"f_back",
".",
"f_lineno",
"def",
"_basic_log",
"(",
"fn",
",",
"result",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"\"function = \"",
"+",
"fn",
".",
"__name__",
",",
"print",
"\" arguments = {0} {1}\"",
".",
"format",
"(",
"args",
",",
"kwargs",
")",
"print",
"\" return = {0}\"",
".",
"format",
"(",
"result",
")",
"def",
"_info_log_decorator",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_basic_log",
"(",
"fn",
",",
"result",
",",
"args",
",",
"kwargs",
")",
"return",
"_wrapper",
"def",
"_debug_log_decorator",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ts",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"te",
"=",
"time",
".",
"time",
"(",
")",
"_basic_log",
"(",
"fn",
",",
"result",
",",
"args",
",",
"kwargs",
")",
"print",
"\" time = %.6f sec\"",
"%",
"(",
"te",
"-",
"ts",
")",
"print",
"\" called_from_line : \"",
"+",
"str",
"(",
"_get_line_number",
"(",
")",
")",
"return",
"_wrapper",
"if",
"loglevel",
".",
"lower",
"==",
"\"debug\"",
":",
"return",
"_debug_log_decorator",
"else",
":",
"return",
"_info_log_decorator"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/util/decorators.py#L32-L69 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | predefinedEntity | (name) | return xmlEntity(_obj=ret) | Check whether this name is an predefined entity. | Check whether this name is an predefined entity. | [
"Check",
"whether",
"this",
"name",
"is",
"an",
"predefined",
"entity",
"."
] | def predefinedEntity(name):
"""Check whether this name is an predefined entity. """
ret = libxml2mod.xmlGetPredefinedEntity(name)
if ret is None:raise treeError('xmlGetPredefinedEntity() failed')
return xmlEntity(_obj=ret) | [
"def",
"predefinedEntity",
"(",
"name",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlGetPredefinedEntity",
"(",
"name",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlGetPredefinedEntity() failed'",
")",
"return",
"xmlEntity",
"(",
"_obj",
"=",
"ret",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L366-L370 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/crywaflib/msvs.py | python | vsnode_build_all.collect_properties | (self) | Visual studio projects are associated with platforms and configurations (for building especially) | Visual studio projects are associated with platforms and configurations (for building especially) | [
"Visual",
"studio",
"projects",
"are",
"associated",
"with",
"platforms",
"and",
"configurations",
"(",
"for",
"building",
"especially",
")"
] | def collect_properties(self):
"""
Visual studio projects are associated with platforms and configurations (for building especially)
"""
super(vsnode_build_all, self).collect_properties()
for x in self.build_properties:
x.outdir = self.path.parent.abspath()
x.preprocessor_definitions = ''
x.includes_search_path = ''
x.c_flags = ''
x.cxx_flags = ''
x.link_flags = ''
x.target_spec = ''
x.target_config = ''
if x.platform == 'CppCheck':
continue
waf_spec = self.ctx.convert_vs_spec_to_waf_spec(x.configuration)
waf_platform = self.ctx.convert_vs_platform_to_waf_platform(x.platform)
waf_configuration = self.ctx.convert_vs_configuration_to_waf_configuration(x.configuration)
current_env = self.ctx.all_envs[waf_platform + '_' + waf_configuration]
if waf_platform == 'orbis':
x.platform_toolset = 'Clang'
x.android_platform_target_version = ''
else:
x.platform_toolset = 'v' + str(current_env['MSVC_VERSION']).replace('.','') if current_env['MSVC_VERSION'] else ""
x.android_platform_target_version = str(current_env['ANDROID_TARGET_VERSION']) if current_env['ANDROID_TARGET_VERSION'] else "23"
x.target_spec = waf_spec
x.target_config = waf_platform + '_' + waf_configuration
# Collect WAF files
waf_data_dir = self.ctx.root.make_node(Context.launch_dir).make_node('_WAF_')
waf_source_dir = self.ctx.root.make_node(Context.launch_dir).make_node('Code/Tools/waf-1.7.13')
waf_config_files = waf_data_dir.ant_glob('**/*', maxdepth=0)
waf_spec_files = waf_data_dir.make_node('specs').ant_glob('**/*')
waf_scripts = waf_source_dir.make_node('waflib').ant_glob('**/*.py')
waf_crytek_scripts = waf_source_dir.make_node('crywaflib').ant_glob('**/*.py')
# Remove files found in crywaflib from waf scripts
tmp = []
waf_crytek_scripts_files = []
for node in waf_crytek_scripts:
waf_crytek_scripts_files += [os.path.basename(node.abspath())]
for x in waf_scripts:
if os.path.basename(x.abspath()) in waf_crytek_scripts_files:
continue
tmp += [x]
waf_scripts = tmp
for file in waf_config_files:
self.project_filter[file.abspath()] = 'Settings'
for file in waf_spec_files:
self.project_filter[file.abspath()] = 'Specs'
for file in waf_scripts:
filter_name = 'Scripts'
subdir = os.path.dirname( file.path_from( waf_source_dir.make_node('waflib') ) )
if subdir != '':
filter_name += '/' + subdir
self.project_filter[file.abspath()] = filter_name
for file in waf_crytek_scripts:
self.project_filter[file.abspath()] = 'Crytek Scripts'
self.source += waf_config_files + waf_spec_files + waf_scripts + waf_crytek_scripts
# without a cpp file, VS wont compile this project
dummy_node = self.ctx.get_bintemp_folder_node().make_node('__waf_compile_dummy__.cpp')
self.project_filter[dummy_node.abspath()] = 'DummyCompileNode'
self.source += [ dummy_node ]
# Waf commands
self.exec_waf_command = [
('show_gui', 'utilities'),
('configure', 'show_option_dialog'),
('generate_uber_files', 'generate_uber_files'),
('generate_solution', 'msvs')
]
for command in self.exec_waf_command:
executable_command = self.ctx.get_bintemp_folder_node().make_node('_waf_' + command[0] + '_.cpp')
self.project_filter[executable_command.abspath()] = '_WAF Commands'
self.waf_command_override_files += [ executable_command ] | [
"def",
"collect_properties",
"(",
"self",
")",
":",
"super",
"(",
"vsnode_build_all",
",",
"self",
")",
".",
"collect_properties",
"(",
")",
"for",
"x",
"in",
"self",
".",
"build_properties",
":",
"x",
".",
"outdir",
"=",
"self",
".",
"path",
".",
"parent",
".",
"abspath",
"(",
")",
"x",
".",
"preprocessor_definitions",
"=",
"''",
"x",
".",
"includes_search_path",
"=",
"''",
"x",
".",
"c_flags",
"=",
"''",
"x",
".",
"cxx_flags",
"=",
"''",
"x",
".",
"link_flags",
"=",
"''",
"x",
".",
"target_spec",
"=",
"''",
"x",
".",
"target_config",
"=",
"''",
"if",
"x",
".",
"platform",
"==",
"'CppCheck'",
":",
"continue",
"waf_spec",
"=",
"self",
".",
"ctx",
".",
"convert_vs_spec_to_waf_spec",
"(",
"x",
".",
"configuration",
")",
"waf_platform",
"=",
"self",
".",
"ctx",
".",
"convert_vs_platform_to_waf_platform",
"(",
"x",
".",
"platform",
")",
"waf_configuration",
"=",
"self",
".",
"ctx",
".",
"convert_vs_configuration_to_waf_configuration",
"(",
"x",
".",
"configuration",
")",
"current_env",
"=",
"self",
".",
"ctx",
".",
"all_envs",
"[",
"waf_platform",
"+",
"'_'",
"+",
"waf_configuration",
"]",
"if",
"waf_platform",
"==",
"'orbis'",
":",
"x",
".",
"platform_toolset",
"=",
"'Clang'",
"x",
".",
"android_platform_target_version",
"=",
"''",
"else",
":",
"x",
".",
"platform_toolset",
"=",
"'v'",
"+",
"str",
"(",
"current_env",
"[",
"'MSVC_VERSION'",
"]",
")",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"if",
"current_env",
"[",
"'MSVC_VERSION'",
"]",
"else",
"\"\"",
"x",
".",
"android_platform_target_version",
"=",
"str",
"(",
"current_env",
"[",
"'ANDROID_TARGET_VERSION'",
"]",
")",
"if",
"current_env",
"[",
"'ANDROID_TARGET_VERSION'",
"]",
"else",
"\"23\"",
"x",
".",
"target_spec",
"=",
"waf_spec",
"x",
".",
"target_config",
"=",
"waf_platform",
"+",
"'_'",
"+",
"waf_configuration",
"# Collect WAF files",
"waf_data_dir",
"=",
"self",
".",
"ctx",
".",
"root",
".",
"make_node",
"(",
"Context",
".",
"launch_dir",
")",
".",
"make_node",
"(",
"'_WAF_'",
")",
"waf_source_dir",
"=",
"self",
".",
"ctx",
".",
"root",
".",
"make_node",
"(",
"Context",
".",
"launch_dir",
")",
".",
"make_node",
"(",
"'Code/Tools/waf-1.7.13'",
")",
"waf_config_files",
"=",
"waf_data_dir",
".",
"ant_glob",
"(",
"'**/*'",
",",
"maxdepth",
"=",
"0",
")",
"waf_spec_files",
"=",
"waf_data_dir",
".",
"make_node",
"(",
"'specs'",
")",
".",
"ant_glob",
"(",
"'**/*'",
")",
"waf_scripts",
"=",
"waf_source_dir",
".",
"make_node",
"(",
"'waflib'",
")",
".",
"ant_glob",
"(",
"'**/*.py'",
")",
"waf_crytek_scripts",
"=",
"waf_source_dir",
".",
"make_node",
"(",
"'crywaflib'",
")",
".",
"ant_glob",
"(",
"'**/*.py'",
")",
"# Remove files found in crywaflib from waf scripts",
"tmp",
"=",
"[",
"]",
"waf_crytek_scripts_files",
"=",
"[",
"]",
"for",
"node",
"in",
"waf_crytek_scripts",
":",
"waf_crytek_scripts_files",
"+=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"node",
".",
"abspath",
"(",
")",
")",
"]",
"for",
"x",
"in",
"waf_scripts",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"x",
".",
"abspath",
"(",
")",
")",
"in",
"waf_crytek_scripts_files",
":",
"continue",
"tmp",
"+=",
"[",
"x",
"]",
"waf_scripts",
"=",
"tmp",
"for",
"file",
"in",
"waf_config_files",
":",
"self",
".",
"project_filter",
"[",
"file",
".",
"abspath",
"(",
")",
"]",
"=",
"'Settings'",
"for",
"file",
"in",
"waf_spec_files",
":",
"self",
".",
"project_filter",
"[",
"file",
".",
"abspath",
"(",
")",
"]",
"=",
"'Specs'",
"for",
"file",
"in",
"waf_scripts",
":",
"filter_name",
"=",
"'Scripts'",
"subdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
".",
"path_from",
"(",
"waf_source_dir",
".",
"make_node",
"(",
"'waflib'",
")",
")",
")",
"if",
"subdir",
"!=",
"''",
":",
"filter_name",
"+=",
"'/'",
"+",
"subdir",
"self",
".",
"project_filter",
"[",
"file",
".",
"abspath",
"(",
")",
"]",
"=",
"filter_name",
"for",
"file",
"in",
"waf_crytek_scripts",
":",
"self",
".",
"project_filter",
"[",
"file",
".",
"abspath",
"(",
")",
"]",
"=",
"'Crytek Scripts'",
"self",
".",
"source",
"+=",
"waf_config_files",
"+",
"waf_spec_files",
"+",
"waf_scripts",
"+",
"waf_crytek_scripts",
"# without a cpp file, VS wont compile this project",
"dummy_node",
"=",
"self",
".",
"ctx",
".",
"get_bintemp_folder_node",
"(",
")",
".",
"make_node",
"(",
"'__waf_compile_dummy__.cpp'",
")",
"self",
".",
"project_filter",
"[",
"dummy_node",
".",
"abspath",
"(",
")",
"]",
"=",
"'DummyCompileNode'",
"self",
".",
"source",
"+=",
"[",
"dummy_node",
"]",
"# Waf commands\t\t",
"self",
".",
"exec_waf_command",
"=",
"[",
"(",
"'show_gui'",
",",
"'utilities'",
")",
",",
"(",
"'configure'",
",",
"'show_option_dialog'",
")",
",",
"(",
"'generate_uber_files'",
",",
"'generate_uber_files'",
")",
",",
"(",
"'generate_solution'",
",",
"'msvs'",
")",
"]",
"for",
"command",
"in",
"self",
".",
"exec_waf_command",
":",
"executable_command",
"=",
"self",
".",
"ctx",
".",
"get_bintemp_folder_node",
"(",
")",
".",
"make_node",
"(",
"'_waf_'",
"+",
"command",
"[",
"0",
"]",
"+",
"'_.cpp'",
")",
"self",
".",
"project_filter",
"[",
"executable_command",
".",
"abspath",
"(",
")",
"]",
"=",
"'_WAF Commands'",
"self",
".",
"waf_command_override_files",
"+=",
"[",
"executable_command",
"]"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/msvs.py#L1161-L1250 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/managers.py | python | AutoProxy | (token, serializer, manager=None, authkey=None,
exposed=None, incref=True) | return proxy | Return an auto-proxy for `token` | Return an auto-proxy for `token` | [
"Return",
"an",
"auto",
"-",
"proxy",
"for",
"token"
] | def AutoProxy(token, serializer, manager=None, authkey=None,
exposed=None, incref=True):
'''
Return an auto-proxy for `token`
'''
_Client = listener_client[serializer][1]
if exposed is None:
conn = _Client(token.address, authkey=authkey)
try:
exposed = dispatch(conn, None, 'get_methods', (token,))
finally:
conn.close()
if authkey is None and manager is not None:
authkey = manager._authkey
if authkey is None:
authkey = current_process().authkey
ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed)
proxy = ProxyType(token, serializer, manager=manager, authkey=authkey,
incref=incref)
proxy._isauto = True
return proxy | [
"def",
"AutoProxy",
"(",
"token",
",",
"serializer",
",",
"manager",
"=",
"None",
",",
"authkey",
"=",
"None",
",",
"exposed",
"=",
"None",
",",
"incref",
"=",
"True",
")",
":",
"_Client",
"=",
"listener_client",
"[",
"serializer",
"]",
"[",
"1",
"]",
"if",
"exposed",
"is",
"None",
":",
"conn",
"=",
"_Client",
"(",
"token",
".",
"address",
",",
"authkey",
"=",
"authkey",
")",
"try",
":",
"exposed",
"=",
"dispatch",
"(",
"conn",
",",
"None",
",",
"'get_methods'",
",",
"(",
"token",
",",
")",
")",
"finally",
":",
"conn",
".",
"close",
"(",
")",
"if",
"authkey",
"is",
"None",
"and",
"manager",
"is",
"not",
"None",
":",
"authkey",
"=",
"manager",
".",
"_authkey",
"if",
"authkey",
"is",
"None",
":",
"authkey",
"=",
"current_process",
"(",
")",
".",
"authkey",
"ProxyType",
"=",
"MakeProxyType",
"(",
"'AutoProxy[%s]'",
"%",
"token",
".",
"typeid",
",",
"exposed",
")",
"proxy",
"=",
"ProxyType",
"(",
"token",
",",
"serializer",
",",
"manager",
"=",
"manager",
",",
"authkey",
"=",
"authkey",
",",
"incref",
"=",
"incref",
")",
"proxy",
".",
"_isauto",
"=",
"True",
"return",
"proxy"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/managers.py#L906-L929 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/util/mac/keychain_helper.py | python | IsKeychainLocked | () | return child.returncode != 0 | Returns True if the keychain is locked, or if there is an error determining
the keychain state. | Returns True if the keychain is locked, or if there is an error determining
the keychain state. | [
"Returns",
"True",
"if",
"the",
"keychain",
"is",
"locked",
"or",
"if",
"there",
"is",
"an",
"error",
"determining",
"the",
"keychain",
"state",
"."
] | def IsKeychainLocked():
"""
Returns True if the keychain is locked, or if there is an error determining
the keychain state.
"""
path = _PathForExecutable('determine_if_keychain_is_locked')
child = subprocess.Popen(path, stdout=subprocess.PIPE)
child.communicate()
return child.returncode != 0 | [
"def",
"IsKeychainLocked",
"(",
")",
":",
"path",
"=",
"_PathForExecutable",
"(",
"'determine_if_keychain_is_locked'",
")",
"child",
"=",
"subprocess",
".",
"Popen",
"(",
"path",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"child",
".",
"communicate",
"(",
")",
"return",
"child",
".",
"returncode",
"!=",
"0"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/util/mac/keychain_helper.py#L16-L25 | |
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/python/framework/errors.py | python | OpError.__init__ | (self, node_def, op, message, error_code) | Creates a new `OpError` indicating that a particular op failed.
Args:
node_def: The `graph_pb2.NodeDef` proto representing the op that failed,
if known; otherwise None.
op: The `ops.Operation` that failed, if known; otherwise None.
message: The message string describing the failure.
error_code: The `error_codes_pb2.Code` describing the error. | Creates a new `OpError` indicating that a particular op failed. | [
"Creates",
"a",
"new",
"OpError",
"indicating",
"that",
"a",
"particular",
"op",
"failed",
"."
] | def __init__(self, node_def, op, message, error_code):
"""Creates a new `OpError` indicating that a particular op failed.
Args:
node_def: The `graph_pb2.NodeDef` proto representing the op that failed,
if known; otherwise None.
op: The `ops.Operation` that failed, if known; otherwise None.
message: The message string describing the failure.
error_code: The `error_codes_pb2.Code` describing the error.
"""
super(OpError, self).__init__()
self._message = message
self._node_def = node_def
self._op = op
self._error_code = error_code | [
"def",
"__init__",
"(",
"self",
",",
"node_def",
",",
"op",
",",
"message",
",",
"error_code",
")",
":",
"super",
"(",
"OpError",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_message",
"=",
"message",
"self",
".",
"_node_def",
"=",
"node_def",
"self",
".",
"_op",
"=",
"op",
"self",
".",
"_error_code",
"=",
"error_code"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/errors.py#L40-L54 | ||
google/omaha | 61e8c2833fd69c9a13978400108e5b9ebff24a09 | omaha/omaha_version_utils.py | python | OmahaVersionInfo.__init__ | (self, version_file) | Initializes the class based on data from a VERSION file. | Initializes the class based on data from a VERSION file. | [
"Initializes",
"the",
"class",
"based",
"on",
"data",
"from",
"a",
"VERSION",
"file",
"."
] | def __init__(self, version_file):
"""Initializes the class based on data from a VERSION file."""
self._ReadFile(version_file)
self.filename_prefix = '' | [
"def",
"__init__",
"(",
"self",
",",
"version_file",
")",
":",
"self",
".",
"_ReadFile",
"(",
"version_file",
")",
"self",
".",
"filename_prefix",
"=",
"''"
] | https://github.com/google/omaha/blob/61e8c2833fd69c9a13978400108e5b9ebff24a09/omaha/omaha_version_utils.py#L242-L246 | ||
mysql/mysql-router | cc0179f982bb9739a834eb6fd205a56224616133 | ext/gmock/scripts/gmock_doctor.py | python | _NeedToUseReturnNullDiagnoser | (msg) | return _GenericDiagnoser(
'NRNULL', 'Need to use ReturnNull',
[(clang_regex, diagnosis),
(gcc_regex, diagnosis % {'type': 'the right type'})],
msg) | Diagnoses the NRNULL disease, given the error messages by the compiler. | Diagnoses the NRNULL disease, given the error messages by the compiler. | [
"Diagnoses",
"the",
"NRNULL",
"disease",
"given",
"the",
"error",
"messages",
"by",
"the",
"compiler",
"."
] | def _NeedToUseReturnNullDiagnoser(msg):
"""Diagnoses the NRNULL disease, given the error messages by the compiler."""
gcc_regex = ('instantiated from \'testing::internal::ReturnAction<R>'
'::operator testing::Action<Func>\(\) const.*\n' +
_GCC_FILE_LINE_RE + r'instantiated from here\n'
r'.*error: no matching function for call to \'ImplicitCast_\('
r'(:?long )?int&\)')
clang_regex = (r'\bgmock-actions.h:.* error: no matching function for '
r'call to \'ImplicitCast_\'\r?\n'
r'(.*\n)*?' +
_CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
r'of function template specialization '
r'\'testing::internal::ReturnAction<(int|long)>::operator '
r'Action<(?P<type>.*)\(\)>\' requested here')
diagnosis = """
You are probably calling Return(NULL) and the compiler isn't sure how to turn
NULL into %(type)s. Use ReturnNull() instead.
Note: the line number may be off; please fix all instances of Return(NULL)."""
return _GenericDiagnoser(
'NRNULL', 'Need to use ReturnNull',
[(clang_regex, diagnosis),
(gcc_regex, diagnosis % {'type': 'the right type'})],
msg) | [
"def",
"_NeedToUseReturnNullDiagnoser",
"(",
"msg",
")",
":",
"gcc_regex",
"=",
"(",
"'instantiated from \\'testing::internal::ReturnAction<R>'",
"'::operator testing::Action<Func>\\(\\) const.*\\n'",
"+",
"_GCC_FILE_LINE_RE",
"+",
"r'instantiated from here\\n'",
"r'.*error: no matching function for call to \\'ImplicitCast_\\('",
"r'(:?long )?int&\\)'",
")",
"clang_regex",
"=",
"(",
"r'\\bgmock-actions.h:.* error: no matching function for '",
"r'call to \\'ImplicitCast_\\'\\r?\\n'",
"r'(.*\\n)*?'",
"+",
"_CLANG_NON_GMOCK_FILE_LINE_RE",
"+",
"r'note: in instantiation '",
"r'of function template specialization '",
"r'\\'testing::internal::ReturnAction<(int|long)>::operator '",
"r'Action<(?P<type>.*)\\(\\)>\\' requested here'",
")",
"diagnosis",
"=",
"\"\"\"\nYou are probably calling Return(NULL) and the compiler isn't sure how to turn\nNULL into %(type)s. Use ReturnNull() instead.\nNote: the line number may be off; please fix all instances of Return(NULL).\"\"\"",
"return",
"_GenericDiagnoser",
"(",
"'NRNULL'",
",",
"'Need to use ReturnNull'",
",",
"[",
"(",
"clang_regex",
",",
"diagnosis",
")",
",",
"(",
"gcc_regex",
",",
"diagnosis",
"%",
"{",
"'type'",
":",
"'the right type'",
"}",
")",
"]",
",",
"msg",
")"
] | https://github.com/mysql/mysql-router/blob/cc0179f982bb9739a834eb6fd205a56224616133/ext/gmock/scripts/gmock_doctor.py#L412-L435 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exomerge3.py | python | ExodusModel._partition_triangle_block_from_node_field | (self, element_block_id,
new_element_block_id,
node_field_name, timestep,
interval_list) | Subdivide a 'tri3' element block based on the given field intervals.
The target element block will have a element field named 'interval'
corresponding to the given interval the element falls into.
This is a helper function for generating nice looking WRL files. | Subdivide a 'tri3' element block based on the given field intervals. | [
"Subdivide",
"a",
"tri3",
"element",
"block",
"based",
"on",
"the",
"given",
"field",
"intervals",
"."
] | def _partition_triangle_block_from_node_field(self, element_block_id,
new_element_block_id,
node_field_name, timestep,
interval_list):
"""
Subdivide a 'tri3' element block based on the given field intervals.
The target element block will have a element field named 'interval'
corresponding to the given interval the element falls into.
This is a helper function for generating nice looking WRL files.
"""
[element_block_id] = self._format_element_block_id_list(
[element_block_id], single=True)
[node_field_name] = self._format_id_list([node_field_name],
self.get_node_field_names(),
'node field',
single=True)
[timestep] = self._format_id_list([timestep],
self.get_timesteps(),
'timestep',
single=True)
# verify block is actually a tri3 block
if self._get_element_type(element_block_id) != 'tri3':
self._error(
'Invalid element type',
'This function can only be used to divide element '
'blocks composed of "tri3" elements.')
timestep_index = self.timesteps.index(timestep)
connectivity = self.get_connectivity(element_block_id)
element_count = self.get_element_count(element_block_id)
new_connectivity = []
element_interval_values = []
triangles = [
tuple(connectivity[x * 3:(x + 1) * 3])
for x in range(element_count)
]
for index, upper_bound in enumerate(interval_list):
# hold new vertices we have to create
# edge = (x, y)
# new_vertex[edge] = mid_edge_vertex_index
# we do this to keep the mesh watertight
new_vertex = dict()
new_nodes = []
next_node_index = len(self.nodes)
values = self.node_fields[node_field_name][timestep_index]
for tri in triangles:
for d in range(3):
d2 = (d + 1) % 3
edge = (tri[d], tri[d2])
if (self._sign(values[tri[d]] - upper_bound) *
self._sign(values[tri[d2]] - upper_bound) == -1):
if edge not in new_vertex:
opposite_edge = tuple(reversed(edge))
new_vertex[edge] = next_node_index
new_vertex[opposite_edge] = next_node_index
next_node_index += 1
phi = (upper_bound - values[tri[d]]) / (
values[tri[d2]] - values[tri[d]])
new_node = ((tri[d], 1.0 - phi), (tri[d2], phi))
new_nodes.append(new_node)
self._create_averaged_nodes(new_nodes, [])
# now form new triangles
new_triangles = []
this_partition = []
values = self.node_fields[node_field_name][timestep_index]
for tri in triangles:
if (values[tri[0]] <= upper_bound
and values[tri[1]] <= upper_bound
and values[tri[2]] <= upper_bound):
this_partition.append(tri)
elif (values[tri[0]] >= upper_bound
and values[tri[1]] >= upper_bound
and values[tri[2]] >= upper_bound):
new_triangles.append(tri)
else:
# find vertex below the bound
d = 0
while (values[tri[d]] >= upper_bound
or values[tri[(d + 1) % 3]] < upper_bound):
d += 1
tri = tuple(tri[(d + x) % 3] for x in range(3))
case = tuple(
self._sign(values[tri[x]] - upper_bound)
for x in range(3))
if case == (-1, 1, -1):
m1 = new_vertex[(tri[0], tri[1])]
m2 = new_vertex[(tri[1], tri[2])]
# below triangles
this_partition.append((tri[0], m1, tri[2]))
this_partition.append((m1, m2, tri[2]))
# above triangles
new_triangles.append((m1, tri[1], m2))
elif case == (-1, 1, 1):
m1 = new_vertex[(tri[0], tri[1])]
m2 = new_vertex[(tri[2], tri[0])]
# below triangles
this_partition.append((tri[0], m1, m2))
# above triangles
new_triangles.append((m1, tri[1], m2))
new_triangles.append((tri[1], tri[2], m2))
elif case == (-1, 0, 1):
m1 = new_vertex[(tri[2], tri[0])]
# below triangles
this_partition.append((tri[0], tri[1], m1))
# above triangles
new_triangles.append((tri[1], tri[2], m1))
elif case == (-1, 1, 0):
m1 = new_vertex[(tri[0], tri[1])]
# below triangles
this_partition.append((tri[0], m1, tri[2]))
# above triangles
new_triangles.append((m1, tri[1], tri[2]))
else:
self._bug('Unknown case')
triangles = new_triangles
new_connectivity.extend(itertools.chain(*this_partition))
element_interval_values.extend([float(index)] *
len(this_partition))
# add rest of triangle to last partition
new_connectivity.extend(itertools.chain(*triangles))
element_interval_values.extend([float(len(interval_list))] *
len(triangles))
self.create_element_block(
new_element_block_id,
['tri3', len(new_connectivity) // 3, 3, 0], new_connectivity)
self.create_element_field('interval', new_element_block_id, 0.0)
fields = self._get_element_block_fields(new_element_block_id)
field = fields['interval']
for index in range(len(self.timesteps)):
field[index] = list(element_interval_values) | [
"def",
"_partition_triangle_block_from_node_field",
"(",
"self",
",",
"element_block_id",
",",
"new_element_block_id",
",",
"node_field_name",
",",
"timestep",
",",
"interval_list",
")",
":",
"[",
"element_block_id",
"]",
"=",
"self",
".",
"_format_element_block_id_list",
"(",
"[",
"element_block_id",
"]",
",",
"single",
"=",
"True",
")",
"[",
"node_field_name",
"]",
"=",
"self",
".",
"_format_id_list",
"(",
"[",
"node_field_name",
"]",
",",
"self",
".",
"get_node_field_names",
"(",
")",
",",
"'node field'",
",",
"single",
"=",
"True",
")",
"[",
"timestep",
"]",
"=",
"self",
".",
"_format_id_list",
"(",
"[",
"timestep",
"]",
",",
"self",
".",
"get_timesteps",
"(",
")",
",",
"'timestep'",
",",
"single",
"=",
"True",
")",
"# verify block is actually a tri3 block",
"if",
"self",
".",
"_get_element_type",
"(",
"element_block_id",
")",
"!=",
"'tri3'",
":",
"self",
".",
"_error",
"(",
"'Invalid element type'",
",",
"'This function can only be used to divide element '",
"'blocks composed of \"tri3\" elements.'",
")",
"timestep_index",
"=",
"self",
".",
"timesteps",
".",
"index",
"(",
"timestep",
")",
"connectivity",
"=",
"self",
".",
"get_connectivity",
"(",
"element_block_id",
")",
"element_count",
"=",
"self",
".",
"get_element_count",
"(",
"element_block_id",
")",
"new_connectivity",
"=",
"[",
"]",
"element_interval_values",
"=",
"[",
"]",
"triangles",
"=",
"[",
"tuple",
"(",
"connectivity",
"[",
"x",
"*",
"3",
":",
"(",
"x",
"+",
"1",
")",
"*",
"3",
"]",
")",
"for",
"x",
"in",
"range",
"(",
"element_count",
")",
"]",
"for",
"index",
",",
"upper_bound",
"in",
"enumerate",
"(",
"interval_list",
")",
":",
"# hold new vertices we have to create",
"# edge = (x, y)",
"# new_vertex[edge] = mid_edge_vertex_index",
"# we do this to keep the mesh watertight",
"new_vertex",
"=",
"dict",
"(",
")",
"new_nodes",
"=",
"[",
"]",
"next_node_index",
"=",
"len",
"(",
"self",
".",
"nodes",
")",
"values",
"=",
"self",
".",
"node_fields",
"[",
"node_field_name",
"]",
"[",
"timestep_index",
"]",
"for",
"tri",
"in",
"triangles",
":",
"for",
"d",
"in",
"range",
"(",
"3",
")",
":",
"d2",
"=",
"(",
"d",
"+",
"1",
")",
"%",
"3",
"edge",
"=",
"(",
"tri",
"[",
"d",
"]",
",",
"tri",
"[",
"d2",
"]",
")",
"if",
"(",
"self",
".",
"_sign",
"(",
"values",
"[",
"tri",
"[",
"d",
"]",
"]",
"-",
"upper_bound",
")",
"*",
"self",
".",
"_sign",
"(",
"values",
"[",
"tri",
"[",
"d2",
"]",
"]",
"-",
"upper_bound",
")",
"==",
"-",
"1",
")",
":",
"if",
"edge",
"not",
"in",
"new_vertex",
":",
"opposite_edge",
"=",
"tuple",
"(",
"reversed",
"(",
"edge",
")",
")",
"new_vertex",
"[",
"edge",
"]",
"=",
"next_node_index",
"new_vertex",
"[",
"opposite_edge",
"]",
"=",
"next_node_index",
"next_node_index",
"+=",
"1",
"phi",
"=",
"(",
"upper_bound",
"-",
"values",
"[",
"tri",
"[",
"d",
"]",
"]",
")",
"/",
"(",
"values",
"[",
"tri",
"[",
"d2",
"]",
"]",
"-",
"values",
"[",
"tri",
"[",
"d",
"]",
"]",
")",
"new_node",
"=",
"(",
"(",
"tri",
"[",
"d",
"]",
",",
"1.0",
"-",
"phi",
")",
",",
"(",
"tri",
"[",
"d2",
"]",
",",
"phi",
")",
")",
"new_nodes",
".",
"append",
"(",
"new_node",
")",
"self",
".",
"_create_averaged_nodes",
"(",
"new_nodes",
",",
"[",
"]",
")",
"# now form new triangles",
"new_triangles",
"=",
"[",
"]",
"this_partition",
"=",
"[",
"]",
"values",
"=",
"self",
".",
"node_fields",
"[",
"node_field_name",
"]",
"[",
"timestep_index",
"]",
"for",
"tri",
"in",
"triangles",
":",
"if",
"(",
"values",
"[",
"tri",
"[",
"0",
"]",
"]",
"<=",
"upper_bound",
"and",
"values",
"[",
"tri",
"[",
"1",
"]",
"]",
"<=",
"upper_bound",
"and",
"values",
"[",
"tri",
"[",
"2",
"]",
"]",
"<=",
"upper_bound",
")",
":",
"this_partition",
".",
"append",
"(",
"tri",
")",
"elif",
"(",
"values",
"[",
"tri",
"[",
"0",
"]",
"]",
">=",
"upper_bound",
"and",
"values",
"[",
"tri",
"[",
"1",
"]",
"]",
">=",
"upper_bound",
"and",
"values",
"[",
"tri",
"[",
"2",
"]",
"]",
">=",
"upper_bound",
")",
":",
"new_triangles",
".",
"append",
"(",
"tri",
")",
"else",
":",
"# find vertex below the bound",
"d",
"=",
"0",
"while",
"(",
"values",
"[",
"tri",
"[",
"d",
"]",
"]",
">=",
"upper_bound",
"or",
"values",
"[",
"tri",
"[",
"(",
"d",
"+",
"1",
")",
"%",
"3",
"]",
"]",
"<",
"upper_bound",
")",
":",
"d",
"+=",
"1",
"tri",
"=",
"tuple",
"(",
"tri",
"[",
"(",
"d",
"+",
"x",
")",
"%",
"3",
"]",
"for",
"x",
"in",
"range",
"(",
"3",
")",
")",
"case",
"=",
"tuple",
"(",
"self",
".",
"_sign",
"(",
"values",
"[",
"tri",
"[",
"x",
"]",
"]",
"-",
"upper_bound",
")",
"for",
"x",
"in",
"range",
"(",
"3",
")",
")",
"if",
"case",
"==",
"(",
"-",
"1",
",",
"1",
",",
"-",
"1",
")",
":",
"m1",
"=",
"new_vertex",
"[",
"(",
"tri",
"[",
"0",
"]",
",",
"tri",
"[",
"1",
"]",
")",
"]",
"m2",
"=",
"new_vertex",
"[",
"(",
"tri",
"[",
"1",
"]",
",",
"tri",
"[",
"2",
"]",
")",
"]",
"# below triangles",
"this_partition",
".",
"append",
"(",
"(",
"tri",
"[",
"0",
"]",
",",
"m1",
",",
"tri",
"[",
"2",
"]",
")",
")",
"this_partition",
".",
"append",
"(",
"(",
"m1",
",",
"m2",
",",
"tri",
"[",
"2",
"]",
")",
")",
"# above triangles",
"new_triangles",
".",
"append",
"(",
"(",
"m1",
",",
"tri",
"[",
"1",
"]",
",",
"m2",
")",
")",
"elif",
"case",
"==",
"(",
"-",
"1",
",",
"1",
",",
"1",
")",
":",
"m1",
"=",
"new_vertex",
"[",
"(",
"tri",
"[",
"0",
"]",
",",
"tri",
"[",
"1",
"]",
")",
"]",
"m2",
"=",
"new_vertex",
"[",
"(",
"tri",
"[",
"2",
"]",
",",
"tri",
"[",
"0",
"]",
")",
"]",
"# below triangles",
"this_partition",
".",
"append",
"(",
"(",
"tri",
"[",
"0",
"]",
",",
"m1",
",",
"m2",
")",
")",
"# above triangles",
"new_triangles",
".",
"append",
"(",
"(",
"m1",
",",
"tri",
"[",
"1",
"]",
",",
"m2",
")",
")",
"new_triangles",
".",
"append",
"(",
"(",
"tri",
"[",
"1",
"]",
",",
"tri",
"[",
"2",
"]",
",",
"m2",
")",
")",
"elif",
"case",
"==",
"(",
"-",
"1",
",",
"0",
",",
"1",
")",
":",
"m1",
"=",
"new_vertex",
"[",
"(",
"tri",
"[",
"2",
"]",
",",
"tri",
"[",
"0",
"]",
")",
"]",
"# below triangles",
"this_partition",
".",
"append",
"(",
"(",
"tri",
"[",
"0",
"]",
",",
"tri",
"[",
"1",
"]",
",",
"m1",
")",
")",
"# above triangles",
"new_triangles",
".",
"append",
"(",
"(",
"tri",
"[",
"1",
"]",
",",
"tri",
"[",
"2",
"]",
",",
"m1",
")",
")",
"elif",
"case",
"==",
"(",
"-",
"1",
",",
"1",
",",
"0",
")",
":",
"m1",
"=",
"new_vertex",
"[",
"(",
"tri",
"[",
"0",
"]",
",",
"tri",
"[",
"1",
"]",
")",
"]",
"# below triangles",
"this_partition",
".",
"append",
"(",
"(",
"tri",
"[",
"0",
"]",
",",
"m1",
",",
"tri",
"[",
"2",
"]",
")",
")",
"# above triangles",
"new_triangles",
".",
"append",
"(",
"(",
"m1",
",",
"tri",
"[",
"1",
"]",
",",
"tri",
"[",
"2",
"]",
")",
")",
"else",
":",
"self",
".",
"_bug",
"(",
"'Unknown case'",
")",
"triangles",
"=",
"new_triangles",
"new_connectivity",
".",
"extend",
"(",
"itertools",
".",
"chain",
"(",
"*",
"this_partition",
")",
")",
"element_interval_values",
".",
"extend",
"(",
"[",
"float",
"(",
"index",
")",
"]",
"*",
"len",
"(",
"this_partition",
")",
")",
"# add rest of triangle to last partition",
"new_connectivity",
".",
"extend",
"(",
"itertools",
".",
"chain",
"(",
"*",
"triangles",
")",
")",
"element_interval_values",
".",
"extend",
"(",
"[",
"float",
"(",
"len",
"(",
"interval_list",
")",
")",
"]",
"*",
"len",
"(",
"triangles",
")",
")",
"self",
".",
"create_element_block",
"(",
"new_element_block_id",
",",
"[",
"'tri3'",
",",
"len",
"(",
"new_connectivity",
")",
"//",
"3",
",",
"3",
",",
"0",
"]",
",",
"new_connectivity",
")",
"self",
".",
"create_element_field",
"(",
"'interval'",
",",
"new_element_block_id",
",",
"0.0",
")",
"fields",
"=",
"self",
".",
"_get_element_block_fields",
"(",
"new_element_block_id",
")",
"field",
"=",
"fields",
"[",
"'interval'",
"]",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"timesteps",
")",
")",
":",
"field",
"[",
"index",
"]",
"=",
"list",
"(",
"element_interval_values",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge3.py#L1478-L1609 | ||
netket/netket | 0d534e54ecbf25b677ea72af6b85947979420652 | netket/graph/lattice.py | python | Lattice.basis_coords | (self) | return self._basis_coords | basis coordinates of all lattice sites | basis coordinates of all lattice sites | [
"basis",
"coordinates",
"of",
"all",
"lattice",
"sites"
] | def basis_coords(self) -> CoordT:
"""basis coordinates of all lattice sites"""
return self._basis_coords | [
"def",
"basis_coords",
"(",
"self",
")",
"->",
"CoordT",
":",
"return",
"self",
".",
"_basis_coords"
] | https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/graph/lattice.py#L429-L431 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/nn/functional.py | python | unfold | (
input: Tensor, kernel_size: BroadcastingList2[int],
dilation: BroadcastingList2[int] = 1,
padding: BroadcastingList2[int] = 0,
stride: BroadcastingList2[int] = 1
) | r"""Extracts sliding local blocks from a batched input tensor.
.. warning::
Currently, only 4-D input tensors (batched image-like tensors) are
supported.
.. warning::
More than one element of the unfolded tensor may refer to a single
memory location. As a result, in-place operations (especially ones that
are vectorized) may result in incorrect behavior. If you need to write
to the tensor, please clone it first.
See :class:`torch.nn.Unfold` for details | r"""Extracts sliding local blocks from a batched input tensor. | [
"r",
"Extracts",
"sliding",
"local",
"blocks",
"from",
"a",
"batched",
"input",
"tensor",
"."
] | def unfold(
input: Tensor, kernel_size: BroadcastingList2[int],
dilation: BroadcastingList2[int] = 1,
padding: BroadcastingList2[int] = 0,
stride: BroadcastingList2[int] = 1
) -> Tensor:
r"""Extracts sliding local blocks from a batched input tensor.
.. warning::
Currently, only 4-D input tensors (batched image-like tensors) are
supported.
.. warning::
More than one element of the unfolded tensor may refer to a single
memory location. As a result, in-place operations (especially ones that
are vectorized) may result in incorrect behavior. If you need to write
to the tensor, please clone it first.
See :class:`torch.nn.Unfold` for details
"""
if has_torch_function_unary(input):
return handle_torch_function(
unfold, (input,), input, kernel_size, dilation=dilation, padding=padding, stride=stride
)
if input.dim() == 4:
msg = "{} must be int or 2-tuple for 4D input"
assert_int_or_pair(kernel_size, "kernel_size", msg)
assert_int_or_pair(dilation, "dilation", msg)
assert_int_or_pair(padding, "padding", msg)
assert_int_or_pair(stride, "stride", msg)
return torch._C._nn.im2col(input, _pair(kernel_size), _pair(dilation), _pair(padding), _pair(stride))
else:
raise NotImplementedError("Input Error: Only 4D input Tensors are supported (got {}D)".format(input.dim())) | [
"def",
"unfold",
"(",
"input",
":",
"Tensor",
",",
"kernel_size",
":",
"BroadcastingList2",
"[",
"int",
"]",
",",
"dilation",
":",
"BroadcastingList2",
"[",
"int",
"]",
"=",
"1",
",",
"padding",
":",
"BroadcastingList2",
"[",
"int",
"]",
"=",
"0",
",",
"stride",
":",
"BroadcastingList2",
"[",
"int",
"]",
"=",
"1",
")",
"->",
"Tensor",
":",
"if",
"has_torch_function_unary",
"(",
"input",
")",
":",
"return",
"handle_torch_function",
"(",
"unfold",
",",
"(",
"input",
",",
")",
",",
"input",
",",
"kernel_size",
",",
"dilation",
"=",
"dilation",
",",
"padding",
"=",
"padding",
",",
"stride",
"=",
"stride",
")",
"if",
"input",
".",
"dim",
"(",
")",
"==",
"4",
":",
"msg",
"=",
"\"{} must be int or 2-tuple for 4D input\"",
"assert_int_or_pair",
"(",
"kernel_size",
",",
"\"kernel_size\"",
",",
"msg",
")",
"assert_int_or_pair",
"(",
"dilation",
",",
"\"dilation\"",
",",
"msg",
")",
"assert_int_or_pair",
"(",
"padding",
",",
"\"padding\"",
",",
"msg",
")",
"assert_int_or_pair",
"(",
"stride",
",",
"\"stride\"",
",",
"msg",
")",
"return",
"torch",
".",
"_C",
".",
"_nn",
".",
"im2col",
"(",
"input",
",",
"_pair",
"(",
"kernel_size",
")",
",",
"_pair",
"(",
"dilation",
")",
",",
"_pair",
"(",
"padding",
")",
",",
"_pair",
"(",
"stride",
")",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"Input Error: Only 4D input Tensors are supported (got {}D)\"",
".",
"format",
"(",
"input",
".",
"dim",
"(",
")",
")",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/nn/functional.py#L4605-L4640 | ||
JiayinCao/SORT | 457b75cba7d8ed5bf834b0ec38be26b249a5372c | blender-plugin/addons/sortblend/exporter.py | python | depsgraph_objects | (depsgraph: bpy.types.Depsgraph) | Iterates evaluated objects in depsgraph with ITERATED_OBJECT_TYPES | Iterates evaluated objects in depsgraph with ITERATED_OBJECT_TYPES | [
"Iterates",
"evaluated",
"objects",
"in",
"depsgraph",
"with",
"ITERATED_OBJECT_TYPES"
] | def depsgraph_objects(depsgraph: bpy.types.Depsgraph):
""" Iterates evaluated objects in depsgraph with ITERATED_OBJECT_TYPES """
ITERATED_OBJECT_TYPES = ('MESH', 'LIGHT')
for obj in depsgraph.objects:
if obj.type in ITERATED_OBJECT_TYPES:
yield obj.evaluated_get(depsgraph) | [
"def",
"depsgraph_objects",
"(",
"depsgraph",
":",
"bpy",
".",
"types",
".",
"Depsgraph",
")",
":",
"ITERATED_OBJECT_TYPES",
"=",
"(",
"'MESH'",
",",
"'LIGHT'",
")",
"for",
"obj",
"in",
"depsgraph",
".",
"objects",
":",
"if",
"obj",
".",
"type",
"in",
"ITERATED_OBJECT_TYPES",
":",
"yield",
"obj",
".",
"evaluated_get",
"(",
"depsgraph",
")"
] | https://github.com/JiayinCao/SORT/blob/457b75cba7d8ed5bf834b0ec38be26b249a5372c/blender-plugin/addons/sortblend/exporter.py#L31-L36 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/imputils.py | python | Registry.lower_getattr_generic | (self, ty) | return self.lower_getattr(ty, None) | Decorate the fallback implementation of __getattr__ for type *ty*.
The decorated implementation will have the signature
(context, builder, typ, val, attr). The implementation is
called for attributes which haven't been explicitly registered
with lower_getattr(). | Decorate the fallback implementation of __getattr__ for type *ty*. | [
"Decorate",
"the",
"fallback",
"implementation",
"of",
"__getattr__",
"for",
"type",
"*",
"ty",
"*",
"."
] | def lower_getattr_generic(self, ty):
"""
Decorate the fallback implementation of __getattr__ for type *ty*.
The decorated implementation will have the signature
(context, builder, typ, val, attr). The implementation is
called for attributes which haven't been explicitly registered
with lower_getattr().
"""
return self.lower_getattr(ty, None) | [
"def",
"lower_getattr_generic",
"(",
"self",
",",
"ty",
")",
":",
"return",
"self",
".",
"lower_getattr",
"(",
"ty",
",",
"None",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/imputils.py#L60-L69 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pyio.py | python | TextIOBase.detach | (self) | Separate the underlying buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIO is in an
unusable state. | Separate the underlying buffer from the TextIOBase and return it. | [
"Separate",
"the",
"underlying",
"buffer",
"from",
"the",
"TextIOBase",
"and",
"return",
"it",
"."
] | def detach(self):
"""
Separate the underlying buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIO is in an
unusable state.
"""
self._unsupported("detach") | [
"def",
"detach",
"(",
"self",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"detach\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pyio.py#L1803-L1810 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py | python | TarFile.bz2open | (cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs) | return t | Open bzip2 compressed tar archive name for reading or writing.
Appending is not allowed. | Open bzip2 compressed tar archive name for reading or writing.
Appending is not allowed. | [
"Open",
"bzip2",
"compressed",
"tar",
"archive",
"name",
"for",
"reading",
"or",
"writing",
".",
"Appending",
"is",
"not",
"allowed",
"."
] | def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
"""Open bzip2 compressed tar archive name for reading or writing.
Appending is not allowed.
"""
if len(mode) > 1 or mode not in "rw":
raise ValueError("mode must be 'r' or 'w'.")
try:
import bz2
except ImportError:
raise CompressionError("bz2 module is not available")
if fileobj is not None:
fileobj = _BZ2Proxy(fileobj, mode)
else:
fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
except (IOError, EOFError):
fileobj.close()
raise ReadError("not a bzip2 file")
t._extfileobj = False
return t | [
"def",
"bz2open",
"(",
"cls",
",",
"name",
",",
"mode",
"=",
"\"r\"",
",",
"fileobj",
"=",
"None",
",",
"compresslevel",
"=",
"9",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"mode",
")",
">",
"1",
"or",
"mode",
"not",
"in",
"\"rw\"",
":",
"raise",
"ValueError",
"(",
"\"mode must be 'r' or 'w'.\"",
")",
"try",
":",
"import",
"bz2",
"except",
"ImportError",
":",
"raise",
"CompressionError",
"(",
"\"bz2 module is not available\"",
")",
"if",
"fileobj",
"is",
"not",
"None",
":",
"fileobj",
"=",
"_BZ2Proxy",
"(",
"fileobj",
",",
"mode",
")",
"else",
":",
"fileobj",
"=",
"bz2",
".",
"BZ2File",
"(",
"name",
",",
"mode",
",",
"compresslevel",
"=",
"compresslevel",
")",
"try",
":",
"t",
"=",
"cls",
".",
"taropen",
"(",
"name",
",",
"mode",
",",
"fileobj",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"IOError",
",",
"EOFError",
")",
":",
"fileobj",
".",
"close",
"(",
")",
"raise",
"ReadError",
"(",
"\"not a bzip2 file\"",
")",
"t",
".",
"_extfileobj",
"=",
"False",
"return",
"t"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py#L1829-L1852 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/process/plugins.py | python | ThreadManager.stop | (self) | Release all threads and run all 'stop_thread' listeners. | Release all threads and run all 'stop_thread' listeners. | [
"Release",
"all",
"threads",
"and",
"run",
"all",
"stop_thread",
"listeners",
"."
] | def stop(self):
"""Release all threads and run all 'stop_thread' listeners."""
for thread_ident, i in self.threads.items():
self.bus.publish('stop_thread', i)
self.threads.clear() | [
"def",
"stop",
"(",
"self",
")",
":",
"for",
"thread_ident",
",",
"i",
"in",
"self",
".",
"threads",
".",
"items",
"(",
")",
":",
"self",
".",
"bus",
".",
"publish",
"(",
"'stop_thread'",
",",
"i",
")",
"self",
".",
"threads",
".",
"clear",
"(",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/process/plugins.py#L677-L681 | ||
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py | python | IPv6Address.ipv4_mapped | (self) | return IPv4Address(self._ip & 0xFFFFFFFF) | Return the IPv4 mapped address.
Returns:
If the IPv6 address is a v4 mapped address, return the
IPv4 mapped address. Return None otherwise. | Return the IPv4 mapped address. | [
"Return",
"the",
"IPv4",
"mapped",
"address",
"."
] | def ipv4_mapped(self):
"""Return the IPv4 mapped address.
Returns:
If the IPv6 address is a v4 mapped address, return the
IPv4 mapped address. Return None otherwise.
"""
if (self._ip >> 32) != 0xFFFF:
return None
return IPv4Address(self._ip & 0xFFFFFFFF) | [
"def",
"ipv4_mapped",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_ip",
">>",
"32",
")",
"!=",
"0xFFFF",
":",
"return",
"None",
"return",
"IPv4Address",
"(",
"self",
".",
"_ip",
"&",
"0xFFFFFFFF",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L1935-L1945 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/syntax/_django.py | python | SyntaxData.GetCommentPattern | (self) | return [u"#",] | Returns a list of characters used to comment a block of code | Returns a list of characters used to comment a block of code | [
"Returns",
"a",
"list",
"of",
"characters",
"used",
"to",
"comment",
"a",
"block",
"of",
"code"
] | def GetCommentPattern(self):
"""Returns a list of characters used to comment a block of code """
return [u"#",] | [
"def",
"GetCommentPattern",
"(",
"self",
")",
":",
"return",
"[",
"u\"#\"",
",",
"]"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_django.py#L85-L87 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/buildscripts/git.py | python | Repository.is_commit | (self, revision) | return not self._callgit("cat-file", ["-e", "{0}^{{commit}}".format(revision)]) | Return True if the specified hash is a valid git commit. | Return True if the specified hash is a valid git commit. | [
"Return",
"True",
"if",
"the",
"specified",
"hash",
"is",
"a",
"valid",
"git",
"commit",
"."
] | def is_commit(self, revision):
"""Return True if the specified hash is a valid git commit."""
# cat-file -e returns 0 if it is a valid hash
return not self._callgit("cat-file", ["-e", "{0}^{{commit}}".format(revision)]) | [
"def",
"is_commit",
"(",
"self",
",",
"revision",
")",
":",
"# cat-file -e returns 0 if it is a valid hash",
"return",
"not",
"self",
".",
"_callgit",
"(",
"\"cat-file\"",
",",
"[",
"\"-e\"",
",",
"\"{0}^{{commit}}\"",
".",
"format",
"(",
"revision",
")",
"]",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/git.py#L133-L136 | |
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/mox.py | python | MockMethod.__call__ | (self, *params, **named_params) | return expected_method._return_value | Log parameters and return the specified return value.
If the Mock(Anything/Object) associated with this call is in record mode,
this MockMethod will be pushed onto the expected call queue. If the mock
is in replay mode, this will pop a MockMethod off the top of the queue and
verify this call is equal to the expected call.
Raises:
UnexpectedMethodCall if this call is supposed to match an expected method
call and it does not. | Log parameters and return the specified return value. | [
"Log",
"parameters",
"and",
"return",
"the",
"specified",
"return",
"value",
"."
] | def __call__(self, *params, **named_params):
"""Log parameters and return the specified return value.
If the Mock(Anything/Object) associated with this call is in record mode,
this MockMethod will be pushed onto the expected call queue. If the mock
is in replay mode, this will pop a MockMethod off the top of the queue and
verify this call is equal to the expected call.
Raises:
UnexpectedMethodCall if this call is supposed to match an expected method
call and it does not.
"""
self._params = params
self._named_params = named_params
if not self._replay_mode:
self._call_queue.append(self)
return self
expected_method = self._VerifyMethodCall()
if expected_method._side_effects:
expected_method._side_effects(*params, **named_params)
if expected_method._exception:
raise expected_method._exception
return expected_method._return_value | [
"def",
"__call__",
"(",
"self",
",",
"*",
"params",
",",
"*",
"*",
"named_params",
")",
":",
"self",
".",
"_params",
"=",
"params",
"self",
".",
"_named_params",
"=",
"named_params",
"if",
"not",
"self",
".",
"_replay_mode",
":",
"self",
".",
"_call_queue",
".",
"append",
"(",
"self",
")",
"return",
"self",
"expected_method",
"=",
"self",
".",
"_VerifyMethodCall",
"(",
")",
"if",
"expected_method",
".",
"_side_effects",
":",
"expected_method",
".",
"_side_effects",
"(",
"*",
"params",
",",
"*",
"*",
"named_params",
")",
"if",
"expected_method",
".",
"_exception",
":",
"raise",
"expected_method",
".",
"_exception",
"return",
"expected_method",
".",
"_return_value"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/mox.py#L545-L573 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/summary/writer/event_file_writer.py | python | EventFileWriter.close | (self) | Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore. | Flushes the event file to disk and close the file. | [
"Flushes",
"the",
"event",
"file",
"to",
"disk",
"and",
"close",
"the",
"file",
"."
] | def close(self):
"""Flushes the event file to disk and close the file.
Call this method when you do not need the summary writer anymore.
"""
self.add_event(self._sentinel_event)
self.flush()
self._worker.join()
self._ev_writer.Close()
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"add_event",
"(",
"self",
".",
"_sentinel_event",
")",
"self",
".",
"flush",
"(",
")",
"self",
".",
"_worker",
".",
"join",
"(",
")",
"self",
".",
"_ev_writer",
".",
"Close",
"(",
")",
"self",
".",
"_closed",
"=",
"True"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/summary/writer/event_file_writer.py#L121-L130 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/transform.py | python | _make_tuple_of_string | (x) | Converts `x` into a list of `str` if possible.
Args:
x: a `str`, a list of `str`, a tuple of `str`, or `None`.
Returns:
`x` if it is a tuple of str, `tuple(x)` if it is a list of str,
`(x)` if `x` is a `str`, `()` if x is `None`.
Raises:
TypeError: `x` is not a `str`, a list or tuple of `str`, or `None`. | Converts `x` into a list of `str` if possible. | [
"Converts",
"x",
"into",
"a",
"list",
"of",
"str",
"if",
"possible",
"."
] | def _make_tuple_of_string(x):
"""Converts `x` into a list of `str` if possible.
Args:
x: a `str`, a list of `str`, a tuple of `str`, or `None`.
Returns:
`x` if it is a tuple of str, `tuple(x)` if it is a list of str,
`(x)` if `x` is a `str`, `()` if x is `None`.
Raises:
TypeError: `x` is not a `str`, a list or tuple of `str`, or `None`.
"""
if x is None:
return ()
elif isinstance(x, str):
return (x,)
elif isinstance(x, collections.Iterable):
for i, y in enumerate(x):
if not isinstance(y, str):
raise TypeError(
"Expected a tuple or list of strings; entry %s has type %s." %
(i, type(y).__name__))
return x
raise TypeError("Expected a string or list of strings or tuple of strings; " +
"got %s" % type(x).__name__) | [
"def",
"_make_tuple_of_string",
"(",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"(",
")",
"elif",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"(",
"x",
",",
")",
"elif",
"isinstance",
"(",
"x",
",",
"collections",
".",
"Iterable",
")",
":",
"for",
"i",
",",
"y",
"in",
"enumerate",
"(",
"x",
")",
":",
"if",
"not",
"isinstance",
"(",
"y",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected a tuple or list of strings; entry %s has type %s.\"",
"%",
"(",
"i",
",",
"type",
"(",
"y",
")",
".",
"__name__",
")",
")",
"return",
"x",
"raise",
"TypeError",
"(",
"\"Expected a string or list of strings or tuple of strings; \"",
"+",
"\"got %s\"",
"%",
"type",
"(",
"x",
")",
".",
"__name__",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/dataframe/transform.py#L61-L86 | ||
ducha-aiki/LSUVinit | a42ecdc0d44c217a29b65e98748d80b90d5c6279 | python/caffe/io.py | python | load_image | (filename, color=True) | return img | Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale. | Load an image converting from grayscale or alpha as needed. | [
"Load",
"an",
"image",
"converting",
"from",
"grayscale",
"or",
"alpha",
"as",
"needed",
"."
] | def load_image(filename, color=True):
"""
Load an image converting from grayscale or alpha as needed.
Parameters
----------
filename : string
color : boolean
flag for color format. True (default) loads as RGB while False
loads as intensity (if image is already grayscale).
Returns
-------
image : an image with type np.float32 in range [0, 1]
of size (H x W x 3) in RGB or
of size (H x W x 1) in grayscale.
"""
img = skimage.img_as_float(skimage.io.imread(filename)).astype(np.float32)
if img.ndim == 2:
img = img[:, :, np.newaxis]
if color:
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img | [
"def",
"load_image",
"(",
"filename",
",",
"color",
"=",
"True",
")",
":",
"img",
"=",
"skimage",
".",
"img_as_float",
"(",
"skimage",
".",
"io",
".",
"imread",
"(",
"filename",
")",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"if",
"img",
".",
"ndim",
"==",
"2",
":",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
"np",
".",
"newaxis",
"]",
"if",
"color",
":",
"img",
"=",
"np",
".",
"tile",
"(",
"img",
",",
"(",
"1",
",",
"1",
",",
"3",
")",
")",
"elif",
"img",
".",
"shape",
"[",
"2",
"]",
"==",
"4",
":",
"img",
"=",
"img",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"return",
"img"
] | https://github.com/ducha-aiki/LSUVinit/blob/a42ecdc0d44c217a29b65e98748d80b90d5c6279/python/caffe/io.py#L278-L302 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_gdi.py | python | Region.GetBox | (*args, **kwargs) | return _gdi_.Region_GetBox(*args, **kwargs) | GetBox(self) -> Rect | GetBox(self) -> Rect | [
"GetBox",
"(",
"self",
")",
"-",
">",
"Rect"
] | def GetBox(*args, **kwargs):
"""GetBox(self) -> Rect"""
return _gdi_.Region_GetBox(*args, **kwargs) | [
"def",
"GetBox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"Region_GetBox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L1579-L1581 | |
quantOS-org/DataCore | e2ef9bd2c22ee9e2845675b6435a14fa607f3551 | mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/python_message.py | python | _ExtensionDict.__getitem__ | (self, extension_handle) | return result | Returns the current value of the given extension handle. | Returns the current value of the given extension handle. | [
"Returns",
"the",
"current",
"value",
"of",
"the",
"given",
"extension",
"handle",
"."
] | def __getitem__(self, extension_handle):
"""Returns the current value of the given extension handle."""
_VerifyExtensionHandle(self._extended_message, extension_handle)
result = self._extended_message._fields.get(extension_handle)
if result is not None:
return result
if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:
result = extension_handle._default_constructor(self._extended_message)
elif extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
result = extension_handle.message_type._concrete_class()
try:
result._SetListener(self._extended_message._listener_for_children)
except ReferenceError:
pass
else:
# Singular scalar -- just return the default without inserting into the
# dict.
return extension_handle.default_value
# Atomically check if another thread has preempted us and, if not, swap
# in the new object we just created. If someone has preempted us, we
# take that object and discard ours.
# WARNING: We are relying on setdefault() being atomic. This is true
# in CPython but we haven't investigated others. This warning appears
# in several other locations in this file.
result = self._extended_message._fields.setdefault(
extension_handle, result)
return result | [
"def",
"__getitem__",
"(",
"self",
",",
"extension_handle",
")",
":",
"_VerifyExtensionHandle",
"(",
"self",
".",
"_extended_message",
",",
"extension_handle",
")",
"result",
"=",
"self",
".",
"_extended_message",
".",
"_fields",
".",
"get",
"(",
"extension_handle",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"if",
"extension_handle",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"result",
"=",
"extension_handle",
".",
"_default_constructor",
"(",
"self",
".",
"_extended_message",
")",
"elif",
"extension_handle",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"result",
"=",
"extension_handle",
".",
"message_type",
".",
"_concrete_class",
"(",
")",
"try",
":",
"result",
".",
"_SetListener",
"(",
"self",
".",
"_extended_message",
".",
"_listener_for_children",
")",
"except",
"ReferenceError",
":",
"pass",
"else",
":",
"# Singular scalar -- just return the default without inserting into the",
"# dict.",
"return",
"extension_handle",
".",
"default_value",
"# Atomically check if another thread has preempted us and, if not, swap",
"# in the new object we just created. If someone has preempted us, we",
"# take that object and discard ours.",
"# WARNING: We are relying on setdefault() being atomic. This is true",
"# in CPython but we haven't investigated others. This warning appears",
"# in several other locations in this file.",
"result",
"=",
"self",
".",
"_extended_message",
".",
"_fields",
".",
"setdefault",
"(",
"extension_handle",
",",
"result",
")",
"return",
"result"
] | https://github.com/quantOS-org/DataCore/blob/e2ef9bd2c22ee9e2845675b6435a14fa607f3551/mdlink/deps/windows/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L1064-L1095 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/applications/workbench/workbench/plotting/globalfiguremanager.py | python | GlobalFigureManager.has_fignum | (cls, num) | return num in cls.figs | Return *True* if figure *num* exists. | Return *True* if figure *num* exists. | [
"Return",
"*",
"True",
"*",
"if",
"figure",
"*",
"num",
"*",
"exists",
"."
] | def has_fignum(cls, num):
"""
Return *True* if figure *num* exists.
"""
return num in cls.figs | [
"def",
"has_fignum",
"(",
"cls",
",",
"num",
")",
":",
"return",
"num",
"in",
"cls",
".",
"figs"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/plotting/globalfiguremanager.py#L152-L156 | |
arangodb/arangodb | 0d658689c7d1b721b314fa3ca27d38303e1570c8 | 3rdParty/V8/gyp/xcode_emulation.py | python | MacPrefixHeader.__init__ | (self, xcode_settings,
gyp_path_to_build_path, gyp_path_to_build_output) | If xcode_settings is None, all methods on this class are no-ops.
Args:
gyp_path_to_build_path: A function that takes a gyp-relative path,
and returns a path relative to the build directory.
gyp_path_to_build_output: A function that takes a gyp-relative path and
a language code ('c', 'cc', 'm', or 'mm'), and that returns a path
to where the output of precompiling that path for that language
should be placed (without the trailing '.gch'). | If xcode_settings is None, all methods on this class are no-ops. | [
"If",
"xcode_settings",
"is",
"None",
"all",
"methods",
"on",
"this",
"class",
"are",
"no",
"-",
"ops",
"."
] | def __init__(self, xcode_settings,
gyp_path_to_build_path, gyp_path_to_build_output):
"""If xcode_settings is None, all methods on this class are no-ops.
Args:
gyp_path_to_build_path: A function that takes a gyp-relative path,
and returns a path relative to the build directory.
gyp_path_to_build_output: A function that takes a gyp-relative path and
a language code ('c', 'cc', 'm', or 'mm'), and that returns a path
to where the output of precompiling that path for that language
should be placed (without the trailing '.gch').
"""
# This doesn't support per-configuration prefix headers. Good enough
# for now.
self.header = None
self.compile_headers = False
if xcode_settings:
self.header = xcode_settings.GetPerTargetSetting('GCC_PREFIX_HEADER')
self.compile_headers = xcode_settings.GetPerTargetSetting(
'GCC_PRECOMPILE_PREFIX_HEADER', default='NO') != 'NO'
self.compiled_headers = {}
if self.header:
if self.compile_headers:
for lang in ['c', 'cc', 'm', 'mm']:
self.compiled_headers[lang] = gyp_path_to_build_output(
self.header, lang)
self.header = gyp_path_to_build_path(self.header) | [
"def",
"__init__",
"(",
"self",
",",
"xcode_settings",
",",
"gyp_path_to_build_path",
",",
"gyp_path_to_build_output",
")",
":",
"# This doesn't support per-configuration prefix headers. Good enough",
"# for now.",
"self",
".",
"header",
"=",
"None",
"self",
".",
"compile_headers",
"=",
"False",
"if",
"xcode_settings",
":",
"self",
".",
"header",
"=",
"xcode_settings",
".",
"GetPerTargetSetting",
"(",
"'GCC_PREFIX_HEADER'",
")",
"self",
".",
"compile_headers",
"=",
"xcode_settings",
".",
"GetPerTargetSetting",
"(",
"'GCC_PRECOMPILE_PREFIX_HEADER'",
",",
"default",
"=",
"'NO'",
")",
"!=",
"'NO'",
"self",
".",
"compiled_headers",
"=",
"{",
"}",
"if",
"self",
".",
"header",
":",
"if",
"self",
".",
"compile_headers",
":",
"for",
"lang",
"in",
"[",
"'c'",
",",
"'cc'",
",",
"'m'",
",",
"'mm'",
"]",
":",
"self",
".",
"compiled_headers",
"[",
"lang",
"]",
"=",
"gyp_path_to_build_output",
"(",
"self",
".",
"header",
",",
"lang",
")",
"self",
".",
"header",
"=",
"gyp_path_to_build_path",
"(",
"self",
".",
"header",
")"
] | https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/xcode_emulation.py#L1174-L1200 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillView.py | python | DrillView.set_available_modes | (self, modes) | Set the available acquisition modes in the comboxbox.
Args:
modes (list(str)): list of acquisition modes | Set the available acquisition modes in the comboxbox. | [
"Set",
"the",
"available",
"acquisition",
"modes",
"in",
"the",
"comboxbox",
"."
] | def set_available_modes(self, modes):
"""
Set the available acquisition modes in the comboxbox.
Args:
modes (list(str)): list of acquisition modes
"""
self.modeSelector.blockSignals(True)
self.modeSelector.clear()
self.modeSelector.addItems(modes)
self.modeSelector.blockSignals(False) | [
"def",
"set_available_modes",
"(",
"self",
",",
"modes",
")",
":",
"self",
".",
"modeSelector",
".",
"blockSignals",
"(",
"True",
")",
"self",
".",
"modeSelector",
".",
"clear",
"(",
")",
"self",
".",
"modeSelector",
".",
"addItems",
"(",
"modes",
")",
"self",
".",
"modeSelector",
".",
"blockSignals",
"(",
"False",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/view/DrillView.py#L470-L480 | ||
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/functional/elemwise.py | python | floor_div | (x, y) | return _elwise(x, y, mode=Elemwise.Mode.FLOOR_DIV) | r"""Element-wise `floor(x / y)`. | r"""Element-wise `floor(x / y)`. | [
"r",
"Element",
"-",
"wise",
"floor",
"(",
"x",
"/",
"y",
")",
"."
] | def floor_div(x, y):
r"""Element-wise `floor(x / y)`."""
return _elwise(x, y, mode=Elemwise.Mode.FLOOR_DIV) | [
"def",
"floor_div",
"(",
"x",
",",
"y",
")",
":",
"return",
"_elwise",
"(",
"x",
",",
"y",
",",
"mode",
"=",
"Elemwise",
".",
"Mode",
".",
"FLOOR_DIV",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/elemwise.py#L192-L194 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | TextAttr.HasFontUnderlined | (*args, **kwargs) | return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs) | HasFontUnderlined(self) -> bool | HasFontUnderlined(self) -> bool | [
"HasFontUnderlined",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasFontUnderlined(*args, **kwargs):
"""HasFontUnderlined(self) -> bool"""
return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs) | [
"def",
"HasFontUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasFontUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L1804-L1806 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/session.py | python | Session.get_data | (self, data_path) | return self.get_component('data_loader').load_data(data_path) | Retrieve the data associated with `data_path`.
:type data_path: str
:param data_path: The path to the data you wish to retrieve. | Retrieve the data associated with `data_path`. | [
"Retrieve",
"the",
"data",
"associated",
"with",
"data_path",
"."
] | def get_data(self, data_path):
"""
Retrieve the data associated with `data_path`.
:type data_path: str
:param data_path: The path to the data you wish to retrieve.
"""
return self.get_component('data_loader').load_data(data_path) | [
"def",
"get_data",
"(",
"self",
",",
"data_path",
")",
":",
"return",
"self",
".",
"get_component",
"(",
"'data_loader'",
")",
".",
"load_data",
"(",
"data_path",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/session.py#L466-L473 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | MenuItem.SetTextColour | (*args, **kwargs) | return _core_.MenuItem_SetTextColour(*args, **kwargs) | SetTextColour(self, Colour colText) | SetTextColour(self, Colour colText) | [
"SetTextColour",
"(",
"self",
"Colour",
"colText",
")"
] | def SetTextColour(*args, **kwargs):
"""SetTextColour(self, Colour colText)"""
return _core_.MenuItem_SetTextColour(*args, **kwargs) | [
"def",
"SetTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"MenuItem_SetTextColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L12565-L12567 | |
grpc/grpc | 27bc6fe7797e43298dc931b96dc57322d0852a9f | src/python/grpcio/grpc/aio/_base_server.py | python | ServicerContext.send_initial_metadata | (self,
initial_metadata: MetadataType) | Sends the initial metadata value to the client.
This method need not be called by implementations if they have no
metadata to add to what the gRPC runtime will transmit.
Args:
initial_metadata: The initial :term:`metadata`. | Sends the initial metadata value to the client. | [
"Sends",
"the",
"initial",
"metadata",
"value",
"to",
"the",
"client",
"."
] | async def send_initial_metadata(self,
initial_metadata: MetadataType) -> None:
"""Sends the initial metadata value to the client.
This method need not be called by implementations if they have no
metadata to add to what the gRPC runtime will transmit.
Args:
initial_metadata: The initial :term:`metadata`.
""" | [
"async",
"def",
"send_initial_metadata",
"(",
"self",
",",
"initial_metadata",
":",
"MetadataType",
")",
"->",
"None",
":"
] | https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/aio/_base_server.py#L165-L174 | ||
arkenthera/electron-vibrancy | 383153ef9ccb23a6c7517150d6bb0794dff3115e | scripts/cpplint.py | python | FindStartOfExpressionInLine | (line, endpos, stack) | return (-1, stack) | Find position at the matching start of current expression.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
stack: nesting stack at endpos.
Returns:
On finding matching start: (index at matching start, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at beginning of this line) | Find position at the matching start of current expression. | [
"Find",
"position",
"at",
"the",
"matching",
"start",
"of",
"current",
"expression",
"."
] | def FindStartOfExpressionInLine(line, endpos, stack):
"""Find position at the matching start of current expression.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
stack: nesting stack at endpos.
Returns:
On finding matching start: (index at matching start, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at beginning of this line)
"""
i = endpos
while i >= 0:
char = line[i]
if char in ')]}':
# Found end of expression, push to expression stack
stack.append(char)
elif char == '>':
# Found potential end of template argument list.
#
# Ignore it if it's a "->" or ">=" or "operator>"
if (i > 0 and
(line[i - 1] == '-' or
Match(r'\s>=\s', line[i - 1:]) or
Search(r'\boperator\s*$', line[0:i]))):
i -= 1
else:
stack.append('>')
elif char == '<':
# Found potential start of template argument list
if i > 0 and line[i - 1] == '<':
# Left shift operator
i -= 1
else:
# If there is a matching '>', we can pop the expression stack.
# Otherwise, ignore this '<' since it must be an operator.
if stack and stack[-1] == '>':
stack.pop()
if not stack:
return (i, None)
elif char in '([{':
# Found start of expression.
#
# If there are any unmatched '>' on the stack, they must be
# operators. Remove those.
while stack and stack[-1] == '>':
stack.pop()
if not stack:
return (-1, None)
if ((char == '(' and stack[-1] == ')') or
(char == '[' and stack[-1] == ']') or
(char == '{' and stack[-1] == '}')):
stack.pop()
if not stack:
return (i, None)
else:
# Mismatched parentheses
return (-1, None)
elif char == ';':
# Found something that look like end of statements. If we are currently
# expecting a '<', the matching '>' must have been an operator, since
# template argument list should not contain statements.
while stack and stack[-1] == '>':
stack.pop()
if not stack:
return (-1, None)
i -= 1
return (-1, stack) | [
"def",
"FindStartOfExpressionInLine",
"(",
"line",
",",
"endpos",
",",
"stack",
")",
":",
"i",
"=",
"endpos",
"while",
"i",
">=",
"0",
":",
"char",
"=",
"line",
"[",
"i",
"]",
"if",
"char",
"in",
"')]}'",
":",
"# Found end of expression, push to expression stack",
"stack",
".",
"append",
"(",
"char",
")",
"elif",
"char",
"==",
"'>'",
":",
"# Found potential end of template argument list.",
"#",
"# Ignore it if it's a \"->\" or \">=\" or \"operator>\"",
"if",
"(",
"i",
">",
"0",
"and",
"(",
"line",
"[",
"i",
"-",
"1",
"]",
"==",
"'-'",
"or",
"Match",
"(",
"r'\\s>=\\s'",
",",
"line",
"[",
"i",
"-",
"1",
":",
"]",
")",
"or",
"Search",
"(",
"r'\\boperator\\s*$'",
",",
"line",
"[",
"0",
":",
"i",
"]",
")",
")",
")",
":",
"i",
"-=",
"1",
"else",
":",
"stack",
".",
"append",
"(",
"'>'",
")",
"elif",
"char",
"==",
"'<'",
":",
"# Found potential start of template argument list",
"if",
"i",
">",
"0",
"and",
"line",
"[",
"i",
"-",
"1",
"]",
"==",
"'<'",
":",
"# Left shift operator",
"i",
"-=",
"1",
"else",
":",
"# If there is a matching '>', we can pop the expression stack.",
"# Otherwise, ignore this '<' since it must be an operator.",
"if",
"stack",
"and",
"stack",
"[",
"-",
"1",
"]",
"==",
"'>'",
":",
"stack",
".",
"pop",
"(",
")",
"if",
"not",
"stack",
":",
"return",
"(",
"i",
",",
"None",
")",
"elif",
"char",
"in",
"'([{'",
":",
"# Found start of expression.",
"#",
"# If there are any unmatched '>' on the stack, they must be",
"# operators. Remove those.",
"while",
"stack",
"and",
"stack",
"[",
"-",
"1",
"]",
"==",
"'>'",
":",
"stack",
".",
"pop",
"(",
")",
"if",
"not",
"stack",
":",
"return",
"(",
"-",
"1",
",",
"None",
")",
"if",
"(",
"(",
"char",
"==",
"'('",
"and",
"stack",
"[",
"-",
"1",
"]",
"==",
"')'",
")",
"or",
"(",
"char",
"==",
"'['",
"and",
"stack",
"[",
"-",
"1",
"]",
"==",
"']'",
")",
"or",
"(",
"char",
"==",
"'{'",
"and",
"stack",
"[",
"-",
"1",
"]",
"==",
"'}'",
")",
")",
":",
"stack",
".",
"pop",
"(",
")",
"if",
"not",
"stack",
":",
"return",
"(",
"i",
",",
"None",
")",
"else",
":",
"# Mismatched parentheses",
"return",
"(",
"-",
"1",
",",
"None",
")",
"elif",
"char",
"==",
"';'",
":",
"# Found something that look like end of statements. If we are currently",
"# expecting a '<', the matching '>' must have been an operator, since",
"# template argument list should not contain statements.",
"while",
"stack",
"and",
"stack",
"[",
"-",
"1",
"]",
"==",
"'>'",
":",
"stack",
".",
"pop",
"(",
")",
"if",
"not",
"stack",
":",
"return",
"(",
"-",
"1",
",",
"None",
")",
"i",
"-=",
"1",
"return",
"(",
"-",
"1",
",",
"stack",
")"
] | https://github.com/arkenthera/electron-vibrancy/blob/383153ef9ccb23a6c7517150d6bb0794dff3115e/scripts/cpplint.py#L1357-L1431 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/idl/idl/errors.py | python | ParserContext.add_unstable_no_api_version | (self, location, command_name) | Add an error about a command with 'unstable' but no 'api_version'. | Add an error about a command with 'unstable' but no 'api_version'. | [
"Add",
"an",
"error",
"about",
"a",
"command",
"with",
"unstable",
"but",
"no",
"api_version",
"."
] | def add_unstable_no_api_version(self, location, command_name):
# type: (common.SourceLocation, str) -> None
"""Add an error about a command with 'unstable' but no 'api_version'."""
# pylint: disable=invalid-name
self._add_error(
location, ERROR_ID_UNSTABLE_NO_API_VERSION,
("Command '%s' specifies 'unstable' but has no 'api_version'" % (command_name, ))) | [
"def",
"add_unstable_no_api_version",
"(",
"self",
",",
"location",
",",
"command_name",
")",
":",
"# type: (common.SourceLocation, str) -> None",
"# pylint: disable=invalid-name",
"self",
".",
"_add_error",
"(",
"location",
",",
"ERROR_ID_UNSTABLE_NO_API_VERSION",
",",
"(",
"\"Command '%s' specifies 'unstable' but has no 'api_version'\"",
"%",
"(",
"command_name",
",",
")",
")",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/errors.py#L887-L893 | ||
msracver/Deep-Image-Analogy | 632b9287b42552e32dad64922967c8c9ec7fc4d3 | tools/extra/resize_and_crop_images.py | python | PILResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256, fit = True) | Downsample the image. | Downsample the image. | [
"Downsample",
"the",
"image",
"."
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256, fit = True):
'''Downsample the image.
'''
img = Image.open(input_file)
box = (output_side_length, output_side_length)
#preresize image with factor 2, 4, 8 and fast algorithm
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
#calculate the cropping box and get the cropped part
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = int(y2/2-box[1]*wRatio/2)
y2 = int(y2/2+box[1]*wRatio/2)
else:
x1 = int(x2/2-box[0]*hRatio/2)
x2 = int(x2/2+box[0]*hRatio/2)
img = img.crop((x1,y1,x2,y2))
#Resize the image with best quality algorithm ANTI-ALIAS
img.thumbnail(box, Image.ANTIALIAS)
#save it into a file-like object
with open(output_file, 'wb') as out:
img.save(out, 'JPEG', quality=75) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
",",
"fit",
"=",
"True",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"input_file",
")",
"box",
"=",
"(",
"output_side_length",
",",
"output_side_length",
")",
"#preresize image with factor 2, 4, 8 and fast algorithm",
"factor",
"=",
"1",
"while",
"img",
".",
"size",
"[",
"0",
"]",
"/",
"factor",
">",
"2",
"*",
"box",
"[",
"0",
"]",
"and",
"img",
".",
"size",
"[",
"1",
"]",
"*",
"2",
"/",
"factor",
">",
"2",
"*",
"box",
"[",
"1",
"]",
":",
"factor",
"*=",
"2",
"if",
"factor",
">",
"1",
":",
"img",
".",
"thumbnail",
"(",
"(",
"img",
".",
"size",
"[",
"0",
"]",
"/",
"factor",
",",
"img",
".",
"size",
"[",
"1",
"]",
"/",
"factor",
")",
",",
"Image",
".",
"NEAREST",
")",
"#calculate the cropping box and get the cropped part",
"if",
"fit",
":",
"x1",
"=",
"y1",
"=",
"0",
"x2",
",",
"y2",
"=",
"img",
".",
"size",
"wRatio",
"=",
"1.0",
"*",
"x2",
"/",
"box",
"[",
"0",
"]",
"hRatio",
"=",
"1.0",
"*",
"y2",
"/",
"box",
"[",
"1",
"]",
"if",
"hRatio",
">",
"wRatio",
":",
"y1",
"=",
"int",
"(",
"y2",
"/",
"2",
"-",
"box",
"[",
"1",
"]",
"*",
"wRatio",
"/",
"2",
")",
"y2",
"=",
"int",
"(",
"y2",
"/",
"2",
"+",
"box",
"[",
"1",
"]",
"*",
"wRatio",
"/",
"2",
")",
"else",
":",
"x1",
"=",
"int",
"(",
"x2",
"/",
"2",
"-",
"box",
"[",
"0",
"]",
"*",
"hRatio",
"/",
"2",
")",
"x2",
"=",
"int",
"(",
"x2",
"/",
"2",
"+",
"box",
"[",
"0",
"]",
"*",
"hRatio",
"/",
"2",
")",
"img",
"=",
"img",
".",
"crop",
"(",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
")",
"#Resize the image with best quality algorithm ANTI-ALIAS",
"img",
".",
"thumbnail",
"(",
"box",
",",
"Image",
".",
"ANTIALIAS",
")",
"#save it into a file-like object",
"with",
"open",
"(",
"output_file",
",",
"'wb'",
")",
"as",
"out",
":",
"img",
".",
"save",
"(",
"out",
",",
"'JPEG'",
",",
"quality",
"=",
"75",
")"
] | https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/tools/extra/resize_and_crop_images.py#L40-L71 | ||
nasa/fprime | 595cf3682d8365943d86c1a6fe7c78f0a116acf0 | Autocoders/Python/bin/codegen.py | python | cleanUp | () | If something failed then clean up files generated. | If something failed then clean up files generated. | [
"If",
"something",
"failed",
"then",
"clean",
"up",
"files",
"generated",
"."
] | def cleanUp():
"""
If something failed then clean up files generated.
"""
PRINT.info("ERROR: Cleaning up partially created files.")
for file in glob.glob("*_ac_*.new"):
os.remove(file)
for file in glob.glob("*_token.data"):
os.remove(file)
for file in glob.glob("*_opcode_offset.data"):
os.remove(file)
PRINT.info("Completed.")
sys.exit(-1) | [
"def",
"cleanUp",
"(",
")",
":",
"PRINT",
".",
"info",
"(",
"\"ERROR: Cleaning up partially created files.\"",
")",
"for",
"file",
"in",
"glob",
".",
"glob",
"(",
"\"*_ac_*.new\"",
")",
":",
"os",
".",
"remove",
"(",
"file",
")",
"for",
"file",
"in",
"glob",
".",
"glob",
"(",
"\"*_token.data\"",
")",
":",
"os",
".",
"remove",
"(",
"file",
")",
"for",
"file",
"in",
"glob",
".",
"glob",
"(",
"\"*_opcode_offset.data\"",
")",
":",
"os",
".",
"remove",
"(",
"file",
")",
"PRINT",
".",
"info",
"(",
"\"Completed.\"",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")"
] | https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/bin/codegen.py#L91-L107 | ||
CoolProp/CoolProp | 381c8535e5dec3eec27ad430ebbfff8bc9dfc008 | wrappers/Python/CoolProp/Plots/SimpleCycles.py | python | SimpleCycle | (Ref, Te, Tc, DTsh, DTsc, eta_a, Ts_Ph='Ph', **kwargs) | This function plots a simple four-component cycle, on the current axis, or that given by the optional parameter *axis*
Required parameters:
* Ref : A string for the refrigerant
* Te : Evap Temperature in K
* Tc : Condensing Temperature in K
* DTsh : Evaporator outlet superheat in K
* DTsc : Condenser outlet subcooling in K
* eta_a : Adiabatic efficiency of compressor (no units) in range [0,1]
Optional parameters:
* Ts_Ph : 'Ts' for a Temperature-Entropy plot, 'Ph' for a Pressure-Enthalpy
* axis : An axis to use instead of the active axis
* skipPlot : If True, won't actually plot anything, just print COP | This function plots a simple four-component cycle, on the current axis, or that given by the optional parameter *axis* | [
"This",
"function",
"plots",
"a",
"simple",
"four",
"-",
"component",
"cycle",
"on",
"the",
"current",
"axis",
"or",
"that",
"given",
"by",
"the",
"optional",
"parameter",
"*",
"axis",
"*"
] | def SimpleCycle(Ref, Te, Tc, DTsh, DTsc, eta_a, Ts_Ph='Ph', **kwargs):
"""
This function plots a simple four-component cycle, on the current axis, or that given by the optional parameter *axis*
Required parameters:
* Ref : A string for the refrigerant
* Te : Evap Temperature in K
* Tc : Condensing Temperature in K
* DTsh : Evaporator outlet superheat in K
* DTsc : Condenser outlet subcooling in K
* eta_a : Adiabatic efficiency of compressor (no units) in range [0,1]
Optional parameters:
* Ts_Ph : 'Ts' for a Temperature-Entropy plot, 'Ph' for a Pressure-Enthalpy
* axis : An axis to use instead of the active axis
* skipPlot : If True, won't actually plot anything, just print COP
"""
warnings.warn("This function has been deprecated. Please consider converting it to an object inheriting from \"BaseCycle\".", DeprecationWarning)
for i in kwargs:
warnings.warn("This function has been deprecated, your input \"{0}: {1}\" will be ignored".format(i, kwargs[i]), DeprecationWarning)
from CoolProp.Plots import SimpleCompressionCycle
cycle = SimpleCompressionCycle(fluid_ref=Ref, graph_type=Ts_Ph)
cycle.simple_solve_dt(Te, Tc, DTsh, DTsc, eta_a, SI=True)
print(cycle.COP_cooling(), cycle.COP_heating()) | [
"def",
"SimpleCycle",
"(",
"Ref",
",",
"Te",
",",
"Tc",
",",
"DTsh",
",",
"DTsc",
",",
"eta_a",
",",
"Ts_Ph",
"=",
"'Ph'",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"This function has been deprecated. Please consider converting it to an object inheriting from \\\"BaseCycle\\\".\"",
",",
"DeprecationWarning",
")",
"for",
"i",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"\"This function has been deprecated, your input \\\"{0}: {1}\\\" will be ignored\"",
".",
"format",
"(",
"i",
",",
"kwargs",
"[",
"i",
"]",
")",
",",
"DeprecationWarning",
")",
"from",
"CoolProp",
".",
"Plots",
"import",
"SimpleCompressionCycle",
"cycle",
"=",
"SimpleCompressionCycle",
"(",
"fluid_ref",
"=",
"Ref",
",",
"graph_type",
"=",
"Ts_Ph",
")",
"cycle",
".",
"simple_solve_dt",
"(",
"Te",
",",
"Tc",
",",
"DTsh",
",",
"DTsc",
",",
"eta_a",
",",
"SI",
"=",
"True",
")",
"print",
"(",
"cycle",
".",
"COP_cooling",
"(",
")",
",",
"cycle",
".",
"COP_heating",
"(",
")",
")"
] | https://github.com/CoolProp/CoolProp/blob/381c8535e5dec3eec27ad430ebbfff8bc9dfc008/wrappers/Python/CoolProp/Plots/SimpleCycles.py#L14-L42 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_state.py | python | _GradLoopState.pending_exits_count | (self) | return self._pending_exits_count | The number of exits we expect to see but haven't. | The number of exits we expect to see but haven't. | [
"The",
"number",
"of",
"exits",
"we",
"expect",
"to",
"see",
"but",
"haven",
"t",
"."
] | def pending_exits_count(self):
"""The number of exits we expect to see but haven't."""
return self._pending_exits_count | [
"def",
"pending_exits_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pending_exits_count"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/control_flow_state.py#L287-L289 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/intercept.py | python | intercept_build | () | return capture(args) | Entry point for 'intercept-build' command. | Entry point for 'intercept-build' command. | [
"Entry",
"point",
"for",
"intercept",
"-",
"build",
"command",
"."
] | def intercept_build():
""" Entry point for 'intercept-build' command. """
args = parse_args_for_intercept_build()
return capture(args) | [
"def",
"intercept_build",
"(",
")",
":",
"args",
"=",
"parse_args_for_intercept_build",
"(",
")",
"return",
"capture",
"(",
"args",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/intercept.py#L51-L55 | |
google/llvm-propeller | 45c226984fe8377ebfb2ad7713c680d652ba678d | lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py | python | SpawnBase.flush | (self) | This does nothing. It is here to support the interface for a
File-like object. | This does nothing. It is here to support the interface for a
File-like object. | [
"This",
"does",
"nothing",
".",
"It",
"is",
"here",
"to",
"support",
"the",
"interface",
"for",
"a",
"File",
"-",
"like",
"object",
"."
] | def flush(self):
'''This does nothing. It is here to support the interface for a
File-like object. '''
pass | [
"def",
"flush",
"(",
"self",
")",
":",
"pass"
] | https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/spawnbase.py#L506-L509 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/mox3/mox3/mox.py | python | MockObject.__getattr__ | (self, name) | Intercept attribute request on this object.
If the attribute is a public class variable, it will be returned and
not recorded as a call.
If the attribute is not a variable, it is handled like a method
call. The method name is checked against the set of mockable
methods, and a new MockMethod is returned that is aware of the
MockObject's state (record or replay). The call will be recorded
or replayed by the MockMethod's __call__.
Args:
# name: the name of the attribute being requested.
name: str
Returns:
Either a class variable or a new MockMethod that is aware of the
state of the mock (record or replay).
Raises:
UnknownMethodCallError if the MockObject does not mock the
requested method. | Intercept attribute request on this object. | [
"Intercept",
"attribute",
"request",
"on",
"this",
"object",
"."
] | def __getattr__(self, name):
"""Intercept attribute request on this object.
If the attribute is a public class variable, it will be returned and
not recorded as a call.
If the attribute is not a variable, it is handled like a method
call. The method name is checked against the set of mockable
methods, and a new MockMethod is returned that is aware of the
MockObject's state (record or replay). The call will be recorded
or replayed by the MockMethod's __call__.
Args:
# name: the name of the attribute being requested.
name: str
Returns:
Either a class variable or a new MockMethod that is aware of the
state of the mock (record or replay).
Raises:
UnknownMethodCallError if the MockObject does not mock the
requested method.
"""
if name in self._known_vars:
return getattr(self._class_to_mock, name)
if name in self._known_methods:
return self._CreateMockMethod(
name,
method_to_mock=getattr(self._class_to_mock, name))
raise UnknownMethodCallError(name) | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_known_vars",
":",
"return",
"getattr",
"(",
"self",
".",
"_class_to_mock",
",",
"name",
")",
"if",
"name",
"in",
"self",
".",
"_known_methods",
":",
"return",
"self",
".",
"_CreateMockMethod",
"(",
"name",
",",
"method_to_mock",
"=",
"getattr",
"(",
"self",
".",
"_class_to_mock",
",",
"name",
")",
")",
"raise",
"UnknownMethodCallError",
"(",
"name",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mox3/mox3/mox.py#L625-L658 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | ListCtrl.GetColumnIndexFromOrder | (*args, **kwargs) | return _controls_.ListCtrl_GetColumnIndexFromOrder(*args, **kwargs) | GetColumnIndexFromOrder(self, int order) -> int | GetColumnIndexFromOrder(self, int order) -> int | [
"GetColumnIndexFromOrder",
"(",
"self",
"int",
"order",
")",
"-",
">",
"int"
] | def GetColumnIndexFromOrder(*args, **kwargs):
"""GetColumnIndexFromOrder(self, int order) -> int"""
return _controls_.ListCtrl_GetColumnIndexFromOrder(*args, **kwargs) | [
"def",
"GetColumnIndexFromOrder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_GetColumnIndexFromOrder",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4485-L4487 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | IsHandler.InitFunction | (self, func) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def InitFunction(self, func):
"""Overrriden from TypeHandler."""
func.AddCmdArg(Argument("result_shm_id", 'uint32_t'))
func.AddCmdArg(Argument("result_shm_offset", 'uint32_t'))
if func.GetInfo('result') == None:
func.AddInfo('result', ['uint32_t'])
func.passthrough_service_doer_args.append(Argument('result', 'uint32_t*')) | [
"def",
"InitFunction",
"(",
"self",
",",
"func",
")",
":",
"func",
".",
"AddCmdArg",
"(",
"Argument",
"(",
"\"result_shm_id\"",
",",
"'uint32_t'",
")",
")",
"func",
".",
"AddCmdArg",
"(",
"Argument",
"(",
"\"result_shm_offset\"",
",",
"'uint32_t'",
")",
")",
"if",
"func",
".",
"GetInfo",
"(",
"'result'",
")",
"==",
"None",
":",
"func",
".",
"AddInfo",
"(",
"'result'",
",",
"[",
"'uint32_t'",
"]",
")",
"func",
".",
"passthrough_service_doer_args",
".",
"append",
"(",
"Argument",
"(",
"'result'",
",",
"'uint32_t*'",
")",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L8118-L8124 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cgi.py | python | parse_multipart | (fp, pdict) | return partdict | Parse multipart input.
Arguments:
fp : input file
pdict: dictionary containing other parameters of content-type header
Returns a dictionary just like parse_qs(): keys are the field names, each
value is a list of values for that field. This is easy to use but not
much good if you are expecting megabytes to be uploaded -- in that case,
use the FieldStorage class instead which is much more flexible. Note
that content-type is the raw, unparsed contents of the content-type
header.
XXX This does not parse nested multipart parts -- use FieldStorage for
that.
XXX This should really be subsumed by FieldStorage altogether -- no
point in having two implementations of the same parsing algorithm.
Also, FieldStorage protects itself better against certain DoS attacks
by limiting the size of the data read in one chunk. The API here
does not support that kind of protection. This also affects parse()
since it can call parse_multipart(). | Parse multipart input. | [
"Parse",
"multipart",
"input",
"."
] | def parse_multipart(fp, pdict):
"""Parse multipart input.
Arguments:
fp : input file
pdict: dictionary containing other parameters of content-type header
Returns a dictionary just like parse_qs(): keys are the field names, each
value is a list of values for that field. This is easy to use but not
much good if you are expecting megabytes to be uploaded -- in that case,
use the FieldStorage class instead which is much more flexible. Note
that content-type is the raw, unparsed contents of the content-type
header.
XXX This does not parse nested multipart parts -- use FieldStorage for
that.
XXX This should really be subsumed by FieldStorage altogether -- no
point in having two implementations of the same parsing algorithm.
Also, FieldStorage protects itself better against certain DoS attacks
by limiting the size of the data read in one chunk. The API here
does not support that kind of protection. This also affects parse()
since it can call parse_multipart().
"""
boundary = ""
if 'boundary' in pdict:
boundary = pdict['boundary']
if not valid_boundary(boundary):
raise ValueError, ('Invalid boundary in multipart form: %r'
% (boundary,))
nextpart = "--" + boundary
lastpart = "--" + boundary + "--"
partdict = {}
terminator = ""
while terminator != lastpart:
bytes = -1
data = None
if terminator:
# At start of next part. Read headers first.
headers = mimetools.Message(fp)
clength = headers.getheader('content-length')
if clength:
try:
bytes = int(clength)
except ValueError:
pass
if bytes > 0:
if maxlen and bytes > maxlen:
raise ValueError, 'Maximum content length exceeded'
data = fp.read(bytes)
else:
data = ""
# Read lines until end of part.
lines = []
while 1:
line = fp.readline()
if not line:
terminator = lastpart # End outer loop
break
if line[:2] == "--":
terminator = line.strip()
if terminator in (nextpart, lastpart):
break
lines.append(line)
# Done with part.
if data is None:
continue
if bytes < 0:
if lines:
# Strip final line terminator
line = lines[-1]
if line[-2:] == "\r\n":
line = line[:-2]
elif line[-1:] == "\n":
line = line[:-1]
lines[-1] = line
data = "".join(lines)
line = headers['content-disposition']
if not line:
continue
key, params = parse_header(line)
if key != 'form-data':
continue
if 'name' in params:
name = params['name']
else:
continue
if name in partdict:
partdict[name].append(data)
else:
partdict[name] = [data]
return partdict | [
"def",
"parse_multipart",
"(",
"fp",
",",
"pdict",
")",
":",
"boundary",
"=",
"\"\"",
"if",
"'boundary'",
"in",
"pdict",
":",
"boundary",
"=",
"pdict",
"[",
"'boundary'",
"]",
"if",
"not",
"valid_boundary",
"(",
"boundary",
")",
":",
"raise",
"ValueError",
",",
"(",
"'Invalid boundary in multipart form: %r'",
"%",
"(",
"boundary",
",",
")",
")",
"nextpart",
"=",
"\"--\"",
"+",
"boundary",
"lastpart",
"=",
"\"--\"",
"+",
"boundary",
"+",
"\"--\"",
"partdict",
"=",
"{",
"}",
"terminator",
"=",
"\"\"",
"while",
"terminator",
"!=",
"lastpart",
":",
"bytes",
"=",
"-",
"1",
"data",
"=",
"None",
"if",
"terminator",
":",
"# At start of next part. Read headers first.",
"headers",
"=",
"mimetools",
".",
"Message",
"(",
"fp",
")",
"clength",
"=",
"headers",
".",
"getheader",
"(",
"'content-length'",
")",
"if",
"clength",
":",
"try",
":",
"bytes",
"=",
"int",
"(",
"clength",
")",
"except",
"ValueError",
":",
"pass",
"if",
"bytes",
">",
"0",
":",
"if",
"maxlen",
"and",
"bytes",
">",
"maxlen",
":",
"raise",
"ValueError",
",",
"'Maximum content length exceeded'",
"data",
"=",
"fp",
".",
"read",
"(",
"bytes",
")",
"else",
":",
"data",
"=",
"\"\"",
"# Read lines until end of part.",
"lines",
"=",
"[",
"]",
"while",
"1",
":",
"line",
"=",
"fp",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"terminator",
"=",
"lastpart",
"# End outer loop",
"break",
"if",
"line",
"[",
":",
"2",
"]",
"==",
"\"--\"",
":",
"terminator",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"terminator",
"in",
"(",
"nextpart",
",",
"lastpart",
")",
":",
"break",
"lines",
".",
"append",
"(",
"line",
")",
"# Done with part.",
"if",
"data",
"is",
"None",
":",
"continue",
"if",
"bytes",
"<",
"0",
":",
"if",
"lines",
":",
"# Strip final line terminator",
"line",
"=",
"lines",
"[",
"-",
"1",
"]",
"if",
"line",
"[",
"-",
"2",
":",
"]",
"==",
"\"\\r\\n\"",
":",
"line",
"=",
"line",
"[",
":",
"-",
"2",
"]",
"elif",
"line",
"[",
"-",
"1",
":",
"]",
"==",
"\"\\n\"",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"lines",
"[",
"-",
"1",
"]",
"=",
"line",
"data",
"=",
"\"\"",
".",
"join",
"(",
"lines",
")",
"line",
"=",
"headers",
"[",
"'content-disposition'",
"]",
"if",
"not",
"line",
":",
"continue",
"key",
",",
"params",
"=",
"parse_header",
"(",
"line",
")",
"if",
"key",
"!=",
"'form-data'",
":",
"continue",
"if",
"'name'",
"in",
"params",
":",
"name",
"=",
"params",
"[",
"'name'",
"]",
"else",
":",
"continue",
"if",
"name",
"in",
"partdict",
":",
"partdict",
"[",
"name",
"]",
".",
"append",
"(",
"data",
")",
"else",
":",
"partdict",
"[",
"name",
"]",
"=",
"[",
"data",
"]",
"return",
"partdict"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/cgi.py#L193-L288 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/auibar.py | python | AuiDefaultToolBarArt.DrawOverflowButton | (self, dc, wnd, rect, state) | Draws the overflow button for the :class:`AuiToolBar`.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` derived window;
:param Rect `rect`: the :class:`AuiToolBarItem` rectangle;
:param integer `state`: the overflow button state. | Draws the overflow button for the :class:`AuiToolBar`.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` derived window;
:param Rect `rect`: the :class:`AuiToolBarItem` rectangle;
:param integer `state`: the overflow button state. | [
"Draws",
"the",
"overflow",
"button",
"for",
"the",
":",
"class",
":",
"AuiToolBar",
".",
":",
"param",
"dc",
":",
"a",
":",
"class",
":",
"DC",
"device",
"context",
";",
":",
"param",
"wnd",
":",
"a",
":",
"class",
":",
"Window",
"derived",
"window",
";",
":",
"param",
"Rect",
"rect",
":",
"the",
":",
"class",
":",
"AuiToolBarItem",
"rectangle",
";",
":",
"param",
"integer",
"state",
":",
"the",
"overflow",
"button",
"state",
"."
] | def DrawOverflowButton(self, dc, wnd, rect, state):
"""
Draws the overflow button for the :class:`AuiToolBar`.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` derived window;
:param Rect `rect`: the :class:`AuiToolBarItem` rectangle;
:param integer `state`: the overflow button state.
"""
if state & AUI_BUTTON_STATE_HOVER or state & AUI_BUTTON_STATE_PRESSED:
cli_rect = wnd.GetClientRect()
light_gray_bg = StepColour(self._highlight_colour, 170)
if self._agwFlags & AUI_TB_VERTICAL:
dc.SetPen(wx.Pen(self._highlight_colour))
dc.DrawLine(rect.x, rect.y, rect.x+rect.width, rect.y)
dc.SetPen(wx.Pen(light_gray_bg))
dc.SetBrush(wx.Brush(light_gray_bg))
dc.DrawRectangle(rect.x, rect.y+1, rect.width, rect.height)
else:
dc.SetPen(wx.Pen(self._highlight_colour))
dc.DrawLine(rect.x, rect.y, rect.x, rect.y+rect.height)
dc.SetPen(wx.Pen(light_gray_bg))
dc.SetBrush(wx.Brush(light_gray_bg))
dc.DrawRectangle(rect.x+1, rect.y, rect.width, rect.height)
x = rect.x + 1 + (rect.width-self._overflow_bmp.GetWidth())/2
y = rect.y + 1 + (rect.height-self._overflow_bmp.GetHeight())/2
dc.DrawBitmap(self._overflow_bmp, x, y, True) | [
"def",
"DrawOverflowButton",
"(",
"self",
",",
"dc",
",",
"wnd",
",",
"rect",
",",
"state",
")",
":",
"if",
"state",
"&",
"AUI_BUTTON_STATE_HOVER",
"or",
"state",
"&",
"AUI_BUTTON_STATE_PRESSED",
":",
"cli_rect",
"=",
"wnd",
".",
"GetClientRect",
"(",
")",
"light_gray_bg",
"=",
"StepColour",
"(",
"self",
".",
"_highlight_colour",
",",
"170",
")",
"if",
"self",
".",
"_agwFlags",
"&",
"AUI_TB_VERTICAL",
":",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"self",
".",
"_highlight_colour",
")",
")",
"dc",
".",
"DrawLine",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
",",
"rect",
".",
"x",
"+",
"rect",
".",
"width",
",",
"rect",
".",
"y",
")",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"light_gray_bg",
")",
")",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"light_gray_bg",
")",
")",
"dc",
".",
"DrawRectangle",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
"+",
"1",
",",
"rect",
".",
"width",
",",
"rect",
".",
"height",
")",
"else",
":",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"self",
".",
"_highlight_colour",
")",
")",
"dc",
".",
"DrawLine",
"(",
"rect",
".",
"x",
",",
"rect",
".",
"y",
",",
"rect",
".",
"x",
",",
"rect",
".",
"y",
"+",
"rect",
".",
"height",
")",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"light_gray_bg",
")",
")",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"light_gray_bg",
")",
")",
"dc",
".",
"DrawRectangle",
"(",
"rect",
".",
"x",
"+",
"1",
",",
"rect",
".",
"y",
",",
"rect",
".",
"width",
",",
"rect",
".",
"height",
")",
"x",
"=",
"rect",
".",
"x",
"+",
"1",
"+",
"(",
"rect",
".",
"width",
"-",
"self",
".",
"_overflow_bmp",
".",
"GetWidth",
"(",
")",
")",
"/",
"2",
"y",
"=",
"rect",
".",
"y",
"+",
"1",
"+",
"(",
"rect",
".",
"height",
"-",
"self",
".",
"_overflow_bmp",
".",
"GetHeight",
"(",
")",
")",
"/",
"2",
"dc",
".",
"DrawBitmap",
"(",
"self",
".",
"_overflow_bmp",
",",
"x",
",",
"y",
",",
"True",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L1307-L1340 | ||
NicknineTheEagle/TF2-Base | 20459c5a7fbc995b6bf54fa85c2f62a101e9fb64 | src/thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py | python | DescriptorBase.__init__ | (self, options, options_class_name) | Initialize the descriptor given its options message and the name of the
class of the options message. The name of the class is required in case
the options message is None and has to be created. | Initialize the descriptor given its options message and the name of the
class of the options message. The name of the class is required in case
the options message is None and has to be created. | [
"Initialize",
"the",
"descriptor",
"given",
"its",
"options",
"message",
"and",
"the",
"name",
"of",
"the",
"class",
"of",
"the",
"options",
"message",
".",
"The",
"name",
"of",
"the",
"class",
"is",
"required",
"in",
"case",
"the",
"options",
"message",
"is",
"None",
"and",
"has",
"to",
"be",
"created",
"."
] | def __init__(self, options, options_class_name):
"""Initialize the descriptor given its options message and the name of the
class of the options message. The name of the class is required in case
the options message is None and has to be created.
"""
self._options = options
self._options_class_name = options_class_name
# Does this descriptor have non-default options?
self.has_options = options is not None | [
"def",
"__init__",
"(",
"self",
",",
"options",
",",
"options_class_name",
")",
":",
"self",
".",
"_options",
"=",
"options",
"self",
".",
"_options_class_name",
"=",
"options_class_name",
"# Does this descriptor have non-default options?",
"self",
".",
"has_options",
"=",
"options",
"is",
"not",
"None"
] | https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/descriptor.py#L67-L76 | ||
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/utils/depend.py | python | depend_value.__get__ | (self, instance, owner) | return self.get() | Overwrites standard get function. | Overwrites standard get function. | [
"Overwrites",
"standard",
"get",
"function",
"."
] | def __get__(self, instance, owner):
"""Overwrites standard get function."""
return self.get() | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"owner",
")",
":",
"return",
"self",
".",
"get",
"(",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/utils/depend.py#L327-L330 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/stc.py | python | StyledTextCtrl.GetMultipleSelection | (*args, **kwargs) | return _stc.StyledTextCtrl_GetMultipleSelection(*args, **kwargs) | GetMultipleSelection(self) -> bool
Whether multiple selections can be made | GetMultipleSelection(self) -> bool | [
"GetMultipleSelection",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetMultipleSelection(*args, **kwargs):
"""
GetMultipleSelection(self) -> bool
Whether multiple selections can be made
"""
return _stc.StyledTextCtrl_GetMultipleSelection(*args, **kwargs) | [
"def",
"GetMultipleSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_stc",
".",
"StyledTextCtrl_GetMultipleSelection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L6048-L6054 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/lite/examples/experimental_new_converter/stack_trace_example.py | python | test_from_concrete_function | () | displaying stack trace when converting concrete function. | displaying stack trace when converting concrete function. | [
"displaying",
"stack",
"trace",
"when",
"converting",
"concrete",
"function",
"."
] | def test_from_concrete_function():
"""displaying stack trace when converting concrete function."""
@tf.function(input_signature=[tf.TensorSpec(shape=[3, 3], dtype=tf.float32)])
def model(x):
y = tf.math.reciprocal(x) # not supported
return y + y
func = model.get_concrete_function()
converter = tf.lite.TFLiteConverter.from_concrete_functions([func], model)
converter.convert() | [
"def",
"test_from_concrete_function",
"(",
")",
":",
"@",
"tf",
".",
"function",
"(",
"input_signature",
"=",
"[",
"tf",
".",
"TensorSpec",
"(",
"shape",
"=",
"[",
"3",
",",
"3",
"]",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"]",
")",
"def",
"model",
"(",
"x",
")",
":",
"y",
"=",
"tf",
".",
"math",
".",
"reciprocal",
"(",
"x",
")",
"# not supported",
"return",
"y",
"+",
"y",
"func",
"=",
"model",
".",
"get_concrete_function",
"(",
")",
"converter",
"=",
"tf",
".",
"lite",
".",
"TFLiteConverter",
".",
"from_concrete_functions",
"(",
"[",
"func",
"]",
",",
"model",
")",
"converter",
".",
"convert",
"(",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/examples/experimental_new_converter/stack_trace_example.py#L58-L67 | ||
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py | python | CodeGenerator.return_buffer_contents | (self, frame, force_unescaped=False) | Return the buffer contents of the frame. | Return the buffer contents of the frame. | [
"Return",
"the",
"buffer",
"contents",
"of",
"the",
"frame",
"."
] | def return_buffer_contents(self, frame, force_unescaped=False):
"""Return the buffer contents of the frame."""
if not force_unescaped:
if frame.eval_ctx.volatile:
self.writeline('if context.eval_ctx.autoescape:')
self.indent()
self.writeline('return Markup(concat(%s))' % frame.buffer)
self.outdent()
self.writeline('else:')
self.indent()
self.writeline('return concat(%s)' % frame.buffer)
self.outdent()
return
elif frame.eval_ctx.autoescape:
self.writeline('return Markup(concat(%s))' % frame.buffer)
return
self.writeline('return concat(%s)' % frame.buffer) | [
"def",
"return_buffer_contents",
"(",
"self",
",",
"frame",
",",
"force_unescaped",
"=",
"False",
")",
":",
"if",
"not",
"force_unescaped",
":",
"if",
"frame",
".",
"eval_ctx",
".",
"volatile",
":",
"self",
".",
"writeline",
"(",
"'if context.eval_ctx.autoescape:'",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"writeline",
"(",
"'return Markup(concat(%s))'",
"%",
"frame",
".",
"buffer",
")",
"self",
".",
"outdent",
"(",
")",
"self",
".",
"writeline",
"(",
"'else:'",
")",
"self",
".",
"indent",
"(",
")",
"self",
".",
"writeline",
"(",
"'return concat(%s)'",
"%",
"frame",
".",
"buffer",
")",
"self",
".",
"outdent",
"(",
")",
"return",
"elif",
"frame",
".",
"eval_ctx",
".",
"autoescape",
":",
"self",
".",
"writeline",
"(",
"'return Markup(concat(%s))'",
"%",
"frame",
".",
"buffer",
")",
"return",
"self",
".",
"writeline",
"(",
"'return concat(%s)'",
"%",
"frame",
".",
"buffer",
")"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/compiler.py#L327-L343 | ||
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/meta.py | python | find_referenced_templates | (ast) | Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed. | Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded. | [
"Finds",
"all",
"the",
"referenced",
"templates",
"from",
"the",
"AST",
".",
"This",
"will",
"return",
"an",
"iterator",
"over",
"all",
"the",
"hardcoded",
"template",
"extensions",
"inclusions",
"and",
"imports",
".",
"If",
"dynamic",
"inheritance",
"or",
"inclusion",
"is",
"used",
"None",
"will",
"be",
"yielded",
"."
] | def find_referenced_templates(ast):
"""Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed.
"""
for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
nodes.Include)):
if not isinstance(node.template, nodes.Const):
# a tuple with some non consts in there
if isinstance(node.template, (nodes.Tuple, nodes.List)):
for template_name in node.template.items:
# something const, only yield the strings and ignore
# non-string consts that really just make no sense
if isinstance(template_name, nodes.Const):
if isinstance(template_name.value, string_types):
yield template_name.value
# something dynamic in there
else:
yield None
# something dynamic we don't know about here
else:
yield None
continue
# constant is a basestring, direct template name
if isinstance(node.template.value, string_types):
yield node.template.value
# a tuple or list (latter *should* not happen) made of consts,
# yield the consts that are strings. We could warn here for
# non string values
elif isinstance(node, nodes.Include) and \
isinstance(node.template.value, (tuple, list)):
for template_name in node.template.value:
if isinstance(template_name, string_types):
yield template_name
# something else we don't care about, we could warn here
else:
yield None | [
"def",
"find_referenced_templates",
"(",
"ast",
")",
":",
"for",
"node",
"in",
"ast",
".",
"find_all",
"(",
"(",
"nodes",
".",
"Extends",
",",
"nodes",
".",
"FromImport",
",",
"nodes",
".",
"Import",
",",
"nodes",
".",
"Include",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
".",
"template",
",",
"nodes",
".",
"Const",
")",
":",
"# a tuple with some non consts in there",
"if",
"isinstance",
"(",
"node",
".",
"template",
",",
"(",
"nodes",
".",
"Tuple",
",",
"nodes",
".",
"List",
")",
")",
":",
"for",
"template_name",
"in",
"node",
".",
"template",
".",
"items",
":",
"# something const, only yield the strings and ignore",
"# non-string consts that really just make no sense",
"if",
"isinstance",
"(",
"template_name",
",",
"nodes",
".",
"Const",
")",
":",
"if",
"isinstance",
"(",
"template_name",
".",
"value",
",",
"string_types",
")",
":",
"yield",
"template_name",
".",
"value",
"# something dynamic in there",
"else",
":",
"yield",
"None",
"# something dynamic we don't know about here",
"else",
":",
"yield",
"None",
"continue",
"# constant is a basestring, direct template name",
"if",
"isinstance",
"(",
"node",
".",
"template",
".",
"value",
",",
"string_types",
")",
":",
"yield",
"node",
".",
"template",
".",
"value",
"# a tuple or list (latter *should* not happen) made of consts,",
"# yield the consts that are strings. We could warn here for",
"# non string values",
"elif",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"Include",
")",
"and",
"isinstance",
"(",
"node",
".",
"template",
".",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"for",
"template_name",
"in",
"node",
".",
"template",
".",
"value",
":",
"if",
"isinstance",
"(",
"template_name",
",",
"string_types",
")",
":",
"yield",
"template_name",
"# something else we don't care about, we could warn here",
"else",
":",
"yield",
"None"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/meta.py#L60-L106 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/extras.py | python | clump_masked | (a) | return _ezclump(mask) | Returns a list of slices corresponding to the masked clumps of a 1-D array.
(A "clump" is defined as a contiguous region of the array).
Parameters
----------
a : ndarray
A one-dimensional masked array.
Returns
-------
slices : list of slice
The list of slices, one for each continuous region of masked elements
in `a`.
Notes
-----
.. versionadded:: 1.4.0
See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
notmasked_contiguous, clump_unmasked
Examples
--------
>>> a = np.ma.masked_array(np.arange(10))
>>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
>>> np.ma.clump_masked(a)
[slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)] | Returns a list of slices corresponding to the masked clumps of a 1-D array.
(A "clump" is defined as a contiguous region of the array). | [
"Returns",
"a",
"list",
"of",
"slices",
"corresponding",
"to",
"the",
"masked",
"clumps",
"of",
"a",
"1",
"-",
"D",
"array",
".",
"(",
"A",
"clump",
"is",
"defined",
"as",
"a",
"contiguous",
"region",
"of",
"the",
"array",
")",
"."
] | def clump_masked(a):
"""
Returns a list of slices corresponding to the masked clumps of a 1-D array.
(A "clump" is defined as a contiguous region of the array).
Parameters
----------
a : ndarray
A one-dimensional masked array.
Returns
-------
slices : list of slice
The list of slices, one for each continuous region of masked elements
in `a`.
Notes
-----
.. versionadded:: 1.4.0
See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
notmasked_contiguous, clump_unmasked
Examples
--------
>>> a = np.ma.masked_array(np.arange(10))
>>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
>>> np.ma.clump_masked(a)
[slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)]
"""
mask = ma.getmask(a)
if mask is nomask:
return []
return _ezclump(mask) | [
"def",
"clump_masked",
"(",
"a",
")",
":",
"mask",
"=",
"ma",
".",
"getmask",
"(",
"a",
")",
"if",
"mask",
"is",
"nomask",
":",
"return",
"[",
"]",
"return",
"_ezclump",
"(",
"mask",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/extras.py#L1838-L1874 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/fancy_getopt.py | python | OptionDummy.__init__ | (self, options=[]) | Create a new OptionDummy instance. The attributes listed in
'options' will be initialized to None. | Create a new OptionDummy instance. The attributes listed in
'options' will be initialized to None. | [
"Create",
"a",
"new",
"OptionDummy",
"instance",
".",
"The",
"attributes",
"listed",
"in",
"options",
"will",
"be",
"initialized",
"to",
"None",
"."
] | def __init__ (self, options=[]):
"""Create a new OptionDummy instance. The attributes listed in
'options' will be initialized to None."""
for opt in options:
setattr(self, opt, None) | [
"def",
"__init__",
"(",
"self",
",",
"options",
"=",
"[",
"]",
")",
":",
"for",
"opt",
"in",
"options",
":",
"setattr",
"(",
"self",
",",
"opt",
",",
"None",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/fancy_getopt.py#L480-L484 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/joblib/joblib/externals/loky/backend/spawn.py | python | prepare | (data) | Try to get current process ready to unpickle process object | Try to get current process ready to unpickle process object | [
"Try",
"to",
"get",
"current",
"process",
"ready",
"to",
"unpickle",
"process",
"object"
] | def prepare(data):
'''
Try to get current process ready to unpickle process object
'''
if 'name' in data:
process.current_process().name = data['name']
if 'authkey' in data:
process.current_process().authkey = data['authkey']
if 'log_to_stderr' in data and data['log_to_stderr']:
util.log_to_stderr()
if 'log_level' in data:
util.get_logger().setLevel(data['log_level'])
if 'log_fmt' in data:
import logging
util.get_logger().handlers[0].setFormatter(
logging.Formatter(data['log_fmt'])
)
if 'sys_path' in data:
sys.path = data['sys_path']
if 'sys_argv' in data:
sys.argv = data['sys_argv']
if 'dir' in data:
os.chdir(data['dir'])
if 'orig_dir' in data:
process.ORIGINAL_DIR = data['orig_dir']
if 'mp_tracker_args' in data:
from multiprocessing.resource_tracker import (
_resource_tracker as mp_resource_tracker
)
mp_resource_tracker._fd = data['mp_tracker_args']['fd']
mp_resource_tracker._pid = data['mp_tracker_args']['pid']
if 'tracker_args' in data:
from .resource_tracker import _resource_tracker
_resource_tracker._pid = data["tracker_args"]['pid']
if sys.platform == 'win32':
handle = data["tracker_args"]["fh"]
_resource_tracker._fd = msvcrt.open_osfhandle(handle, 0)
else:
_resource_tracker._fd = data["tracker_args"]["fd"]
if 'init_main_from_name' in data:
_fixup_main_from_name(data['init_main_from_name'])
elif 'init_main_from_path' in data:
_fixup_main_from_path(data['init_main_from_path']) | [
"def",
"prepare",
"(",
"data",
")",
":",
"if",
"'name'",
"in",
"data",
":",
"process",
".",
"current_process",
"(",
")",
".",
"name",
"=",
"data",
"[",
"'name'",
"]",
"if",
"'authkey'",
"in",
"data",
":",
"process",
".",
"current_process",
"(",
")",
".",
"authkey",
"=",
"data",
"[",
"'authkey'",
"]",
"if",
"'log_to_stderr'",
"in",
"data",
"and",
"data",
"[",
"'log_to_stderr'",
"]",
":",
"util",
".",
"log_to_stderr",
"(",
")",
"if",
"'log_level'",
"in",
"data",
":",
"util",
".",
"get_logger",
"(",
")",
".",
"setLevel",
"(",
"data",
"[",
"'log_level'",
"]",
")",
"if",
"'log_fmt'",
"in",
"data",
":",
"import",
"logging",
"util",
".",
"get_logger",
"(",
")",
".",
"handlers",
"[",
"0",
"]",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"data",
"[",
"'log_fmt'",
"]",
")",
")",
"if",
"'sys_path'",
"in",
"data",
":",
"sys",
".",
"path",
"=",
"data",
"[",
"'sys_path'",
"]",
"if",
"'sys_argv'",
"in",
"data",
":",
"sys",
".",
"argv",
"=",
"data",
"[",
"'sys_argv'",
"]",
"if",
"'dir'",
"in",
"data",
":",
"os",
".",
"chdir",
"(",
"data",
"[",
"'dir'",
"]",
")",
"if",
"'orig_dir'",
"in",
"data",
":",
"process",
".",
"ORIGINAL_DIR",
"=",
"data",
"[",
"'orig_dir'",
"]",
"if",
"'mp_tracker_args'",
"in",
"data",
":",
"from",
"multiprocessing",
".",
"resource_tracker",
"import",
"(",
"_resource_tracker",
"as",
"mp_resource_tracker",
")",
"mp_resource_tracker",
".",
"_fd",
"=",
"data",
"[",
"'mp_tracker_args'",
"]",
"[",
"'fd'",
"]",
"mp_resource_tracker",
".",
"_pid",
"=",
"data",
"[",
"'mp_tracker_args'",
"]",
"[",
"'pid'",
"]",
"if",
"'tracker_args'",
"in",
"data",
":",
"from",
".",
"resource_tracker",
"import",
"_resource_tracker",
"_resource_tracker",
".",
"_pid",
"=",
"data",
"[",
"\"tracker_args\"",
"]",
"[",
"'pid'",
"]",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"handle",
"=",
"data",
"[",
"\"tracker_args\"",
"]",
"[",
"\"fh\"",
"]",
"_resource_tracker",
".",
"_fd",
"=",
"msvcrt",
".",
"open_osfhandle",
"(",
"handle",
",",
"0",
")",
"else",
":",
"_resource_tracker",
".",
"_fd",
"=",
"data",
"[",
"\"tracker_args\"",
"]",
"[",
"\"fd\"",
"]",
"if",
"'init_main_from_name'",
"in",
"data",
":",
"_fixup_main_from_name",
"(",
"data",
"[",
"'init_main_from_name'",
"]",
")",
"elif",
"'init_main_from_path'",
"in",
"data",
":",
"_fixup_main_from_path",
"(",
"data",
"[",
"'init_main_from_path'",
"]",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/joblib/joblib/externals/loky/backend/spawn.py#L144-L196 | ||
DOCGroup/ACE_TAO | 79c6e76aa604bcc83e2db1608ab1a1af1960141a | ACE/bin/make_release.py | python | check_workspace | () | Checks that the DOC and MPC repositories are up to date. | Checks that the DOC and MPC repositories are up to date. | [
"Checks",
"that",
"the",
"DOC",
"and",
"MPC",
"repositories",
"are",
"up",
"to",
"date",
"."
] | def check_workspace ():
""" Checks that the DOC and MPC repositories are up to date. """
try:
ex ("cd $DOC_ROOT/ACE_TAO && git pull -p")
print ("Successfully updated ACE/TAO working copy")
except:
print ("Unable to update ACE/TAO workspace at " + doc_root)
raise
try:
ex ("cd $DOC_ROOT/MPC && git pull -p")
print ("Successfully updated MPC working copy to revision ")
except:
print ("Unable to update the MPC workspace at " + doc_root + "/ACE/MPC")
raise
vprint ("Repos root URL = " + opts.repo_root + "\n")
vprint ("Repos MPC root URL = " + opts.mpc_root + "\n") | [
"def",
"check_workspace",
"(",
")",
":",
"try",
":",
"ex",
"(",
"\"cd $DOC_ROOT/ACE_TAO && git pull -p\"",
")",
"print",
"(",
"\"Successfully updated ACE/TAO working copy\"",
")",
"except",
":",
"print",
"(",
"\"Unable to update ACE/TAO workspace at \"",
"+",
"doc_root",
")",
"raise",
"try",
":",
"ex",
"(",
"\"cd $DOC_ROOT/MPC && git pull -p\"",
")",
"print",
"(",
"\"Successfully updated MPC working copy to revision \"",
")",
"except",
":",
"print",
"(",
"\"Unable to update the MPC workspace at \"",
"+",
"doc_root",
"+",
"\"/ACE/MPC\"",
")",
"raise",
"vprint",
"(",
"\"Repos root URL = \"",
"+",
"opts",
".",
"repo_root",
"+",
"\"\\n\"",
")",
"vprint",
"(",
"\"Repos MPC root URL = \"",
"+",
"opts",
".",
"mpc_root",
"+",
"\"\\n\"",
")"
] | https://github.com/DOCGroup/ACE_TAO/blob/79c6e76aa604bcc83e2db1608ab1a1af1960141a/ACE/bin/make_release.py#L172-L190 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/data_flow_grad.py | python | _DynamicPartitionGrads | (op, *grads) | return [reconstructed, None] | Gradients for DynamicPartition. | Gradients for DynamicPartition. | [
"Gradients",
"for",
"DynamicPartition",
"."
] | def _DynamicPartitionGrads(op, *grads):
"""Gradients for DynamicPartition."""
data = op.inputs[0]
indices = op.inputs[1]
num_partitions = op.get_attr("num_partitions")
prefix_shape = array_ops.shape(indices)
original_indices = array_ops.reshape(
math_ops.range(math_ops.reduce_prod(prefix_shape)), prefix_shape)
partitioned_indices = data_flow_ops.dynamic_partition(
original_indices, indices, num_partitions)
reconstructed = data_flow_ops.dynamic_stitch(partitioned_indices, grads)
reconstructed = array_ops.reshape(reconstructed, array_ops.shape(data))
return [reconstructed, None] | [
"def",
"_DynamicPartitionGrads",
"(",
"op",
",",
"*",
"grads",
")",
":",
"data",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"indices",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"num_partitions",
"=",
"op",
".",
"get_attr",
"(",
"\"num_partitions\"",
")",
"prefix_shape",
"=",
"array_ops",
".",
"shape",
"(",
"indices",
")",
"original_indices",
"=",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"range",
"(",
"math_ops",
".",
"reduce_prod",
"(",
"prefix_shape",
")",
")",
",",
"prefix_shape",
")",
"partitioned_indices",
"=",
"data_flow_ops",
".",
"dynamic_partition",
"(",
"original_indices",
",",
"indices",
",",
"num_partitions",
")",
"reconstructed",
"=",
"data_flow_ops",
".",
"dynamic_stitch",
"(",
"partitioned_indices",
",",
"grads",
")",
"reconstructed",
"=",
"array_ops",
".",
"reshape",
"(",
"reconstructed",
",",
"array_ops",
".",
"shape",
"(",
"data",
")",
")",
"return",
"[",
"reconstructed",
",",
"None",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/data_flow_grad.py#L31-L44 | |
assimp/assimp | 97c7e084c2f7f8c9355ea42f73605890481bddc5 | port/PyAssimp/scripts/transformations.py | python | Arcball.setaxes | (self, *axes) | Set axes to constrain rotations. | Set axes to constrain rotations. | [
"Set",
"axes",
"to",
"constrain",
"rotations",
"."
] | def setaxes(self, *axes):
"""Set axes to constrain rotations."""
if axes is None:
self._axes = None
else:
self._axes = [unit_vector(axis) for axis in axes] | [
"def",
"setaxes",
"(",
"self",
",",
"*",
"axes",
")",
":",
"if",
"axes",
"is",
"None",
":",
"self",
".",
"_axes",
"=",
"None",
"else",
":",
"self",
".",
"_axes",
"=",
"[",
"unit_vector",
"(",
"axis",
")",
"for",
"axis",
"in",
"axes",
"]"
] | https://github.com/assimp/assimp/blob/97c7e084c2f7f8c9355ea42f73605890481bddc5/port/PyAssimp/scripts/transformations.py#L1420-L1425 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/shapedbutton.py | python | SButton.SetLabel | (self, label=None) | Sets the button label.
:param `label`: the new button label. | Sets the button label. | [
"Sets",
"the",
"button",
"label",
"."
] | def SetLabel(self, label=None):
"""
Sets the button label.
:param `label`: the new button label.
"""
if label is None:
label = ""
self._buttonlabel = label | [
"def",
"SetLabel",
"(",
"self",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
"is",
"None",
":",
"label",
"=",
"\"\"",
"self",
".",
"_buttonlabel",
"=",
"label"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/shapedbutton.py#L376-L386 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/tf_utils.py | python | maybe_init_scope | (layer) | Open an `init_scope` if in V2 mode and using the keras graph.
Arguments:
layer: The Layer/Model that is currently active.
Yields:
None | Open an `init_scope` if in V2 mode and using the keras graph. | [
"Open",
"an",
"init_scope",
"if",
"in",
"V2",
"mode",
"and",
"using",
"the",
"keras",
"graph",
"."
] | def maybe_init_scope(layer):
"""Open an `init_scope` if in V2 mode and using the keras graph.
Arguments:
layer: The Layer/Model that is currently active.
Yields:
None
"""
# Don't open an init_scope in V1 mode or when using legacy tf.layers.
if (ops.executing_eagerly_outside_functions() and
getattr(layer, '_keras_style', True)):
with ops.init_scope():
yield
else:
yield | [
"def",
"maybe_init_scope",
"(",
"layer",
")",
":",
"# Don't open an init_scope in V1 mode or when using legacy tf.layers.",
"if",
"(",
"ops",
".",
"executing_eagerly_outside_functions",
"(",
")",
"and",
"getattr",
"(",
"layer",
",",
"'_keras_style'",
",",
"True",
")",
")",
":",
"with",
"ops",
".",
"init_scope",
"(",
")",
":",
"yield",
"else",
":",
"yield"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/tf_utils.py#L414-L429 | ||
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/build/skia_gold_common/skia_gold_session.py | python | SkiaGoldSession._RunCmdForRcAndOutput | (cmd) | Runs |cmd| and returns its returncode and output.
Args:
cmd: A list containing the command line to run.
Returns:
A tuple (rc, output), where, |rc| is the returncode of the command and
|output| is the stdout + stderr of the command. | Runs |cmd| and returns its returncode and output. | [
"Runs",
"|cmd|",
"and",
"returns",
"its",
"returncode",
"and",
"output",
"."
] | def _RunCmdForRcAndOutput(cmd):
"""Runs |cmd| and returns its returncode and output.
Args:
cmd: A list containing the command line to run.
Returns:
A tuple (rc, output), where, |rc| is the returncode of the command and
|output| is the stdout + stderr of the command.
"""
raise NotImplementedError() | [
"def",
"_RunCmdForRcAndOutput",
"(",
"cmd",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/skia_gold_common/skia_gold_session.py#L542-L552 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/utils.py | python | switch_host_s3_accelerate | (request, operation_name, **kwargs) | Switches the current s3 endpoint with an S3 Accelerate endpoint | Switches the current s3 endpoint with an S3 Accelerate endpoint | [
"Switches",
"the",
"current",
"s3",
"endpoint",
"with",
"an",
"S3",
"Accelerate",
"endpoint"
] | def switch_host_s3_accelerate(request, operation_name, **kwargs):
"""Switches the current s3 endpoint with an S3 Accelerate endpoint"""
# Note that when registered the switching of the s3 host happens
# before it gets changed to virtual. So we are not concerned with ensuring
# that the bucket name is translated to the virtual style here and we
# can hard code the Accelerate endpoint.
parts = urlsplit(request.url).netloc.split('.')
parts = [p for p in parts if p in S3_ACCELERATE_WHITELIST]
endpoint = 'https://s3-accelerate.'
if len(parts) > 0:
endpoint += '.'.join(parts) + '.'
endpoint += 'amazonaws.com'
if operation_name in ['ListBuckets', 'CreateBucket', 'DeleteBucket']:
return
_switch_hosts(request, endpoint, use_new_scheme=False) | [
"def",
"switch_host_s3_accelerate",
"(",
"request",
",",
"operation_name",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note that when registered the switching of the s3 host happens",
"# before it gets changed to virtual. So we are not concerned with ensuring",
"# that the bucket name is translated to the virtual style here and we",
"# can hard code the Accelerate endpoint.",
"parts",
"=",
"urlsplit",
"(",
"request",
".",
"url",
")",
".",
"netloc",
".",
"split",
"(",
"'.'",
")",
"parts",
"=",
"[",
"p",
"for",
"p",
"in",
"parts",
"if",
"p",
"in",
"S3_ACCELERATE_WHITELIST",
"]",
"endpoint",
"=",
"'https://s3-accelerate.'",
"if",
"len",
"(",
"parts",
")",
">",
"0",
":",
"endpoint",
"+=",
"'.'",
".",
"join",
"(",
"parts",
")",
"+",
"'.'",
"endpoint",
"+=",
"'amazonaws.com'",
"if",
"operation_name",
"in",
"[",
"'ListBuckets'",
",",
"'CreateBucket'",
",",
"'DeleteBucket'",
"]",
":",
"return",
"_switch_hosts",
"(",
"request",
",",
"endpoint",
",",
"use_new_scheme",
"=",
"False",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/utils.py#L1061-L1077 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py3/scipy/linalg/decomp_lu.py | python | lu_solve | (lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True) | Solve an equation system, a x = b, given the LU factorization of a
Parameters
----------
(lu, piv)
Factorization of the coefficient matrix a, as given by lu_factor
b : array
Right-hand side
trans : {0, 1, 2}, optional
Type of system to solve:
===== =========
trans system
===== =========
0 a x = b
1 a^T x = b
2 a^H x = b
===== =========
overwrite_b : bool, optional
Whether to overwrite data in b (may increase performance)
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
x : array
Solution to the system
See also
--------
lu_factor : LU factorize a matrix
Examples
--------
>>> from scipy.linalg import lu_factor, lu_solve
>>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
>>> b = np.array([1, 1, 1, 1])
>>> lu, piv = lu_factor(A)
>>> x = lu_solve((lu, piv), b)
>>> np.allclose(A @ x - b, np.zeros((4,)))
True | Solve an equation system, a x = b, given the LU factorization of a | [
"Solve",
"an",
"equation",
"system",
"a",
"x",
"=",
"b",
"given",
"the",
"LU",
"factorization",
"of",
"a"
] | def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):
"""Solve an equation system, a x = b, given the LU factorization of a
Parameters
----------
(lu, piv)
Factorization of the coefficient matrix a, as given by lu_factor
b : array
Right-hand side
trans : {0, 1, 2}, optional
Type of system to solve:
===== =========
trans system
===== =========
0 a x = b
1 a^T x = b
2 a^H x = b
===== =========
overwrite_b : bool, optional
Whether to overwrite data in b (may increase performance)
check_finite : bool, optional
Whether to check that the input matrices contain only finite numbers.
Disabling may give a performance gain, but may result in problems
(crashes, non-termination) if the inputs do contain infinities or NaNs.
Returns
-------
x : array
Solution to the system
See also
--------
lu_factor : LU factorize a matrix
Examples
--------
>>> from scipy.linalg import lu_factor, lu_solve
>>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
>>> b = np.array([1, 1, 1, 1])
>>> lu, piv = lu_factor(A)
>>> x = lu_solve((lu, piv), b)
>>> np.allclose(A @ x - b, np.zeros((4,)))
True
"""
(lu, piv) = lu_and_piv
if check_finite:
b1 = asarray_chkfinite(b)
else:
b1 = asarray(b)
overwrite_b = overwrite_b or _datacopied(b1, b)
if lu.shape[0] != b1.shape[0]:
raise ValueError("incompatible dimensions.")
getrs, = get_lapack_funcs(('getrs',), (lu, b1))
x, info = getrs(lu, piv, b1, trans=trans, overwrite_b=overwrite_b)
if info == 0:
return x
raise ValueError('illegal value in %d-th argument of internal gesv|posv'
% -info) | [
"def",
"lu_solve",
"(",
"lu_and_piv",
",",
"b",
",",
"trans",
"=",
"0",
",",
"overwrite_b",
"=",
"False",
",",
"check_finite",
"=",
"True",
")",
":",
"(",
"lu",
",",
"piv",
")",
"=",
"lu_and_piv",
"if",
"check_finite",
":",
"b1",
"=",
"asarray_chkfinite",
"(",
"b",
")",
"else",
":",
"b1",
"=",
"asarray",
"(",
"b",
")",
"overwrite_b",
"=",
"overwrite_b",
"or",
"_datacopied",
"(",
"b1",
",",
"b",
")",
"if",
"lu",
".",
"shape",
"[",
"0",
"]",
"!=",
"b1",
".",
"shape",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"incompatible dimensions.\"",
")",
"getrs",
",",
"=",
"get_lapack_funcs",
"(",
"(",
"'getrs'",
",",
")",
",",
"(",
"lu",
",",
"b1",
")",
")",
"x",
",",
"info",
"=",
"getrs",
"(",
"lu",
",",
"piv",
",",
"b1",
",",
"trans",
"=",
"trans",
",",
"overwrite_b",
"=",
"overwrite_b",
")",
"if",
"info",
"==",
"0",
":",
"return",
"x",
"raise",
"ValueError",
"(",
"'illegal value in %d-th argument of internal gesv|posv'",
"%",
"-",
"info",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/linalg/decomp_lu.py#L90-L150 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/contrib/sparsity/asp.py | python | ASPHelper.prune_model | (cls,
place,
main_program=None,
n=2,
m=4,
mask_algo=sparsity.MaskAlgo.MASK_1D,
with_mask=True) | return asp_info.masks.copy() | r"""
This is the implementation of `sparsity.prune_model`, for details please see explanation in `sparsity.prune_model`. | r"""
This is the implementation of `sparsity.prune_model`, for details please see explanation in `sparsity.prune_model`. | [
"r",
"This",
"is",
"the",
"implementation",
"of",
"sparsity",
".",
"prune_model",
"for",
"details",
"please",
"see",
"explanation",
"in",
"sparsity",
".",
"prune_model",
"."
] | def prune_model(cls,
place,
main_program=None,
n=2,
m=4,
mask_algo=sparsity.MaskAlgo.MASK_1D,
with_mask=True):
r"""
This is the implementation of `sparsity.prune_model`, for details please see explanation in `sparsity.prune_model`.
"""
checked_func_name = sparsity.CheckMethod.get_checking_method(mask_algo)
if main_program is None:
main_program = paddle.static.default_main_program()
asp_info = cls._get_program_asp_info(main_program)
for param in main_program.global_block().all_parameters():
if ASPHelper._is_supported_layer(main_program, param.name):
weight_tensor = global_scope().find_var(param.name).get_tensor()
weight_nparray = np.array(weight_tensor)
# The double transpose ops here make sure pruning direction consistent with cuSparseLt.
# SPMMA in cuSparseLt: D = (AxB) + C, where matrix A (mxk) is sparse matrix.
# cuSparseLt would prune matrix A along k dimension.
# In sparse training, layer weight matriices is viewed sparse matrix A, so
# the math fomula should be 'Act(WX + b)'. However, default fomula in PaddlePaddle
# is 'Act(XW + b)'. For enabling SPMMA, weights and inputs should be transposed
# for computing, Act( (W^T X^T)^T + b). Therefore, we have to prune alog k dimension
# of W^T, which is m dimension of W. Moreove, all mask generating functions in
# sparsity/utils is row-major pruning. That is the reason we have to transpose weight
# matrices beforce invoking create_mask. Then we transpose the result maks to make
# sure its shape to be the same as the input weight.
weight_sparse_mask = sparsity.create_mask(
weight_nparray.T, func_name=mask_algo, n=n, m=m).T
weight_pruned_nparray = np.multiply(weight_nparray,
weight_sparse_mask)
weight_tensor.set(weight_pruned_nparray, place)
assert sparsity.check_sparsity(weight_pruned_nparray.T, n=n, m=m, func_name=checked_func_name), \
'Pruning {} weight matrix failure!!!'.format(param.name)
if with_mask:
weight_mask_param = global_scope().find_var(
ASPHelper._get_mask_name(param.name))
assert weight_mask_param is not None, \
'Cannot find {} variable, please call ASPHelper.minimize' \
' and initialization (exe.run(startup_program)) first!'.format(ASPHelper._get_mask_name(param.name))
weight_mask_tensor = weight_mask_param.get_tensor()
weight_mask_tensor.set(weight_sparse_mask, place)
asp_info.update_masks(param.name, weight_sparse_mask)
return asp_info.masks.copy() | [
"def",
"prune_model",
"(",
"cls",
",",
"place",
",",
"main_program",
"=",
"None",
",",
"n",
"=",
"2",
",",
"m",
"=",
"4",
",",
"mask_algo",
"=",
"sparsity",
".",
"MaskAlgo",
".",
"MASK_1D",
",",
"with_mask",
"=",
"True",
")",
":",
"checked_func_name",
"=",
"sparsity",
".",
"CheckMethod",
".",
"get_checking_method",
"(",
"mask_algo",
")",
"if",
"main_program",
"is",
"None",
":",
"main_program",
"=",
"paddle",
".",
"static",
".",
"default_main_program",
"(",
")",
"asp_info",
"=",
"cls",
".",
"_get_program_asp_info",
"(",
"main_program",
")",
"for",
"param",
"in",
"main_program",
".",
"global_block",
"(",
")",
".",
"all_parameters",
"(",
")",
":",
"if",
"ASPHelper",
".",
"_is_supported_layer",
"(",
"main_program",
",",
"param",
".",
"name",
")",
":",
"weight_tensor",
"=",
"global_scope",
"(",
")",
".",
"find_var",
"(",
"param",
".",
"name",
")",
".",
"get_tensor",
"(",
")",
"weight_nparray",
"=",
"np",
".",
"array",
"(",
"weight_tensor",
")",
"# The double transpose ops here make sure pruning direction consistent with cuSparseLt.",
"# SPMMA in cuSparseLt: D = (AxB) + C, where matrix A (mxk) is sparse matrix.",
"# cuSparseLt would prune matrix A along k dimension.",
"# In sparse training, layer weight matriices is viewed sparse matrix A, so",
"# the math fomula should be 'Act(WX + b)'. However, default fomula in PaddlePaddle",
"# is 'Act(XW + b)'. For enabling SPMMA, weights and inputs should be transposed ",
"# for computing, Act( (W^T X^T)^T + b). Therefore, we have to prune alog k dimension ",
"# of W^T, which is m dimension of W. Moreove, all mask generating functions in ",
"# sparsity/utils is row-major pruning. That is the reason we have to transpose weight ",
"# matrices beforce invoking create_mask. Then we transpose the result maks to make ",
"# sure its shape to be the same as the input weight.",
"weight_sparse_mask",
"=",
"sparsity",
".",
"create_mask",
"(",
"weight_nparray",
".",
"T",
",",
"func_name",
"=",
"mask_algo",
",",
"n",
"=",
"n",
",",
"m",
"=",
"m",
")",
".",
"T",
"weight_pruned_nparray",
"=",
"np",
".",
"multiply",
"(",
"weight_nparray",
",",
"weight_sparse_mask",
")",
"weight_tensor",
".",
"set",
"(",
"weight_pruned_nparray",
",",
"place",
")",
"assert",
"sparsity",
".",
"check_sparsity",
"(",
"weight_pruned_nparray",
".",
"T",
",",
"n",
"=",
"n",
",",
"m",
"=",
"m",
",",
"func_name",
"=",
"checked_func_name",
")",
",",
"'Pruning {} weight matrix failure!!!'",
".",
"format",
"(",
"param",
".",
"name",
")",
"if",
"with_mask",
":",
"weight_mask_param",
"=",
"global_scope",
"(",
")",
".",
"find_var",
"(",
"ASPHelper",
".",
"_get_mask_name",
"(",
"param",
".",
"name",
")",
")",
"assert",
"weight_mask_param",
"is",
"not",
"None",
",",
"'Cannot find {} variable, please call ASPHelper.minimize'",
"' and initialization (exe.run(startup_program)) first!'",
".",
"format",
"(",
"ASPHelper",
".",
"_get_mask_name",
"(",
"param",
".",
"name",
")",
")",
"weight_mask_tensor",
"=",
"weight_mask_param",
".",
"get_tensor",
"(",
")",
"weight_mask_tensor",
".",
"set",
"(",
"weight_sparse_mask",
",",
"place",
")",
"asp_info",
".",
"update_masks",
"(",
"param",
".",
"name",
",",
"weight_sparse_mask",
")",
"return",
"asp_info",
".",
"masks",
".",
"copy",
"(",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/sparsity/asp.py#L326-L374 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/six.py | python | _SixMetaPathImporter.is_package | (self, fullname) | return hasattr(self.__get_module(fullname), "__path__") | Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451) | Return true, if the named module is a package. | [
"Return",
"true",
"if",
"the",
"named",
"module",
"is",
"a",
"package",
"."
] | def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__") | [
"def",
"is_package",
"(",
"self",
",",
"fullname",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"__get_module",
"(",
"fullname",
")",
",",
"\"__path__\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/six.py#L209-L216 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/decimal.py | python | Decimal.ln | (self, context=None) | return ans | Returns the natural (base e) logarithm of self. | Returns the natural (base e) logarithm of self. | [
"Returns",
"the",
"natural",
"(",
"base",
"e",
")",
"logarithm",
"of",
"self",
"."
] | def ln(self, context=None):
"""Returns the natural (base e) logarithm of self."""
if context is None:
context = getcontext()
# ln(NaN) = NaN
ans = self._check_nans(context=context)
if ans:
return ans
# ln(0.0) == -Infinity
if not self:
return _NegativeInfinity
# ln(Infinity) = Infinity
if self._isinfinity() == 1:
return _Infinity
# ln(1.0) == 0.0
if self == _One:
return _Zero
# ln(negative) raises InvalidOperation
if self._sign == 1:
return context._raise_error(InvalidOperation,
'ln of a negative value')
# result is irrational, so necessarily inexact
op = _WorkRep(self)
c, e = op.int, op.exp
p = context.prec
# correctly rounded result: repeatedly increase precision by 3
# until we get an unambiguously roundable result
places = p - self._ln_exp_bound() + 2 # at least p+3 places
while True:
coeff = _dlog(c, e, places)
# assert len(str(abs(coeff)))-p >= 1
if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
break
places += 3
ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
context = context._shallow_copy()
rounding = context._set_rounding(ROUND_HALF_EVEN)
ans = ans._fix(context)
context.rounding = rounding
return ans | [
"def",
"ln",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"getcontext",
"(",
")",
"# ln(NaN) = NaN",
"ans",
"=",
"self",
".",
"_check_nans",
"(",
"context",
"=",
"context",
")",
"if",
"ans",
":",
"return",
"ans",
"# ln(0.0) == -Infinity",
"if",
"not",
"self",
":",
"return",
"_NegativeInfinity",
"# ln(Infinity) = Infinity",
"if",
"self",
".",
"_isinfinity",
"(",
")",
"==",
"1",
":",
"return",
"_Infinity",
"# ln(1.0) == 0.0",
"if",
"self",
"==",
"_One",
":",
"return",
"_Zero",
"# ln(negative) raises InvalidOperation",
"if",
"self",
".",
"_sign",
"==",
"1",
":",
"return",
"context",
".",
"_raise_error",
"(",
"InvalidOperation",
",",
"'ln of a negative value'",
")",
"# result is irrational, so necessarily inexact",
"op",
"=",
"_WorkRep",
"(",
"self",
")",
"c",
",",
"e",
"=",
"op",
".",
"int",
",",
"op",
".",
"exp",
"p",
"=",
"context",
".",
"prec",
"# correctly rounded result: repeatedly increase precision by 3",
"# until we get an unambiguously roundable result",
"places",
"=",
"p",
"-",
"self",
".",
"_ln_exp_bound",
"(",
")",
"+",
"2",
"# at least p+3 places",
"while",
"True",
":",
"coeff",
"=",
"_dlog",
"(",
"c",
",",
"e",
",",
"places",
")",
"# assert len(str(abs(coeff)))-p >= 1",
"if",
"coeff",
"%",
"(",
"5",
"*",
"10",
"**",
"(",
"len",
"(",
"str",
"(",
"abs",
"(",
"coeff",
")",
")",
")",
"-",
"p",
"-",
"1",
")",
")",
":",
"break",
"places",
"+=",
"3",
"ans",
"=",
"_dec_from_triple",
"(",
"int",
"(",
"coeff",
"<",
"0",
")",
",",
"str",
"(",
"abs",
"(",
"coeff",
")",
")",
",",
"-",
"places",
")",
"context",
"=",
"context",
".",
"_shallow_copy",
"(",
")",
"rounding",
"=",
"context",
".",
"_set_rounding",
"(",
"ROUND_HALF_EVEN",
")",
"ans",
"=",
"ans",
".",
"_fix",
"(",
"context",
")",
"context",
".",
"rounding",
"=",
"rounding",
"return",
"ans"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L2932-L2980 | |
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/chigger/RenderWindow.py | python | RenderWindow.getActive | (self) | return self.__active | Return the active result object. | Return the active result object. | [
"Return",
"the",
"active",
"result",
"object",
"."
] | def getActive(self):
"""
Return the active result object.
"""
return self.__active | [
"def",
"getActive",
"(",
"self",
")",
":",
"return",
"self",
".",
"__active"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/RenderWindow.py#L159-L163 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py | python | ValidCtxt.validateOneNamespace | (self, doc, elem, prefix, ns, value) | return ret | Try to validate a single namespace declaration for an
element basically it does the following checks as described
by the XML-1.0 recommendation: - [ VC: Attribute Value Type
] - [ VC: Fixed Attribute Default ] - [ VC: Entity Name ] -
[ VC: Name Token ] - [ VC: ID ] - [ VC: IDREF ] - [ VC:
Entity Name ] - [ VC: Notation Attributes ] The ID/IDREF
uniqueness and matching are done separately | Try to validate a single namespace declaration for an
element basically it does the following checks as described
by the XML-1.0 recommendation: - [ VC: Attribute Value Type
] - [ VC: Fixed Attribute Default ] - [ VC: Entity Name ] -
[ VC: Name Token ] - [ VC: ID ] - [ VC: IDREF ] - [ VC:
Entity Name ] - [ VC: Notation Attributes ] The ID/IDREF
uniqueness and matching are done separately | [
"Try",
"to",
"validate",
"a",
"single",
"namespace",
"declaration",
"for",
"an",
"element",
"basically",
"it",
"does",
"the",
"following",
"checks",
"as",
"described",
"by",
"the",
"XML",
"-",
"1",
".",
"0",
"recommendation",
":",
"-",
"[",
"VC",
":",
"Attribute",
"Value",
"Type",
"]",
"-",
"[",
"VC",
":",
"Fixed",
"Attribute",
"Default",
"]",
"-",
"[",
"VC",
":",
"Entity",
"Name",
"]",
"-",
"[",
"VC",
":",
"Name",
"Token",
"]",
"-",
"[",
"VC",
":",
"ID",
"]",
"-",
"[",
"VC",
":",
"IDREF",
"]",
"-",
"[",
"VC",
":",
"Entity",
"Name",
"]",
"-",
"[",
"VC",
":",
"Notation",
"Attributes",
"]",
"The",
"ID",
"/",
"IDREF",
"uniqueness",
"and",
"matching",
"are",
"done",
"separately"
] | def validateOneNamespace(self, doc, elem, prefix, ns, value):
"""Try to validate a single namespace declaration for an
element basically it does the following checks as described
by the XML-1.0 recommendation: - [ VC: Attribute Value Type
] - [ VC: Fixed Attribute Default ] - [ VC: Entity Name ] -
[ VC: Name Token ] - [ VC: ID ] - [ VC: IDREF ] - [ VC:
Entity Name ] - [ VC: Notation Attributes ] The ID/IDREF
uniqueness and matching are done separately """
if doc is None: doc__o = None
else: doc__o = doc._o
if elem is None: elem__o = None
else: elem__o = elem._o
if ns is None: ns__o = None
else: ns__o = ns._o
ret = libxml2mod.xmlValidateOneNamespace(self._o, doc__o, elem__o, prefix, ns__o, value)
return ret | [
"def",
"validateOneNamespace",
"(",
"self",
",",
"doc",
",",
"elem",
",",
"prefix",
",",
"ns",
",",
"value",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc__o",
"=",
"None",
"else",
":",
"doc__o",
"=",
"doc",
".",
"_o",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
":",
"elem__o",
"=",
"elem",
".",
"_o",
"if",
"ns",
"is",
"None",
":",
"ns__o",
"=",
"None",
"else",
":",
"ns__o",
"=",
"ns",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlValidateOneNamespace",
"(",
"self",
".",
"_o",
",",
"doc__o",
",",
"elem__o",
",",
"prefix",
",",
"ns__o",
",",
"value",
")",
"return",
"ret"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L7205-L7220 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/utils/parallel.py | python | _map_multithread | (func, iterable, chunksize=1) | Chop iterable into chunks and submit them to a thread pool.
For very long iterables using a large value for chunksize can make
the job complete much faster than using the default value of 1.
Return an unordered iterator of the results. | Chop iterable into chunks and submit them to a thread pool. | [
"Chop",
"iterable",
"into",
"chunks",
"and",
"submit",
"them",
"to",
"a",
"thread",
"pool",
"."
] | def _map_multithread(func, iterable, chunksize=1):
# type: (Callable[[S], T], Iterable[S], int) -> Iterator[T]
"""Chop iterable into chunks and submit them to a thread pool.
For very long iterables using a large value for chunksize can make
the job complete much faster than using the default value of 1.
Return an unordered iterator of the results.
"""
with closing(ThreadPool(DEFAULT_POOLSIZE)) as pool:
return pool.imap_unordered(func, iterable, chunksize) | [
"def",
"_map_multithread",
"(",
"func",
",",
"iterable",
",",
"chunksize",
"=",
"1",
")",
":",
"# type: (Callable[[S], T], Iterable[S], int) -> Iterator[T]",
"with",
"closing",
"(",
"ThreadPool",
"(",
"DEFAULT_POOLSIZE",
")",
")",
"as",
"pool",
":",
"return",
"pool",
".",
"imap_unordered",
"(",
"func",
",",
"iterable",
",",
"chunksize",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/utils/parallel.py#L88-L98 | ||
leanprover/lean | 72a965986fa5aeae54062e98efb3140b2c4e79fd | src/cmake/Modules/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/leanprover/lean/blob/72a965986fa5aeae54062e98efb3140b2c4e79fd/src/cmake/Modules/cpplint.py#L1076-L1078 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/api.py | python | post | (url, data=None, json=None, **kwargs) | return request('post', url, data=data, json=json, **kwargs) | r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response | r"""Sends a POST request. | [
"r",
"Sends",
"a",
"POST",
"request",
"."
] | def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs) | [
"def",
"post",
"(",
"url",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"request",
"(",
"'post'",
",",
"url",
",",
"data",
"=",
"data",
",",
"json",
"=",
"json",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/api.py#L107-L119 | |
RamadhanAmizudin/malware | 2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1 | Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py | python | EmacsMode.kill_region | (self, e) | Kill the text in the current region. By default, this command is unbound. | Kill the text in the current region. By default, this command is unbound. | [
"Kill",
"the",
"text",
"in",
"the",
"current",
"region",
".",
"By",
"default",
"this",
"command",
"is",
"unbound",
"."
] | def kill_region(self, e): # ()
'''Kill the text in the current region. By default, this command is unbound. '''
pass | [
"def",
"kill_region",
"(",
"self",
",",
"e",
")",
":",
"# ()",
"pass"
] | https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/Fuzzbunch/fuzzbunch/pyreadline/modes/emacs.py#L344-L346 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | DateSpan.GetWeeks | (*args, **kwargs) | return _misc_.DateSpan_GetWeeks(*args, **kwargs) | GetWeeks(self) -> int | GetWeeks(self) -> int | [
"GetWeeks",
"(",
"self",
")",
"-",
">",
"int"
] | def GetWeeks(*args, **kwargs):
"""GetWeeks(self) -> int"""
return _misc_.DateSpan_GetWeeks(*args, **kwargs) | [
"def",
"GetWeeks",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_GetWeeks",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4677-L4679 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/compiler/tensorrt/trt_convert.py | python | _to_string | (s) | return s | Decode s if it is a sequence of bytes. | Decode s if it is a sequence of bytes. | [
"Decode",
"s",
"if",
"it",
"is",
"a",
"sequence",
"of",
"bytes",
"."
] | def _to_string(s):
"""Decode s if it is a sequence of bytes."""
if isinstance(s, _six.binary_type):
return s.decode("utf-8")
return s | [
"def",
"_to_string",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"_six",
".",
"binary_type",
")",
":",
"return",
"s",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"s"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/compiler/tensorrt/trt_convert.py#L89-L93 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | third_party/Python/module/pexpect-4.6/pexpect/screen.py | python | screen.cursor_constrain | (self) | This keeps the cursor within the screen area. | This keeps the cursor within the screen area. | [
"This",
"keeps",
"the",
"cursor",
"within",
"the",
"screen",
"area",
"."
] | def cursor_constrain (self):
'''This keeps the cursor within the screen area.
'''
self.cur_r = constrain (self.cur_r, 1, self.rows)
self.cur_c = constrain (self.cur_c, 1, self.cols) | [
"def",
"cursor_constrain",
"(",
"self",
")",
":",
"self",
".",
"cur_r",
"=",
"constrain",
"(",
"self",
".",
"cur_r",
",",
"1",
",",
"self",
".",
"rows",
")",
"self",
".",
"cur_c",
"=",
"constrain",
"(",
"self",
".",
"cur_c",
",",
"1",
",",
"self",
".",
"cols",
")"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L273-L278 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/listobj.py | python | ListInstance.move | (self, dest_idx, src_idx, count) | Move `count` elements from `src_idx` to `dest_idx`. | Move `count` elements from `src_idx` to `dest_idx`. | [
"Move",
"count",
"elements",
"from",
"src_idx",
"to",
"dest_idx",
"."
] | def move(self, dest_idx, src_idx, count):
"""
Move `count` elements from `src_idx` to `dest_idx`.
"""
dest_ptr = self._gep(dest_idx)
src_ptr = self._gep(src_idx)
cgutils.raw_memmove(self._builder, dest_ptr, src_ptr,
count, itemsize=self._itemsize)
self.set_dirty(True) | [
"def",
"move",
"(",
"self",
",",
"dest_idx",
",",
"src_idx",
",",
"count",
")",
":",
"dest_ptr",
"=",
"self",
".",
"_gep",
"(",
"dest_idx",
")",
"src_ptr",
"=",
"self",
".",
"_gep",
"(",
"src_idx",
")",
"cgutils",
".",
"raw_memmove",
"(",
"self",
".",
"_builder",
",",
"dest_ptr",
",",
"src_ptr",
",",
"count",
",",
"itemsize",
"=",
"self",
".",
"_itemsize",
")",
"self",
".",
"set_dirty",
"(",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/listobj.py#L396-L405 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py | python | _OneHotColumn.key | (self) | return "{}".format(self) | Returns a string which will be used as a key when we do sorting. | Returns a string which will be used as a key when we do sorting. | [
"Returns",
"a",
"string",
"which",
"will",
"be",
"used",
"as",
"a",
"key",
"when",
"we",
"do",
"sorting",
"."
] | def key(self):
"""Returns a string which will be used as a key when we do sorting."""
return "{}".format(self) | [
"def",
"key",
"(",
"self",
")",
":",
"return",
"\"{}\"",
".",
"format",
"(",
"self",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py#L944-L946 | |
lyxok1/Tiny-DSOD | 94d15450699bea0dd3720e75e2d273e476174fba | scripts/cpp_lint.py | python | CheckForNonStandardConstructs | (filename, clean_lines, linenum,
nesting_state, error) | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | [
"r",
"Logs",
"an",
"error",
"if",
"we",
"see",
"certain",
"non",
"-",
"ANSI",
"constructs",
"ignored",
"by",
"gcc",
"-",
"2",
"."
] | def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A _NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage class (static, extern, typedef, etc) should be first.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
% re.escape(base_classname),
line)
if (args and
args.group(1) != 'void' and
not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), args.group(1).strip())):
error(filename, linenum, 'runtime/explicit', 5,
'Single-argument constructors should be marked explicit.') | [
"def",
"CheckForNonStandardConstructs",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Remove comments from the line, but leave in strings for now.",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%[-+ ]?\\d*q'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"3",
",",
"'%q in format strings is deprecated. Use %ll instead.'",
")",
"if",
"Search",
"(",
"r'printf\\s*\\(.*\".*%\\d+\\$'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf_format'",
",",
"2",
",",
"'%N$ formats are unconventional. Try rewriting to avoid them.'",
")",
"# Remove escaped backslashes before looking for undefined escapes.",
"line",
"=",
"line",
".",
"replace",
"(",
"'\\\\\\\\'",
",",
"''",
")",
"if",
"Search",
"(",
"r'(\"|\\').*\\\\(%|\\[|\\(|{)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/printf_format'",
",",
"3",
",",
"'%, [, (, and { are undefined character escapes. Unescape them.'",
")",
"# For the rest, work with both comments and strings removed.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"Search",
"(",
"r'\\b(const|volatile|void|char|short|int|long'",
"r'|float|double|signed|unsigned'",
"r'|schar|u?int8|u?int16|u?int32|u?int64)'",
"r'\\s+(register|static|extern|typedef)\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/storage_class'",
",",
"5",
",",
"'Storage class (static, extern, typedef, etc) should be first.'",
")",
"if",
"Match",
"(",
"r'\\s*#\\s*endif\\s*[^/\\s]+'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/endif_comment'",
",",
"5",
",",
"'Uncommented text after #endif is non-standard. Use a comment.'",
")",
"if",
"Match",
"(",
"r'\\s*class\\s+(\\w+\\s*::\\s*)+\\w+\\s*;'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/forward_decl'",
",",
"5",
",",
"'Inner-style forward declarations are invalid. Remove this line.'",
")",
"if",
"Search",
"(",
"r'(\\w+|[+-]?\\d+(\\.\\d*)?)\\s*(<|>)\\?=?\\s*(\\w+|[+-]?\\d+)(\\.\\d*)?'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/deprecated'",
",",
"3",
",",
"'>? and <? (max and min) operators are non-standard and deprecated.'",
")",
"if",
"Search",
"(",
"r'^\\s*const\\s*string\\s*&\\s*\\w+\\s*;'",
",",
"line",
")",
":",
"# TODO(unknown): Could it be expanded safely to arbitrary references,",
"# without triggering too many false positives? The first",
"# attempt triggered 5 warnings for mostly benign code in the regtest, hence",
"# the restriction.",
"# Here's the original regexp, for the reference:",
"# type_name = r'\\w+((\\s*::\\s*\\w+)|(\\s*<\\s*\\w+?\\s*>))?'",
"# r'\\s*const\\s*' + type_name + '\\s*&\\s*\\w+\\s*;'",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/member_string_references'",
",",
"2",
",",
"'const string& members are dangerous. It is much better to use '",
"'alternatives, such as pointers or simple constants.'",
")",
"# Everything else in this function operates on class declarations.",
"# Return early if the top of the nesting stack is not a class, or if",
"# the class head is not completed yet.",
"classinfo",
"=",
"nesting_state",
".",
"InnermostClass",
"(",
")",
"if",
"not",
"classinfo",
"or",
"not",
"classinfo",
".",
"seen_open_brace",
":",
"return",
"# The class may have been declared with namespace or classname qualifiers.",
"# The constructor and destructor will not have those qualifiers.",
"base_classname",
"=",
"classinfo",
".",
"name",
".",
"split",
"(",
"'::'",
")",
"[",
"-",
"1",
"]",
"# Look for single-argument constructors that aren't marked explicit.",
"# Technically a valid construct, but against style.",
"args",
"=",
"Match",
"(",
"r'\\s+(?:inline\\s+)?%s\\s*\\(([^,()]+)\\)'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"line",
")",
"if",
"(",
"args",
"and",
"args",
".",
"group",
"(",
"1",
")",
"!=",
"'void'",
"and",
"not",
"Match",
"(",
"r'(const\\s+)?%s(\\s+const)?\\s*(?:<\\w+>\\s*)?&'",
"%",
"re",
".",
"escape",
"(",
"base_classname",
")",
",",
"args",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/explicit'",
",",
"5",
",",
"'Single-argument constructors should be marked explicit.'",
")"
] | https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/scripts/cpp_lint.py#L2198-L2302 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_controls.py | python | SearchCtrl.IsCancelButtonVisible | (*args, **kwargs) | return _controls_.SearchCtrl_IsCancelButtonVisible(*args, **kwargs) | IsCancelButtonVisible(self) -> bool
Indicates whether the cancel button is visible. | IsCancelButtonVisible(self) -> bool | [
"IsCancelButtonVisible",
"(",
"self",
")",
"-",
">",
"bool"
] | def IsCancelButtonVisible(*args, **kwargs):
"""
IsCancelButtonVisible(self) -> bool
Indicates whether the cancel button is visible.
"""
return _controls_.SearchCtrl_IsCancelButtonVisible(*args, **kwargs) | [
"def",
"IsCancelButtonVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"SearchCtrl_IsCancelButtonVisible",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L7545-L7551 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/platform.py | python | system_alias | (system, release, version) | return system, release, version | Returns (system, release, version) aliased to common
marketing names used for some systems.
It also does some reordering of the information in some cases
where it would otherwise cause confusion. | Returns (system, release, version) aliased to common
marketing names used for some systems. | [
"Returns",
"(",
"system",
"release",
"version",
")",
"aliased",
"to",
"common",
"marketing",
"names",
"used",
"for",
"some",
"systems",
"."
] | def system_alias(system, release, version):
""" Returns (system, release, version) aliased to common
marketing names used for some systems.
It also does some reordering of the information in some cases
where it would otherwise cause confusion.
"""
if system == 'Rhapsody':
# Apple's BSD derivative
# XXX How can we determine the marketing release number ?
return 'MacOS X Server', system+release, version
elif system == 'SunOS':
# Sun's OS
if release < '5':
# These releases use the old name SunOS
return system, release, version
# Modify release (marketing release = SunOS release - 3)
l = release.split('.')
if l:
try:
major = int(l[0])
except ValueError:
pass
else:
major = major - 3
l[0] = str(major)
release = '.'.join(l)
if release < '6':
system = 'Solaris'
else:
# XXX Whatever the new SunOS marketing name is...
system = 'Solaris'
elif system == 'IRIX64':
# IRIX reports IRIX64 on platforms with 64-bit support; yet it
# is really a version and not a different platform, since 32-bit
# apps are also supported..
system = 'IRIX'
if version:
version = version + ' (64bit)'
else:
version = '64bit'
elif system in ('win32', 'win16'):
# In case one of the other tricks
system = 'Windows'
return system, release, version | [
"def",
"system_alias",
"(",
"system",
",",
"release",
",",
"version",
")",
":",
"if",
"system",
"==",
"'Rhapsody'",
":",
"# Apple's BSD derivative",
"# XXX How can we determine the marketing release number ?",
"return",
"'MacOS X Server'",
",",
"system",
"+",
"release",
",",
"version",
"elif",
"system",
"==",
"'SunOS'",
":",
"# Sun's OS",
"if",
"release",
"<",
"'5'",
":",
"# These releases use the old name SunOS",
"return",
"system",
",",
"release",
",",
"version",
"# Modify release (marketing release = SunOS release - 3)",
"l",
"=",
"release",
".",
"split",
"(",
"'.'",
")",
"if",
"l",
":",
"try",
":",
"major",
"=",
"int",
"(",
"l",
"[",
"0",
"]",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"major",
"=",
"major",
"-",
"3",
"l",
"[",
"0",
"]",
"=",
"str",
"(",
"major",
")",
"release",
"=",
"'.'",
".",
"join",
"(",
"l",
")",
"if",
"release",
"<",
"'6'",
":",
"system",
"=",
"'Solaris'",
"else",
":",
"# XXX Whatever the new SunOS marketing name is...",
"system",
"=",
"'Solaris'",
"elif",
"system",
"==",
"'IRIX64'",
":",
"# IRIX reports IRIX64 on platforms with 64-bit support; yet it",
"# is really a version and not a different platform, since 32-bit",
"# apps are also supported..",
"system",
"=",
"'IRIX'",
"if",
"version",
":",
"version",
"=",
"version",
"+",
"' (64bit)'",
"else",
":",
"version",
"=",
"'64bit'",
"elif",
"system",
"in",
"(",
"'win32'",
",",
"'win16'",
")",
":",
"# In case one of the other tricks",
"system",
"=",
"'Windows'",
"return",
"system",
",",
"release",
",",
"version"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/platform.py#L668-L718 | |
jackaudio/jack2 | 21b293dbc37d42446141a08922cdec0d2550c6a0 | waflib/Tools/msvc.py | python | find_msvc | (conf) | Due to path format limitations, limit operation only to native Win32. Yeah it sucks. | Due to path format limitations, limit operation only to native Win32. Yeah it sucks. | [
"Due",
"to",
"path",
"format",
"limitations",
"limit",
"operation",
"only",
"to",
"native",
"Win32",
".",
"Yeah",
"it",
"sucks",
"."
] | def find_msvc(conf):
"""Due to path format limitations, limit operation only to native Win32. Yeah it sucks."""
if sys.platform == 'cygwin':
conf.fatal('MSVC module does not work under cygwin Python!')
# the autodetection is supposed to be performed before entering in this method
v = conf.env
path = v.PATH
compiler = v.MSVC_COMPILER
version = v.MSVC_VERSION
compiler_name, linker_name, lib_name = _get_prog_names(conf, compiler)
v.MSVC_MANIFEST = (compiler == 'msvc' and version >= 8) or (compiler == 'wsdk' and version >= 6) or (compiler == 'intel' and version >= 11)
# compiler
cxx = conf.find_program(compiler_name, var='CXX', path_list=path)
# before setting anything, check if the compiler is really msvc
env = dict(conf.environ)
if path:
env.update(PATH = ';'.join(path))
if not conf.cmd_and_log(cxx + ['/nologo', '/help'], env=env):
conf.fatal('the msvc compiler could not be identified')
# c/c++ compiler
v.CC = v.CXX = cxx
v.CC_NAME = v.CXX_NAME = 'msvc'
# linker
if not v.LINK_CXX:
conf.find_program(linker_name, path_list=path, errmsg='%s was not found (linker)' % linker_name, var='LINK_CXX')
if not v.LINK_CC:
v.LINK_CC = v.LINK_CXX
# staticlib linker
if not v.AR:
stliblink = conf.find_program(lib_name, path_list=path, var='AR')
if not stliblink:
return
v.ARFLAGS = ['/nologo']
# manifest tool. Not required for VS 2003 and below. Must have for VS 2005 and later
if v.MSVC_MANIFEST:
conf.find_program('MT', path_list=path, var='MT')
v.MTFLAGS = ['/nologo']
try:
conf.load('winres')
except Errors.ConfigurationError:
Logs.warn('Resource compiler not found. Compiling resource file is disabled') | [
"def",
"find_msvc",
"(",
"conf",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"conf",
".",
"fatal",
"(",
"'MSVC module does not work under cygwin Python!'",
")",
"# the autodetection is supposed to be performed before entering in this method",
"v",
"=",
"conf",
".",
"env",
"path",
"=",
"v",
".",
"PATH",
"compiler",
"=",
"v",
".",
"MSVC_COMPILER",
"version",
"=",
"v",
".",
"MSVC_VERSION",
"compiler_name",
",",
"linker_name",
",",
"lib_name",
"=",
"_get_prog_names",
"(",
"conf",
",",
"compiler",
")",
"v",
".",
"MSVC_MANIFEST",
"=",
"(",
"compiler",
"==",
"'msvc'",
"and",
"version",
">=",
"8",
")",
"or",
"(",
"compiler",
"==",
"'wsdk'",
"and",
"version",
">=",
"6",
")",
"or",
"(",
"compiler",
"==",
"'intel'",
"and",
"version",
">=",
"11",
")",
"# compiler",
"cxx",
"=",
"conf",
".",
"find_program",
"(",
"compiler_name",
",",
"var",
"=",
"'CXX'",
",",
"path_list",
"=",
"path",
")",
"# before setting anything, check if the compiler is really msvc",
"env",
"=",
"dict",
"(",
"conf",
".",
"environ",
")",
"if",
"path",
":",
"env",
".",
"update",
"(",
"PATH",
"=",
"';'",
".",
"join",
"(",
"path",
")",
")",
"if",
"not",
"conf",
".",
"cmd_and_log",
"(",
"cxx",
"+",
"[",
"'/nologo'",
",",
"'/help'",
"]",
",",
"env",
"=",
"env",
")",
":",
"conf",
".",
"fatal",
"(",
"'the msvc compiler could not be identified'",
")",
"# c/c++ compiler",
"v",
".",
"CC",
"=",
"v",
".",
"CXX",
"=",
"cxx",
"v",
".",
"CC_NAME",
"=",
"v",
".",
"CXX_NAME",
"=",
"'msvc'",
"# linker",
"if",
"not",
"v",
".",
"LINK_CXX",
":",
"conf",
".",
"find_program",
"(",
"linker_name",
",",
"path_list",
"=",
"path",
",",
"errmsg",
"=",
"'%s was not found (linker)'",
"%",
"linker_name",
",",
"var",
"=",
"'LINK_CXX'",
")",
"if",
"not",
"v",
".",
"LINK_CC",
":",
"v",
".",
"LINK_CC",
"=",
"v",
".",
"LINK_CXX",
"# staticlib linker",
"if",
"not",
"v",
".",
"AR",
":",
"stliblink",
"=",
"conf",
".",
"find_program",
"(",
"lib_name",
",",
"path_list",
"=",
"path",
",",
"var",
"=",
"'AR'",
")",
"if",
"not",
"stliblink",
":",
"return",
"v",
".",
"ARFLAGS",
"=",
"[",
"'/nologo'",
"]",
"# manifest tool. Not required for VS 2003 and below. Must have for VS 2005 and later",
"if",
"v",
".",
"MSVC_MANIFEST",
":",
"conf",
".",
"find_program",
"(",
"'MT'",
",",
"path_list",
"=",
"path",
",",
"var",
"=",
"'MT'",
")",
"v",
".",
"MTFLAGS",
"=",
"[",
"'/nologo'",
"]",
"try",
":",
"conf",
".",
"load",
"(",
"'winres'",
")",
"except",
"Errors",
".",
"ConfigurationError",
":",
"Logs",
".",
"warn",
"(",
"'Resource compiler not found. Compiling resource file is disabled'",
")"
] | https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/msvc.py#L829-L879 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/memory_inspector/memory_inspector/core/memory_map.py | python | MapEntry.__cmp__ | (self, other) | Comparison operator required for bisect. | Comparison operator required for bisect. | [
"Comparison",
"operator",
"required",
"for",
"bisect",
"."
] | def __cmp__(self, other):
"""Comparison operator required for bisect."""
if isinstance(other, MapEntry):
return self.start - other.start
elif isinstance(other, int):
return self.start - other
else:
raise Exception('Cannot compare with %s' % other.__class__) | [
"def",
"__cmp__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"MapEntry",
")",
":",
"return",
"self",
".",
"start",
"-",
"other",
".",
"start",
"elif",
"isinstance",
"(",
"other",
",",
"int",
")",
":",
"return",
"self",
".",
"start",
"-",
"other",
"else",
":",
"raise",
"Exception",
"(",
"'Cannot compare with %s'",
"%",
"other",
".",
"__class__",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/memory_inspector/memory_inspector/core/memory_map.py#L74-L81 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pyio.py | python | RawIOBase.readinto | (self, b) | Read bytes into a pre-allocated bytes-like object b.
Returns an int representing the number of bytes read (0 for EOF), or
None if the object is set not to block and has no data to read. | Read bytes into a pre-allocated bytes-like object b. | [
"Read",
"bytes",
"into",
"a",
"pre",
"-",
"allocated",
"bytes",
"-",
"like",
"object",
"b",
"."
] | def readinto(self, b):
"""Read bytes into a pre-allocated bytes-like object b.
Returns an int representing the number of bytes read (0 for EOF), or
None if the object is set not to block and has no data to read.
"""
self._unsupported("readinto") | [
"def",
"readinto",
"(",
"self",
",",
"b",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"readinto\"",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pyio.py#L653-L659 | ||
Caffe-MPI/Caffe-MPI.github.io | df5992af571a2a19981b69635115c393f18d1c76 | examples/pycaffe/layers/pascal_multilabel_datalayers.py | python | load_pascal_annotation | (index, pascal_root) | return {'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'flipped': False,
'index': index} | This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross! | This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083). | [
"This",
"code",
"is",
"borrowed",
"from",
"Ross",
"Girshick",
"s",
"FAST",
"-",
"RCNN",
"code",
"(",
"https",
":",
"//",
"github",
".",
"com",
"/",
"rbgirshick",
"/",
"fast",
"-",
"rcnn",
")",
".",
"It",
"parses",
"the",
"PASCAL",
".",
"xml",
"metadata",
"files",
".",
"See",
"publication",
"for",
"further",
"details",
":",
"(",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1504",
".",
"08083",
")",
"."
] | def load_pascal_annotation(index, pascal_root):
"""
This code is borrowed from Ross Girshick's FAST-RCNN code
(https://github.com/rbgirshick/fast-rcnn).
It parses the PASCAL .xml metadata files.
See publication for further details: (http://arxiv.org/abs/1504.08083).
Thanks Ross!
"""
classes = ('__background__', # always index 0
'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse',
'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
class_to_ind = dict(zip(classes, xrange(21)))
filename = osp.join(pascal_root, 'Annotations', index + '.xml')
# print 'Loading: {}'.format(filename)
def get_data_from_tag(node, tag):
return node.getElementsByTagName(tag)[0].childNodes[0].data
with open(filename) as f:
data = minidom.parseString(f.read())
objs = data.getElementsByTagName('object')
num_objs = len(objs)
boxes = np.zeros((num_objs, 4), dtype=np.uint16)
gt_classes = np.zeros((num_objs), dtype=np.int32)
overlaps = np.zeros((num_objs, 21), dtype=np.float32)
# Load object bounding boxes into a data frame.
for ix, obj in enumerate(objs):
# Make pixel indexes 0-based
x1 = float(get_data_from_tag(obj, 'xmin')) - 1
y1 = float(get_data_from_tag(obj, 'ymin')) - 1
x2 = float(get_data_from_tag(obj, 'xmax')) - 1
y2 = float(get_data_from_tag(obj, 'ymax')) - 1
cls = class_to_ind[
str(get_data_from_tag(obj, "name")).lower().strip()]
boxes[ix, :] = [x1, y1, x2, y2]
gt_classes[ix] = cls
overlaps[ix, cls] = 1.0
overlaps = scipy.sparse.csr_matrix(overlaps)
return {'boxes': boxes,
'gt_classes': gt_classes,
'gt_overlaps': overlaps,
'flipped': False,
'index': index} | [
"def",
"load_pascal_annotation",
"(",
"index",
",",
"pascal_root",
")",
":",
"classes",
"=",
"(",
"'__background__'",
",",
"# always index 0",
"'aeroplane'",
",",
"'bicycle'",
",",
"'bird'",
",",
"'boat'",
",",
"'bottle'",
",",
"'bus'",
",",
"'car'",
",",
"'cat'",
",",
"'chair'",
",",
"'cow'",
",",
"'diningtable'",
",",
"'dog'",
",",
"'horse'",
",",
"'motorbike'",
",",
"'person'",
",",
"'pottedplant'",
",",
"'sheep'",
",",
"'sofa'",
",",
"'train'",
",",
"'tvmonitor'",
")",
"class_to_ind",
"=",
"dict",
"(",
"zip",
"(",
"classes",
",",
"xrange",
"(",
"21",
")",
")",
")",
"filename",
"=",
"osp",
".",
"join",
"(",
"pascal_root",
",",
"'Annotations'",
",",
"index",
"+",
"'.xml'",
")",
"# print 'Loading: {}'.format(filename)",
"def",
"get_data_from_tag",
"(",
"node",
",",
"tag",
")",
":",
"return",
"node",
".",
"getElementsByTagName",
"(",
"tag",
")",
"[",
"0",
"]",
".",
"childNodes",
"[",
"0",
"]",
".",
"data",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"data",
"=",
"minidom",
".",
"parseString",
"(",
"f",
".",
"read",
"(",
")",
")",
"objs",
"=",
"data",
".",
"getElementsByTagName",
"(",
"'object'",
")",
"num_objs",
"=",
"len",
"(",
"objs",
")",
"boxes",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
",",
"4",
")",
",",
"dtype",
"=",
"np",
".",
"uint16",
")",
"gt_classes",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
")",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"overlaps",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_objs",
",",
"21",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# Load object bounding boxes into a data frame.",
"for",
"ix",
",",
"obj",
"in",
"enumerate",
"(",
"objs",
")",
":",
"# Make pixel indexes 0-based",
"x1",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'xmin'",
")",
")",
"-",
"1",
"y1",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'ymin'",
")",
")",
"-",
"1",
"x2",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'xmax'",
")",
")",
"-",
"1",
"y2",
"=",
"float",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"'ymax'",
")",
")",
"-",
"1",
"cls",
"=",
"class_to_ind",
"[",
"str",
"(",
"get_data_from_tag",
"(",
"obj",
",",
"\"name\"",
")",
")",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"]",
"boxes",
"[",
"ix",
",",
":",
"]",
"=",
"[",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"]",
"gt_classes",
"[",
"ix",
"]",
"=",
"cls",
"overlaps",
"[",
"ix",
",",
"cls",
"]",
"=",
"1.0",
"overlaps",
"=",
"scipy",
".",
"sparse",
".",
"csr_matrix",
"(",
"overlaps",
")",
"return",
"{",
"'boxes'",
":",
"boxes",
",",
"'gt_classes'",
":",
"gt_classes",
",",
"'gt_overlaps'",
":",
"overlaps",
",",
"'flipped'",
":",
"False",
",",
"'index'",
":",
"index",
"}"
] | https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/examples/pycaffe/layers/pascal_multilabel_datalayers.py#L140-L193 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReductionQENS.py | python | IndirectILLReductionQENS._warn_negative_integral | (self, ws, message) | Raises an error if an integral of the given workspace is <= 0
@param ws :: input workspace name
@param message :: message suffix for the error
@throws RuntimeError :: on non-positive integral found | Raises an error if an integral of the given workspace is <= 0 | [
"Raises",
"an",
"error",
"if",
"an",
"integral",
"of",
"the",
"given",
"workspace",
"is",
"<",
"=",
"0"
] | def _warn_negative_integral(self, ws, message):
'''
Raises an error if an integral of the given workspace is <= 0
@param ws :: input workspace name
@param message :: message suffix for the error
@throws RuntimeError :: on non-positive integral found
'''
tmp_int = '__tmp_int'+ws
Integration(InputWorkspace=ws,OutputWorkspace=tmp_int)
for item in mtd[tmp_int]:
for index in range(item.getNumberHistograms()):
if item.readY(index)[0] <= 0:
self.log().warning('Negative or 0 integral in spectrum #{0} {1}'.format(index,message))
DeleteWorkspace(tmp_int) | [
"def",
"_warn_negative_integral",
"(",
"self",
",",
"ws",
",",
"message",
")",
":",
"tmp_int",
"=",
"'__tmp_int'",
"+",
"ws",
"Integration",
"(",
"InputWorkspace",
"=",
"ws",
",",
"OutputWorkspace",
"=",
"tmp_int",
")",
"for",
"item",
"in",
"mtd",
"[",
"tmp_int",
"]",
":",
"for",
"index",
"in",
"range",
"(",
"item",
".",
"getNumberHistograms",
"(",
")",
")",
":",
"if",
"item",
".",
"readY",
"(",
"index",
")",
"[",
"0",
"]",
"<=",
"0",
":",
"self",
".",
"log",
"(",
")",
".",
"warning",
"(",
"'Negative or 0 integral in spectrum #{0} {1}'",
".",
"format",
"(",
"index",
",",
"message",
")",
")",
"DeleteWorkspace",
"(",
"tmp_int",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReductionQENS.py#L269-L285 | ||
PlatformLab/RAMCloud | b1866af19124325a6dfd8cbc267e2e3ef1f965d1 | cpplint.py | python | RemoveMultiLineCommentsFromRange | (lines, begin, end) | Clears a range of lines for multi-line comments. | Clears a range of lines for multi-line comments. | [
"Clears",
"a",
"range",
"of",
"lines",
"for",
"multi",
"-",
"line",
"comments",
"."
] | def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '// dummy' | [
"def",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"begin",
",",
"end",
")",
":",
"# Having // dummy comments makes the lines non-empty, so we will not get",
"# unnecessary blank line warnings later in the code.",
"for",
"i",
"in",
"range",
"(",
"begin",
",",
"end",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"'// dummy'"
] | https://github.com/PlatformLab/RAMCloud/blob/b1866af19124325a6dfd8cbc267e2e3ef1f965d1/cpplint.py#L822-L827 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/logfile.py | python | LogFile.WriteMessage | (self, msg) | Append the message to the current log file
@param msg: string object | Append the message to the current log file
@param msg: string object | [
"Append",
"the",
"message",
"to",
"the",
"current",
"log",
"file",
"@param",
"msg",
":",
"string",
"object"
] | def WriteMessage(self, msg):
"""Append the message to the current log file
@param msg: string object
"""
# Files are named as prefix_YYYY_MM_DD.log
logstamp = "%d_%d_%d" % time.localtime()[:3]
logname = "%s_%s.log" % (self.prefix, logstamp)
logpath = os.path.join(self.logdir, logname)
if os.path.exists(logpath):
opencmd = "ab"
else:
opencmd = "wb"
# with open(logpath, opencmd) as handle:
# handle.write(msg.rstrip() + os.linesep)
try:
handle = open(logpath, opencmd)
handle.write(msg.rstrip() + os.linesep)
handle.close()
except IOError:
pass | [
"def",
"WriteMessage",
"(",
"self",
",",
"msg",
")",
":",
"# Files are named as prefix_YYYY_MM_DD.log",
"logstamp",
"=",
"\"%d_%d_%d\"",
"%",
"time",
".",
"localtime",
"(",
")",
"[",
":",
"3",
"]",
"logname",
"=",
"\"%s_%s.log\"",
"%",
"(",
"self",
".",
"prefix",
",",
"logstamp",
")",
"logpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"logdir",
",",
"logname",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"logpath",
")",
":",
"opencmd",
"=",
"\"ab\"",
"else",
":",
"opencmd",
"=",
"\"wb\"",
"# with open(logpath, opencmd) as handle:",
"# handle.write(msg.rstrip() + os.linesep)",
"try",
":",
"handle",
"=",
"open",
"(",
"logpath",
",",
"opencmd",
")",
"handle",
".",
"write",
"(",
"msg",
".",
"rstrip",
"(",
")",
"+",
"os",
".",
"linesep",
")",
"handle",
".",
"close",
"(",
")",
"except",
"IOError",
":",
"pass"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/logfile.py#L59-L80 | ||
freeorion/freeorion | c266a40eccd3a99a17de8fe57c36ef6ba3771665 | default/python/universe_generation/empires.py | python | get_starting_species_pool | () | Empire species pool generator, return random empire species and ensure somewhat even distribution | Empire species pool generator, return random empire species and ensure somewhat even distribution | [
"Empire",
"species",
"pool",
"generator",
"return",
"random",
"empire",
"species",
"and",
"ensure",
"somewhat",
"even",
"distribution"
] | def get_starting_species_pool():
"""
Empire species pool generator, return random empire species and ensure somewhat even distribution
"""
# fill the initial pool with two sets of all playable species
# this way we have somewhat, but not absolutely strict even distribution of starting species at least when there
# is only a few number of players (some species can occur twice at max while others not at all)
pool = fo.get_playable_species() * 2
# randomize order in initial pool so we don't get the same species all the time
random.shuffle(pool)
# generator loop
while True:
# if our pool is exhausted (because we have more players than species instances in our initial pool)
# refill the pool with one set of all playable species
if not pool:
pool = fo.get_playable_species()
# again, randomize order in refilled pool so we don't get the same species all the time
random.shuffle(pool)
# pick and return next species, and remove it from our pool
yield pool.pop() | [
"def",
"get_starting_species_pool",
"(",
")",
":",
"# fill the initial pool with two sets of all playable species",
"# this way we have somewhat, but not absolutely strict even distribution of starting species at least when there",
"# is only a few number of players (some species can occur twice at max while others not at all)",
"pool",
"=",
"fo",
".",
"get_playable_species",
"(",
")",
"*",
"2",
"# randomize order in initial pool so we don't get the same species all the time",
"random",
".",
"shuffle",
"(",
"pool",
")",
"# generator loop",
"while",
"True",
":",
"# if our pool is exhausted (because we have more players than species instances in our initial pool)",
"# refill the pool with one set of all playable species",
"if",
"not",
"pool",
":",
"pool",
"=",
"fo",
".",
"get_playable_species",
"(",
")",
"# again, randomize order in refilled pool so we don't get the same species all the time",
"random",
".",
"shuffle",
"(",
"pool",
")",
"# pick and return next species, and remove it from our pool",
"yield",
"pool",
".",
"pop",
"(",
")"
] | https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/universe_generation/empires.py#L45-L65 | ||
runtimejs/runtime | 0a6e84c30823d35a4548d6634166784260ae7b74 | deps/v8/tools/release/push_to_candidates.py | python | PrepareChangeLog.Reload | (self, body) | return body | Attempts to reload the commit message from rietveld in order to allow
late changes to the LOG flag. Note: This is brittle to future changes of
the web page name or structure. | Attempts to reload the commit message from rietveld in order to allow
late changes to the LOG flag. Note: This is brittle to future changes of
the web page name or structure. | [
"Attempts",
"to",
"reload",
"the",
"commit",
"message",
"from",
"rietveld",
"in",
"order",
"to",
"allow",
"late",
"changes",
"to",
"the",
"LOG",
"flag",
".",
"Note",
":",
"This",
"is",
"brittle",
"to",
"future",
"changes",
"of",
"the",
"web",
"page",
"name",
"or",
"structure",
"."
] | def Reload(self, body):
"""Attempts to reload the commit message from rietveld in order to allow
late changes to the LOG flag. Note: This is brittle to future changes of
the web page name or structure.
"""
match = re.search(r"^Review URL: https://codereview\.chromium\.org/(\d+)$",
body, flags=re.M)
if match:
cl_url = ("https://codereview.chromium.org/%s/description"
% match.group(1))
try:
# Fetch from Rietveld but only retry once with one second delay since
# there might be many revisions.
body = self.ReadURL(cl_url, wait_plan=[1])
except urllib2.URLError: # pragma: no cover
pass
return body | [
"def",
"Reload",
"(",
"self",
",",
"body",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r\"^Review URL: https://codereview\\.chromium\\.org/(\\d+)$\"",
",",
"body",
",",
"flags",
"=",
"re",
".",
"M",
")",
"if",
"match",
":",
"cl_url",
"=",
"(",
"\"https://codereview.chromium.org/%s/description\"",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"try",
":",
"# Fetch from Rietveld but only retry once with one second delay since",
"# there might be many revisions.",
"body",
"=",
"self",
".",
"ReadURL",
"(",
"cl_url",
",",
"wait_plan",
"=",
"[",
"1",
"]",
")",
"except",
"urllib2",
".",
"URLError",
":",
"# pragma: no cover",
"pass",
"return",
"body"
] | https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/tools/release/push_to_candidates.py#L122-L138 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_controls.py | python | ListCtrl.GetItemText | (*args, **kwargs) | return _controls_.ListCtrl_GetItemText(*args, **kwargs) | GetItemText(self, long item, int col=0) -> String | GetItemText(self, long item, int col=0) -> String | [
"GetItemText",
"(",
"self",
"long",
"item",
"int",
"col",
"=",
"0",
")",
"-",
">",
"String"
] | def GetItemText(*args, **kwargs):
"""GetItemText(self, long item, int col=0) -> String"""
return _controls_.ListCtrl_GetItemText(*args, **kwargs) | [
"def",
"GetItemText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"ListCtrl_GetItemText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4547-L4549 | |
etternagame/etterna | 8775f74ac9c353320128609d4b4150672e9a6d04 | extern/SQLiteCpp/cpplint.py | python | CleansedLines.NumLines | (self) | return self.num_lines | Returns the number of lines represented. | Returns the number of lines represented. | [
"Returns",
"the",
"number",
"of",
"lines",
"represented",
"."
] | def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines | [
"def",
"NumLines",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_lines"
] | https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/SQLiteCpp/cpplint.py#L1208-L1210 | |
lightvector/KataGo | 20d34784703c5b4000643d3ccc43bb37d418f3b5 | python/sgfmill/sgf_grammar.py | python | block_format | (pieces, width=79) | return b"\n".join(lines) | Concatenate strings, adding newlines.
pieces -- iterable of bytes-like objects
width -- int (default 79)
Returns b"".join(pieces), with added newlines between pieces as necessary
to avoid lines longer than 'width' (using nothing more sophisticated than a
byte-count).
Leaves newlines inside 'pieces' untouched, and ignores them in its width
calculation. If a single piece is longer than 'width', it will become a
single long line in the output. | Concatenate strings, adding newlines. | [
"Concatenate",
"strings",
"adding",
"newlines",
"."
] | def block_format(pieces, width=79):
"""Concatenate strings, adding newlines.
pieces -- iterable of bytes-like objects
width -- int (default 79)
Returns b"".join(pieces), with added newlines between pieces as necessary
to avoid lines longer than 'width' (using nothing more sophisticated than a
byte-count).
Leaves newlines inside 'pieces' untouched, and ignores them in its width
calculation. If a single piece is longer than 'width', it will become a
single long line in the output.
"""
lines = []
line = b""
for bb in pieces:
if len(line) + len(bb) > width:
lines.append(line)
line = b""
line += bb
if line:
lines.append(line)
return b"\n".join(lines) | [
"def",
"block_format",
"(",
"pieces",
",",
"width",
"=",
"79",
")",
":",
"lines",
"=",
"[",
"]",
"line",
"=",
"b\"\"",
"for",
"bb",
"in",
"pieces",
":",
"if",
"len",
"(",
"line",
")",
"+",
"len",
"(",
"bb",
")",
">",
"width",
":",
"lines",
".",
"append",
"(",
"line",
")",
"line",
"=",
"b\"\"",
"line",
"+=",
"bb",
"if",
"line",
":",
"lines",
".",
"append",
"(",
"line",
")",
"return",
"b\"\\n\"",
".",
"join",
"(",
"lines",
")"
] | https://github.com/lightvector/KataGo/blob/20d34784703c5b4000643d3ccc43bb37d418f3b5/python/sgfmill/sgf_grammar.py#L255-L279 | |
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TUInt.__ixor__ | (self, *args) | return _snap.TUInt___ixor__(self, *args) | __ixor__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const & | __ixor__(TUInt self, TUInt UInt) -> TUInt | [
"__ixor__",
"(",
"TUInt",
"self",
"TUInt",
"UInt",
")",
"-",
">",
"TUInt"
] | def __ixor__(self, *args):
"""
__ixor__(TUInt self, TUInt UInt) -> TUInt
Parameters:
UInt: TUInt const &
"""
return _snap.TUInt___ixor__(self, *args) | [
"def",
"__ixor__",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TUInt___ixor__",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L13661-L13669 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py | python | Manager.__init__ | (self, rootnode) | Initialize the manager with the root node of the logger hierarchy. | Initialize the manager with the root node of the logger hierarchy. | [
"Initialize",
"the",
"manager",
"with",
"the",
"root",
"node",
"of",
"the",
"logger",
"hierarchy",
"."
] | def __init__(self, rootnode):
"""
Initialize the manager with the root node of the logger hierarchy.
"""
self.root = rootnode
self.disable = 0
self.emittedNoHandlerWarning = False
self.loggerDict = {}
self.loggerClass = None
self.logRecordFactory = None | [
"def",
"__init__",
"(",
"self",
",",
"rootnode",
")",
":",
"self",
".",
"root",
"=",
"rootnode",
"self",
".",
"disable",
"=",
"0",
"self",
".",
"emittedNoHandlerWarning",
"=",
"False",
"self",
".",
"loggerDict",
"=",
"{",
"}",
"self",
".",
"loggerClass",
"=",
"None",
"self",
".",
"logRecordFactory",
"=",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py#L1205-L1214 | ||
sphawes/index | bf0991af04f53ba16757dedd199a4e79077ae2f0 | doc/scripts/create-tag.py | python | append_version | (file: TextIO, version: str, url: str) | Adds a version entry to file based on the inputs version and url.
:param file: the file object to append the version entry to
:param version: the version to use in the version entry
:param url: the url to use in the version entry
:return: None | Adds a version entry to file based on the inputs version and url. | [
"Adds",
"a",
"version",
"entry",
"to",
"file",
"based",
"on",
"the",
"inputs",
"version",
"and",
"url",
"."
] | def append_version(file: TextIO, version: str, url: str) -> None:
"""
Adds a version entry to file based on the inputs version and url.
:param file: the file object to append the version entry to
:param version: the version to use in the version entry
:param url: the url to use in the version entry
:return: None
"""
file.write('[[params.versions]]\n')
file.write('\tversion="{}"\n'.format(version))
file.write('\turl="{}"\n'.format(url)) | [
"def",
"append_version",
"(",
"file",
":",
"TextIO",
",",
"version",
":",
"str",
",",
"url",
":",
"str",
")",
"->",
"None",
":",
"file",
".",
"write",
"(",
"'[[params.versions]]\\n'",
")",
"file",
".",
"write",
"(",
"'\\tversion=\"{}\"\\n'",
".",
"format",
"(",
"version",
")",
")",
"file",
".",
"write",
"(",
"'\\turl=\"{}\"\\n'",
".",
"format",
"(",
"url",
")",
")"
] | https://github.com/sphawes/index/blob/bf0991af04f53ba16757dedd199a4e79077ae2f0/doc/scripts/create-tag.py#L23-L34 | ||
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bernoulli.py | python | Bernoulli.variance | (self, name="variance") | Variance of the distribution.
Args:
name: Name for the op.
Returns:
variance: `Tensor` of the same type and shape as `p`. | Variance of the distribution. | [
"Variance",
"of",
"the",
"distribution",
"."
] | def variance(self, name="variance"):
"""Variance of the distribution.
Args:
name: Name for the op.
Returns:
variance: `Tensor` of the same type and shape as `p`.
"""
with ops.name_scope(self.name):
with ops.op_scope([self.p, self.q], name):
return self.q * self.p | [
"def",
"variance",
"(",
"self",
",",
"name",
"=",
"\"variance\"",
")",
":",
"with",
"ops",
".",
"name_scope",
"(",
"self",
".",
"name",
")",
":",
"with",
"ops",
".",
"op_scope",
"(",
"[",
"self",
".",
"p",
",",
"self",
".",
"q",
"]",
",",
"name",
")",
":",
"return",
"self",
".",
"q",
"*",
"self",
".",
"p"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bernoulli.py#L240-L251 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.