nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/easy_install.py | python | easy_install.expand_dirs | (self) | Calls `os.path.expanduser` on install dirs. | Calls `os.path.expanduser` on install dirs. | [
"Calls",
"os",
".",
"path",
".",
"expanduser",
"on",
"install",
"dirs",
"."
] | def expand_dirs(self):
"""Calls `os.path.expanduser` on install dirs."""
dirs = [
'install_purelib',
'install_platlib',
'install_lib',
'install_headers',
'install_scripts',
'install_data',
]
self._expand_attrs(dirs) | [
"def",
"expand_dirs",
"(",
"self",
")",
":",
"dirs",
"=",
"[",
"'install_purelib'",
",",
"'install_platlib'",
",",
"'install_lib'",
",",
"'install_headers'",
",",
"'install_scripts'",
",",
"'install_data'",
",",
"]",
"self",
".",
"_expand_attrs",
"(",
"dirs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/easy_install.py#L401-L411 | ||
Tencent/CMONGO | c40380caa14e05509f46993aa8b8da966b09b0b5 | src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py | python | Node.get_binfo | (self) | return binfo | Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's signatures. We expect that they're
already built and updated by someone else, if that's
what's wanted. | Fetch a node's build information. | [
"Fetch",
"a",
"node",
"s",
"build",
"information",
"."
] | def get_binfo(self):
"""
Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's signatures. We expect that they're
already built and updated by someone else, if that's
what's wanted.
"""
try:
return self.binfo
except AttributeError:
pass
binfo = self.new_binfo()
self.binfo = binfo
executor = self.get_executor()
ignore_set = self.ignore_set
if self.has_builder():
binfo.bact = str(executor)
binfo.bactsig = SCons.Util.MD5signature(executor.get_contents())
if self._specific_sources:
sources = []
for s in self.sources:
if s not in ignore_set:
sources.append(s)
else:
sources = executor.get_unignored_sources(self, self.ignore)
seen = set()
bsources = []
bsourcesigs = []
for s in sources:
if not s in seen:
seen.add(s)
bsources.append(s)
bsourcesigs.append(s.get_ninfo())
binfo.bsources = bsources
binfo.bsourcesigs = bsourcesigs
depends = self.depends
dependsigs = []
for d in depends:
if d not in ignore_set:
dependsigs.append(d.get_ninfo())
binfo.bdepends = depends
binfo.bdependsigs = dependsigs
implicit = self.implicit or []
implicitsigs = []
for i in implicit:
if i not in ignore_set:
implicitsigs.append(i.get_ninfo())
binfo.bimplicit = implicit
binfo.bimplicitsigs = implicitsigs
return binfo | [
"def",
"get_binfo",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"binfo",
"except",
"AttributeError",
":",
"pass",
"binfo",
"=",
"self",
".",
"new_binfo",
"(",
")",
"self",
".",
"binfo",
"=",
"binfo",
"executor",
"=",
"self",
".",
"get_executor",
"(",
")",
"ignore_set",
"=",
"self",
".",
"ignore_set",
"if",
"self",
".",
"has_builder",
"(",
")",
":",
"binfo",
".",
"bact",
"=",
"str",
"(",
"executor",
")",
"binfo",
".",
"bactsig",
"=",
"SCons",
".",
"Util",
".",
"MD5signature",
"(",
"executor",
".",
"get_contents",
"(",
")",
")",
"if",
"self",
".",
"_specific_sources",
":",
"sources",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"sources",
":",
"if",
"s",
"not",
"in",
"ignore_set",
":",
"sources",
".",
"append",
"(",
"s",
")",
"else",
":",
"sources",
"=",
"executor",
".",
"get_unignored_sources",
"(",
"self",
",",
"self",
".",
"ignore",
")",
"seen",
"=",
"set",
"(",
")",
"bsources",
"=",
"[",
"]",
"bsourcesigs",
"=",
"[",
"]",
"for",
"s",
"in",
"sources",
":",
"if",
"not",
"s",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"s",
")",
"bsources",
".",
"append",
"(",
"s",
")",
"bsourcesigs",
".",
"append",
"(",
"s",
".",
"get_ninfo",
"(",
")",
")",
"binfo",
".",
"bsources",
"=",
"bsources",
"binfo",
".",
"bsourcesigs",
"=",
"bsourcesigs",
"depends",
"=",
"self",
".",
"depends",
"dependsigs",
"=",
"[",
"]",
"for",
"d",
"in",
"depends",
":",
"if",
"d",
"not",
"in",
"ignore_set",
":",
"dependsigs",
".",
"append",
"(",
"d",
".",
"get_ninfo",
"(",
")",
")",
"binfo",
".",
"bdepends",
"=",
"depends",
"binfo",
".",
"bdependsigs",
"=",
"dependsigs",
"implicit",
"=",
"self",
".",
"implicit",
"or",
"[",
"]",
"implicitsigs",
"=",
"[",
"]",
"for",
"i",
"in",
"implicit",
":",
"if",
"i",
"not",
"in",
"ignore_set",
":",
"implicitsigs",
".",
"append",
"(",
"i",
".",
"get_ninfo",
"(",
")",
")",
"binfo",
".",
"bimplicit",
"=",
"implicit",
"binfo",
".",
"bimplicitsigs",
"=",
"implicitsigs",
"return",
"binfo"
] | https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Node/__init__.py#L1097-L1159 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.EnsureNoIDCollisions | (self) | Verifies that no two objects have the same ID. Checks all descendants. | Verifies that no two objects have the same ID. Checks all descendants. | [
"Verifies",
"that",
"no",
"two",
"objects",
"have",
"the",
"same",
"ID",
".",
"Checks",
"all",
"descendants",
"."
] | def EnsureNoIDCollisions(self):
"""Verifies that no two objects have the same ID. Checks all descendants.
"""
ids = {}
descendants = self.Descendants()
for descendant in descendants:
if descendant.id in ids:
other = ids[descendant.id]
raise KeyError(
'Duplicate ID %s, objects "%s" and "%s" in "%s"' % \
(descendant.id, str(descendant._properties),
str(other._properties), self._properties['rootObject'].Name()))
ids[descendant.id] = descendant | [
"def",
"EnsureNoIDCollisions",
"(",
"self",
")",
":",
"ids",
"=",
"{",
"}",
"descendants",
"=",
"self",
".",
"Descendants",
"(",
")",
"for",
"descendant",
"in",
"descendants",
":",
"if",
"descendant",
".",
"id",
"in",
"ids",
":",
"other",
"=",
"ids",
"[",
"descendant",
".",
"id",
"]",
"raise",
"KeyError",
"(",
"'Duplicate ID %s, objects \"%s\" and \"%s\" in \"%s\"'",
"%",
"(",
"descendant",
".",
"id",
",",
"str",
"(",
"descendant",
".",
"_properties",
")",
",",
"str",
"(",
"other",
".",
"_properties",
")",
",",
"self",
".",
"_properties",
"[",
"'rootObject'",
"]",
".",
"Name",
"(",
")",
")",
")",
"ids",
"[",
"descendant",
".",
"id",
"]",
"=",
"descendant"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L455-L468 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/patch_builds/change_data.py | python | find_changed_files | (repo: Repo, revision_map: Optional[RevisionMap] = None) | return {
os.path.relpath(f"{repo.working_dir}/{os.path.normpath(path)}", os.getcwd())
for path in paths
} | Find files that were new or added to the repository between commits.
:param repo: Git repository.
:param revision_map: Map of revisions to compare against for repos.
:return: Set of changed files. | Find files that were new or added to the repository between commits. | [
"Find",
"files",
"that",
"were",
"new",
"or",
"added",
"to",
"the",
"repository",
"between",
"commits",
"."
] | def find_changed_files(repo: Repo, revision_map: Optional[RevisionMap] = None) -> Set[str]:
"""
Find files that were new or added to the repository between commits.
:param repo: Git repository.
:param revision_map: Map of revisions to compare against for repos.
:return: Set of changed files.
"""
LOGGER.info("Getting diff for repo", repo=repo.git_dir)
if not revision_map:
revision_map = {}
diff = repo.index.diff(None)
work_tree_files = _modified_files_for_diff(diff, LOGGER.bind(diff="working tree diff"))
commit = repo.index
diff = commit.diff(revision_map.get(repo.git_dir, repo.head.commit))
index_files = _modified_files_for_diff(diff, LOGGER.bind(diff="index diff"))
untracked_files = set(repo.untracked_files)
LOGGER.info("untracked files", files=untracked_files, diff="untracked diff")
paths = work_tree_files.union(index_files).union(untracked_files)
return {
os.path.relpath(f"{repo.working_dir}/{os.path.normpath(path)}", os.getcwd())
for path in paths
} | [
"def",
"find_changed_files",
"(",
"repo",
":",
"Repo",
",",
"revision_map",
":",
"Optional",
"[",
"RevisionMap",
"]",
"=",
"None",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"LOGGER",
".",
"info",
"(",
"\"Getting diff for repo\"",
",",
"repo",
"=",
"repo",
".",
"git_dir",
")",
"if",
"not",
"revision_map",
":",
"revision_map",
"=",
"{",
"}",
"diff",
"=",
"repo",
".",
"index",
".",
"diff",
"(",
"None",
")",
"work_tree_files",
"=",
"_modified_files_for_diff",
"(",
"diff",
",",
"LOGGER",
".",
"bind",
"(",
"diff",
"=",
"\"working tree diff\"",
")",
")",
"commit",
"=",
"repo",
".",
"index",
"diff",
"=",
"commit",
".",
"diff",
"(",
"revision_map",
".",
"get",
"(",
"repo",
".",
"git_dir",
",",
"repo",
".",
"head",
".",
"commit",
")",
")",
"index_files",
"=",
"_modified_files_for_diff",
"(",
"diff",
",",
"LOGGER",
".",
"bind",
"(",
"diff",
"=",
"\"index diff\"",
")",
")",
"untracked_files",
"=",
"set",
"(",
"repo",
".",
"untracked_files",
")",
"LOGGER",
".",
"info",
"(",
"\"untracked files\"",
",",
"files",
"=",
"untracked_files",
",",
"diff",
"=",
"\"untracked diff\"",
")",
"paths",
"=",
"work_tree_files",
".",
"union",
"(",
"index_files",
")",
".",
"union",
"(",
"untracked_files",
")",
"return",
"{",
"os",
".",
"path",
".",
"relpath",
"(",
"f\"{repo.working_dir}/{os.path.normpath(path)}\"",
",",
"os",
".",
"getcwd",
"(",
")",
")",
"for",
"path",
"in",
"paths",
"}"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/patch_builds/change_data.py#L74-L101 | |
envoyproxy/envoy-wasm | ab5d9381fdf92a1efa0b87cff80036b5b3e81198 | tools/envoy_headersplit/replace_includes.py | python | to_bazelname | (filename: str, mockname: str) | return bazelname | maps divided mock class file name to bazel target name
e.g. map "test/mocks/server/admin_stream.h" to "//test/mocks/server:admin_stream_mocks"
Args:
filename: string, mock class header file name (might be the whole path instead of the base name)
mockname: string, mock directory name
Returns:
corresponding bazel target name | maps divided mock class file name to bazel target name
e.g. map "test/mocks/server/admin_stream.h" to "//test/mocks/server:admin_stream_mocks" | [
"maps",
"divided",
"mock",
"class",
"file",
"name",
"to",
"bazel",
"target",
"name",
"e",
".",
"g",
".",
"map",
"test",
"/",
"mocks",
"/",
"server",
"/",
"admin_stream",
".",
"h",
"to",
"//",
"test",
"/",
"mocks",
"/",
"server",
":",
"admin_stream_mocks"
] | def to_bazelname(filename: str, mockname: str) -> str:
"""
maps divided mock class file name to bazel target name
e.g. map "test/mocks/server/admin_stream.h" to "//test/mocks/server:admin_stream_mocks"
Args:
filename: string, mock class header file name (might be the whole path instead of the base name)
mockname: string, mock directory name
Returns:
corresponding bazel target name
"""
bazelname = "//test/mocks/{}:".format(mockname)
bazelname += filename.split('/')[-1].replace('.h', '') + '_mocks'.format(mockname)
return bazelname | [
"def",
"to_bazelname",
"(",
"filename",
":",
"str",
",",
"mockname",
":",
"str",
")",
"->",
"str",
":",
"bazelname",
"=",
"\"//test/mocks/{}:\"",
".",
"format",
"(",
"mockname",
")",
"bazelname",
"+=",
"filename",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"replace",
"(",
"'.h'",
",",
"''",
")",
"+",
"'_mocks'",
".",
"format",
"(",
"mockname",
")",
"return",
"bazelname"
] | https://github.com/envoyproxy/envoy-wasm/blob/ab5d9381fdf92a1efa0b87cff80036b5b3e81198/tools/envoy_headersplit/replace_includes.py#L38-L52 | |
p4lang/behavioral-model | 81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9 | tools/runtime_CLI.py | python | RuntimeAPI.do_mc_node_update | (self, line) | Update multicast node: mc_node_update <node handle> <space-separated port list> [ | <space-separated lag list> ] | Update multicast node: mc_node_update <node handle> <space-separated port list> [ | <space-separated lag list> ] | [
"Update",
"multicast",
"node",
":",
"mc_node_update",
"<node",
"handle",
">",
"<space",
"-",
"separated",
"port",
"list",
">",
"[",
"|",
"<space",
"-",
"separated",
"lag",
"list",
">",
"]"
] | def do_mc_node_update(self, line):
"Update multicast node: mc_node_update <node handle> <space-separated port list> [ | <space-separated lag list> ]"
self.check_has_pre()
args = line.split()
self.at_least_n_args(args, 2)
l1_hdl = self.get_node_handle(args[0])
port_map_str, lag_map_str = self.parse_ports_and_lags(args)
if self.pre_type == PreType.SimplePre:
print("Updating node", l1_hdl, "with port map", port_map_str)
self.mc_client.bm_mc_node_update(0, l1_hdl, port_map_str)
else:
print("Updating node", l1_hdl, "with port map",
port_map_str, "and lag map", lag_map_str)
self.mc_client.bm_mc_node_update(
0, l1_hdl, port_map_str, lag_map_str) | [
"def",
"do_mc_node_update",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"check_has_pre",
"(",
")",
"args",
"=",
"line",
".",
"split",
"(",
")",
"self",
".",
"at_least_n_args",
"(",
"args",
",",
"2",
")",
"l1_hdl",
"=",
"self",
".",
"get_node_handle",
"(",
"args",
"[",
"0",
"]",
")",
"port_map_str",
",",
"lag_map_str",
"=",
"self",
".",
"parse_ports_and_lags",
"(",
"args",
")",
"if",
"self",
".",
"pre_type",
"==",
"PreType",
".",
"SimplePre",
":",
"print",
"(",
"\"Updating node\"",
",",
"l1_hdl",
",",
"\"with port map\"",
",",
"port_map_str",
")",
"self",
".",
"mc_client",
".",
"bm_mc_node_update",
"(",
"0",
",",
"l1_hdl",
",",
"port_map_str",
")",
"else",
":",
"print",
"(",
"\"Updating node\"",
",",
"l1_hdl",
",",
"\"with port map\"",
",",
"port_map_str",
",",
"\"and lag map\"",
",",
"lag_map_str",
")",
"self",
".",
"mc_client",
".",
"bm_mc_node_update",
"(",
"0",
",",
"l1_hdl",
",",
"port_map_str",
",",
"lag_map_str",
")"
] | https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/runtime_CLI.py#L1794-L1808 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | Joystick.GetButtonState | (*args, **kwargs) | return _misc_.Joystick_GetButtonState(*args, **kwargs) | GetButtonState(self) -> int | GetButtonState(self) -> int | [
"GetButtonState",
"(",
"self",
")",
"-",
">",
"int"
] | def GetButtonState(*args, **kwargs):
"""GetButtonState(self) -> int"""
return _misc_.Joystick_GetButtonState(*args, **kwargs) | [
"def",
"GetButtonState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Joystick_GetButtonState",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2134-L2136 | |
H-uru/Plasma | c2140ea046e82e9c199e257a7f2e7edb42602871 | Scripts/Python/plasma/pch.py | python | showinst | () | show details of the instance of the ptModifier class in the selected module | show details of the instance of the ptModifier class in the selected module | [
"show",
"details",
"of",
"the",
"instance",
"of",
"the",
"ptModifier",
"class",
"in",
"the",
"selected",
"module"
] | def showinst():
"show details of the instance of the ptModifier class in the selected module"
global __pmods
global __sel
for name in __pmods[__sel][1].__dict__.keys():
ist = __pmods[__sel][1].__dict__[name]
if isinstance(ist,PlasmaTypes.ptModifier):
print("Instance of %s in module %s:" % (ist.__class__.__name__,__pmods[__sel][1].__name__[:-13]))
print(" Doc: ",ist.__doc__)
showvars(ist)
showmethods(ist) | [
"def",
"showinst",
"(",
")",
":",
"global",
"__pmods",
"global",
"__sel",
"for",
"name",
"in",
"__pmods",
"[",
"__sel",
"]",
"[",
"1",
"]",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"ist",
"=",
"__pmods",
"[",
"__sel",
"]",
"[",
"1",
"]",
".",
"__dict__",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"ist",
",",
"PlasmaTypes",
".",
"ptModifier",
")",
":",
"print",
"(",
"\"Instance of %s in module %s:\"",
"%",
"(",
"ist",
".",
"__class__",
".",
"__name__",
",",
"__pmods",
"[",
"__sel",
"]",
"[",
"1",
"]",
".",
"__name__",
"[",
":",
"-",
"13",
"]",
")",
")",
"print",
"(",
"\" Doc: \"",
",",
"ist",
".",
"__doc__",
")",
"showvars",
"(",
"ist",
")",
"showmethods",
"(",
"ist",
")"
] | https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/pch.py#L225-L235 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py | python | pack_array | (builder, values, ty=None) | return ary | Pack a sequence of values in a LLVM array. *ty* should be given
if the array may be empty, in which case the type can't be inferred
from the values. | Pack a sequence of values in a LLVM array. *ty* should be given
if the array may be empty, in which case the type can't be inferred
from the values. | [
"Pack",
"a",
"sequence",
"of",
"values",
"in",
"a",
"LLVM",
"array",
".",
"*",
"ty",
"*",
"should",
"be",
"given",
"if",
"the",
"array",
"may",
"be",
"empty",
"in",
"which",
"case",
"the",
"type",
"can",
"t",
"be",
"inferred",
"from",
"the",
"values",
"."
] | def pack_array(builder, values, ty=None):
"""
Pack a sequence of values in a LLVM array. *ty* should be given
if the array may be empty, in which case the type can't be inferred
from the values.
"""
n = len(values)
if ty is None:
ty = values[0].type
ary = ir.ArrayType(ty, n)(ir.Undefined)
for i, v in enumerate(values):
ary = builder.insert_value(ary, v, i)
return ary | [
"def",
"pack_array",
"(",
"builder",
",",
"values",
",",
"ty",
"=",
"None",
")",
":",
"n",
"=",
"len",
"(",
"values",
")",
"if",
"ty",
"is",
"None",
":",
"ty",
"=",
"values",
"[",
"0",
"]",
".",
"type",
"ary",
"=",
"ir",
".",
"ArrayType",
"(",
"ty",
",",
"n",
")",
"(",
"ir",
".",
"Undefined",
")",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"ary",
"=",
"builder",
".",
"insert_value",
"(",
"ary",
",",
"v",
",",
"i",
")",
"return",
"ary"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py#L622-L634 | |
Tencent/Pebble | 68315f176d9e328a233ace29b7579a829f89879f | tools/blade/src/blade/rules_generator.py | python | SconsFileHeaderGenerator._append_prefix_to_building_var | (
self,
prefix='',
building_var='',
condition=False) | A helper method: append prefix to building var if condition is True. | A helper method: append prefix to building var if condition is True. | [
"A",
"helper",
"method",
":",
"append",
"prefix",
"to",
"building",
"var",
"if",
"condition",
"is",
"True",
"."
] | def _append_prefix_to_building_var(
self,
prefix='',
building_var='',
condition=False):
"""A helper method: append prefix to building var if condition is True."""
if condition:
return '%s %s' % (prefix, building_var)
else:
return building_var | [
"def",
"_append_prefix_to_building_var",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"building_var",
"=",
"''",
",",
"condition",
"=",
"False",
")",
":",
"if",
"condition",
":",
"return",
"'%s %s'",
"%",
"(",
"prefix",
",",
"building_var",
")",
"else",
":",
"return",
"building_var"
] | https://github.com/Tencent/Pebble/blob/68315f176d9e328a233ace29b7579a829f89879f/tools/blade/src/blade/rules_generator.py#L61-L70 | ||
OGRECave/ogre-next | 287307980e6de8910f04f3cc0994451b075071fd | Tools/BlenderExport/ogrepkg/gui.py | python | ToggleGroup.setValue | (self, value) | return | Sets a toggle to <code>True</code>.
@param value Key of ToggleModel. | Sets a toggle to <code>True</code>. | [
"Sets",
"a",
"toggle",
"to",
"<code",
">",
"True<",
"/",
"code",
">",
"."
] | def setValue(self, value):
"""Sets a toggle to <code>True</code>.
@param value Key of ToggleModel.
"""
# set value as current active
if (value in self.toggleDict.keys()):
self.value = value
self._notify()
elif value is None:
pass
else:
raise KeyError
return | [
"def",
"setValue",
"(",
"self",
",",
"value",
")",
":",
"# set value as current active",
"if",
"(",
"value",
"in",
"self",
".",
"toggleDict",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"value",
"=",
"value",
"self",
".",
"_notify",
"(",
")",
"elif",
"value",
"is",
"None",
":",
"pass",
"else",
":",
"raise",
"KeyError",
"return"
] | https://github.com/OGRECave/ogre-next/blob/287307980e6de8910f04f3cc0994451b075071fd/Tools/BlenderExport/ogrepkg/gui.py#L514-L527 | |
deepmind/open_spiel | 4ca53bea32bb2875c7385d215424048ae92f78c8 | open_spiel/python/games/iterated_prisoners_dilemma.py | python | IteratedPrisonersDilemmaState.is_terminal | (self) | return self._game_over | Returns True if the game is over. | Returns True if the game is over. | [
"Returns",
"True",
"if",
"the",
"game",
"is",
"over",
"."
] | def is_terminal(self):
"""Returns True if the game is over."""
return self._game_over | [
"def",
"is_terminal",
"(",
"self",
")",
":",
"return",
"self",
".",
"_game_over"
] | https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/games/iterated_prisoners_dilemma.py#L148-L150 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/metrics/cluster/_supervised.py | python | mutual_info_score | (labels_true, labels_pred, contingency=None) | return mi.sum() | Mutual Information between two clusterings.
The Mutual Information is a measure of the similarity between two labels of
the same data. Where :math:`|U_i|` is the number of the samples
in cluster :math:`U_i` and :math:`|V_j|` is the number of the
samples in cluster :math:`V_j`, the Mutual Information
between clusterings :math:`U` and :math:`V` is given as:
.. math::
MI(U,V)=\\sum_{i=1}^{|U|} \\sum_{j=1}^{|V|} \\frac{|U_i\\cap V_j|}{N}
\\log\\frac{N|U_i \\cap V_j|}{|U_i||V_j|}
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.
Read more in the :ref:`User Guide <mutual_info_score>`.
Parameters
----------
labels_true : int array, shape = [n_samples]
A clustering of the data into disjoint subsets.
labels_pred : int array-like of shape (n_samples,)
A clustering of the data into disjoint subsets.
contingency : {None, array, sparse matrix}, \
shape = [n_classes_true, n_classes_pred]
A contingency matrix given by the :func:`contingency_matrix` function.
If value is ``None``, it will be computed, otherwise the given value is
used, with ``labels_true`` and ``labels_pred`` ignored.
Returns
-------
mi : float
Mutual information, a non-negative value
Notes
-----
The logarithm used is the natural logarithm (base-e).
See also
--------
adjusted_mutual_info_score: Adjusted against chance Mutual Information
normalized_mutual_info_score: Normalized Mutual Information | Mutual Information between two clusterings. | [
"Mutual",
"Information",
"between",
"two",
"clusterings",
"."
] | def mutual_info_score(labels_true, labels_pred, contingency=None):
"""Mutual Information between two clusterings.
The Mutual Information is a measure of the similarity between two labels of
the same data. Where :math:`|U_i|` is the number of the samples
in cluster :math:`U_i` and :math:`|V_j|` is the number of the
samples in cluster :math:`V_j`, the Mutual Information
between clusterings :math:`U` and :math:`V` is given as:
.. math::
MI(U,V)=\\sum_{i=1}^{|U|} \\sum_{j=1}^{|V|} \\frac{|U_i\\cap V_j|}{N}
\\log\\frac{N|U_i \\cap V_j|}{|U_i||V_j|}
This metric is independent of the absolute values of the labels:
a permutation of the class or cluster label values won't change the
score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with
``label_pred`` will return the same score value. This can be useful to
measure the agreement of two independent label assignments strategies
on the same dataset when the real ground truth is not known.
Read more in the :ref:`User Guide <mutual_info_score>`.
Parameters
----------
labels_true : int array, shape = [n_samples]
A clustering of the data into disjoint subsets.
labels_pred : int array-like of shape (n_samples,)
A clustering of the data into disjoint subsets.
contingency : {None, array, sparse matrix}, \
shape = [n_classes_true, n_classes_pred]
A contingency matrix given by the :func:`contingency_matrix` function.
If value is ``None``, it will be computed, otherwise the given value is
used, with ``labels_true`` and ``labels_pred`` ignored.
Returns
-------
mi : float
Mutual information, a non-negative value
Notes
-----
The logarithm used is the natural logarithm (base-e).
See also
--------
adjusted_mutual_info_score: Adjusted against chance Mutual Information
normalized_mutual_info_score: Normalized Mutual Information
"""
if contingency is None:
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
contingency = contingency_matrix(labels_true, labels_pred, sparse=True)
else:
contingency = check_array(contingency,
accept_sparse=['csr', 'csc', 'coo'],
dtype=[int, np.int32, np.int64])
if isinstance(contingency, np.ndarray):
# For an array
nzx, nzy = np.nonzero(contingency)
nz_val = contingency[nzx, nzy]
elif sp.issparse(contingency):
# For a sparse matrix
nzx, nzy, nz_val = sp.find(contingency)
else:
raise ValueError("Unsupported type for 'contingency': %s" %
type(contingency))
contingency_sum = contingency.sum()
pi = np.ravel(contingency.sum(axis=1))
pj = np.ravel(contingency.sum(axis=0))
log_contingency_nm = np.log(nz_val)
contingency_nm = nz_val / contingency_sum
# Don't need to calculate the full outer product, just for non-zeroes
outer = (pi.take(nzx).astype(np.int64, copy=False)
* pj.take(nzy).astype(np.int64, copy=False))
log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum())
mi = (contingency_nm * (log_contingency_nm - log(contingency_sum)) +
contingency_nm * log_outer)
return mi.sum() | [
"def",
"mutual_info_score",
"(",
"labels_true",
",",
"labels_pred",
",",
"contingency",
"=",
"None",
")",
":",
"if",
"contingency",
"is",
"None",
":",
"labels_true",
",",
"labels_pred",
"=",
"check_clusterings",
"(",
"labels_true",
",",
"labels_pred",
")",
"contingency",
"=",
"contingency_matrix",
"(",
"labels_true",
",",
"labels_pred",
",",
"sparse",
"=",
"True",
")",
"else",
":",
"contingency",
"=",
"check_array",
"(",
"contingency",
",",
"accept_sparse",
"=",
"[",
"'csr'",
",",
"'csc'",
",",
"'coo'",
"]",
",",
"dtype",
"=",
"[",
"int",
",",
"np",
".",
"int32",
",",
"np",
".",
"int64",
"]",
")",
"if",
"isinstance",
"(",
"contingency",
",",
"np",
".",
"ndarray",
")",
":",
"# For an array",
"nzx",
",",
"nzy",
"=",
"np",
".",
"nonzero",
"(",
"contingency",
")",
"nz_val",
"=",
"contingency",
"[",
"nzx",
",",
"nzy",
"]",
"elif",
"sp",
".",
"issparse",
"(",
"contingency",
")",
":",
"# For a sparse matrix",
"nzx",
",",
"nzy",
",",
"nz_val",
"=",
"sp",
".",
"find",
"(",
"contingency",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unsupported type for 'contingency': %s\"",
"%",
"type",
"(",
"contingency",
")",
")",
"contingency_sum",
"=",
"contingency",
".",
"sum",
"(",
")",
"pi",
"=",
"np",
".",
"ravel",
"(",
"contingency",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
")",
"pj",
"=",
"np",
".",
"ravel",
"(",
"contingency",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
")",
"log_contingency_nm",
"=",
"np",
".",
"log",
"(",
"nz_val",
")",
"contingency_nm",
"=",
"nz_val",
"/",
"contingency_sum",
"# Don't need to calculate the full outer product, just for non-zeroes",
"outer",
"=",
"(",
"pi",
".",
"take",
"(",
"nzx",
")",
".",
"astype",
"(",
"np",
".",
"int64",
",",
"copy",
"=",
"False",
")",
"*",
"pj",
".",
"take",
"(",
"nzy",
")",
".",
"astype",
"(",
"np",
".",
"int64",
",",
"copy",
"=",
"False",
")",
")",
"log_outer",
"=",
"-",
"np",
".",
"log",
"(",
"outer",
")",
"+",
"log",
"(",
"pi",
".",
"sum",
"(",
")",
")",
"+",
"log",
"(",
"pj",
".",
"sum",
"(",
")",
")",
"mi",
"=",
"(",
"contingency_nm",
"*",
"(",
"log_contingency_nm",
"-",
"log",
"(",
"contingency_sum",
")",
")",
"+",
"contingency_nm",
"*",
"log_outer",
")",
"return",
"mi",
".",
"sum",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/metrics/cluster/_supervised.py#L565-L648 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/response.py | python | build_identifiers | (identifiers, parent, params=None, raw_response=None) | return results | Builds a mapping of identifier names to values based on the
identifier source location, type, and target. Identifier
values may be scalars or lists depending on the source type
and location.
:type identifiers: list
:param identifiers: List of :py:class:`~boto3.resources.model.Parameter`
definitions
:type parent: ServiceResource
:param parent: The resource instance to which this action is attached.
:type params: dict
:param params: Request parameters sent to the service.
:type raw_response: dict
:param raw_response: Low-level operation response.
:rtype: list
:return: An ordered list of ``(name, value)`` identifier tuples. | Builds a mapping of identifier names to values based on the
identifier source location, type, and target. Identifier
values may be scalars or lists depending on the source type
and location. | [
"Builds",
"a",
"mapping",
"of",
"identifier",
"names",
"to",
"values",
"based",
"on",
"the",
"identifier",
"source",
"location",
"type",
"and",
"target",
".",
"Identifier",
"values",
"may",
"be",
"scalars",
"or",
"lists",
"depending",
"on",
"the",
"source",
"type",
"and",
"location",
"."
] | def build_identifiers(identifiers, parent, params=None, raw_response=None):
"""
Builds a mapping of identifier names to values based on the
identifier source location, type, and target. Identifier
values may be scalars or lists depending on the source type
and location.
:type identifiers: list
:param identifiers: List of :py:class:`~boto3.resources.model.Parameter`
definitions
:type parent: ServiceResource
:param parent: The resource instance to which this action is attached.
:type params: dict
:param params: Request parameters sent to the service.
:type raw_response: dict
:param raw_response: Low-level operation response.
:rtype: list
:return: An ordered list of ``(name, value)`` identifier tuples.
"""
results = []
for identifier in identifiers:
source = identifier.source
target = identifier.target
if source == 'response':
value = jmespath.search(identifier.path, raw_response)
elif source == 'requestParameter':
value = jmespath.search(identifier.path, params)
elif source == 'identifier':
value = getattr(parent, xform_name(identifier.name))
elif source == 'data':
# If this is a data member then it may incur a load
# action before returning the value.
value = get_data_member(parent, identifier.path)
elif source == 'input':
# This value is set by the user, so ignore it here
continue
else:
raise NotImplementedError(
'Unsupported source type: {0}'.format(source))
results.append((xform_name(target), value))
return results | [
"def",
"build_identifiers",
"(",
"identifiers",
",",
"parent",
",",
"params",
"=",
"None",
",",
"raw_response",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"for",
"identifier",
"in",
"identifiers",
":",
"source",
"=",
"identifier",
".",
"source",
"target",
"=",
"identifier",
".",
"target",
"if",
"source",
"==",
"'response'",
":",
"value",
"=",
"jmespath",
".",
"search",
"(",
"identifier",
".",
"path",
",",
"raw_response",
")",
"elif",
"source",
"==",
"'requestParameter'",
":",
"value",
"=",
"jmespath",
".",
"search",
"(",
"identifier",
".",
"path",
",",
"params",
")",
"elif",
"source",
"==",
"'identifier'",
":",
"value",
"=",
"getattr",
"(",
"parent",
",",
"xform_name",
"(",
"identifier",
".",
"name",
")",
")",
"elif",
"source",
"==",
"'data'",
":",
"# If this is a data member then it may incur a load",
"# action before returning the value.",
"value",
"=",
"get_data_member",
"(",
"parent",
",",
"identifier",
".",
"path",
")",
"elif",
"source",
"==",
"'input'",
":",
"# This value is set by the user, so ignore it here",
"continue",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Unsupported source type: {0}'",
".",
"format",
"(",
"source",
")",
")",
"results",
".",
"append",
"(",
"(",
"xform_name",
"(",
"target",
")",
",",
"value",
")",
")",
"return",
"results"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/boto3/resources/response.py#L32-L76 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/plan/motionplanning.py | python | CSpaceInterface.setDistance | (self, pyDist: object) | return _motionplanning.CSpaceInterface_setDistance(self, pyDist) | r"""
Args:
pyDist (:obj:`object`) | r"""
Args:
pyDist (:obj:`object`) | [
"r",
"Args",
":",
"pyDist",
"(",
":",
"obj",
":",
"object",
")"
] | def setDistance(self, pyDist: object) ->None:
r"""
Args:
pyDist (:obj:`object`)
"""
return _motionplanning.CSpaceInterface_setDistance(self, pyDist) | [
"def",
"setDistance",
"(",
"self",
",",
"pyDist",
":",
"object",
")",
"->",
"None",
":",
"return",
"_motionplanning",
".",
"CSpaceInterface_setDistance",
"(",
"self",
",",
"pyDist",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/plan/motionplanning.py#L552-L557 | |
bareos/bareos | 56a10bb368b0a81e977bb51304033fe49d59efb0 | restapi/bareos_restapi/__init__.py | python | read_client_by_name | (
*,
response: Response,
current_user: User = Depends(get_current_user),
profiles_name: str = Path(..., title="Client name to look for"),
verbose: Optional[bareosBool] = Query("yes", title="Verbose output"),
) | return show_configuration_items(
response=response,
current_user=current_user,
itemType="profiles",
byName=profiles_name,
verbose=verbose,
) | Read all jobdef resources. Built on console command _show profiles_.
Needs at least Bareos Version >= 20.0.0 | Read all jobdef resources. Built on console command _show profiles_. | [
"Read",
"all",
"jobdef",
"resources",
".",
"Built",
"on",
"console",
"command",
"_show",
"profiles_",
"."
] | def read_client_by_name(
*,
response: Response,
current_user: User = Depends(get_current_user),
profiles_name: str = Path(..., title="Client name to look for"),
verbose: Optional[bareosBool] = Query("yes", title="Verbose output"),
):
"""
Read all jobdef resources. Built on console command _show profiles_.
Needs at least Bareos Version >= 20.0.0
"""
return show_configuration_items(
response=response,
current_user=current_user,
itemType="profiles",
byName=profiles_name,
verbose=verbose,
) | [
"def",
"read_client_by_name",
"(",
"*",
",",
"response",
":",
"Response",
",",
"current_user",
":",
"User",
"=",
"Depends",
"(",
"get_current_user",
")",
",",
"profiles_name",
":",
"str",
"=",
"Path",
"(",
"...",
",",
"title",
"=",
"\"Client name to look for\"",
")",
",",
"verbose",
":",
"Optional",
"[",
"bareosBool",
"]",
"=",
"Query",
"(",
"\"yes\"",
",",
"title",
"=",
"\"Verbose output\"",
")",
",",
")",
":",
"return",
"show_configuration_items",
"(",
"response",
"=",
"response",
",",
"current_user",
"=",
"current_user",
",",
"itemType",
"=",
"\"profiles\"",
",",
"byName",
"=",
"profiles_name",
",",
"verbose",
"=",
"verbose",
",",
")"
] | https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/restapi/bareos_restapi/__init__.py#L1838-L1856 | |
miyosuda/TensorFlowAndroidMNIST | 7b5a4603d2780a8a2834575706e9001977524007 | jni-build/jni/include/external/bazel_tools/third_party/py/concurrent/futures/thread.py | python | _remove_dead_thread_references | () | Remove inactive threads from _thread_references.
Should be called periodically to prevent memory leaks in scenarios such as:
>>> while True:
... t = ThreadPoolExecutor(max_workers=5)
... t.map(int, ['1', '2', '3', '4', '5']) | Remove inactive threads from _thread_references. | [
"Remove",
"inactive",
"threads",
"from",
"_thread_references",
"."
] | def _remove_dead_thread_references():
"""Remove inactive threads from _thread_references.
Should be called periodically to prevent memory leaks in scenarios such as:
>>> while True:
... t = ThreadPoolExecutor(max_workers=5)
... t.map(int, ['1', '2', '3', '4', '5'])
"""
for thread_reference in set(_thread_references):
if thread_reference() is None:
_thread_references.discard(thread_reference) | [
"def",
"_remove_dead_thread_references",
"(",
")",
":",
"for",
"thread_reference",
"in",
"set",
"(",
"_thread_references",
")",
":",
"if",
"thread_reference",
"(",
")",
"is",
"None",
":",
"_thread_references",
".",
"discard",
"(",
"thread_reference",
")"
] | https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/external/bazel_tools/third_party/py/concurrent/futures/thread.py#L46-L56 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/sans/algorithm_detail/xml_shapes.py | python | add_xml_shape | (xml, complete_xml_element) | Add an arbitrary shape to region to be masked
:param xml: a list of shapes to which we append here
:param complete_xml_element: description of the shape to add | Add an arbitrary shape to region to be masked
:param xml: a list of shapes to which we append here
:param complete_xml_element: description of the shape to add | [
"Add",
"an",
"arbitrary",
"shape",
"to",
"region",
"to",
"be",
"masked",
":",
"param",
"xml",
":",
"a",
"list",
"of",
"shapes",
"to",
"which",
"we",
"append",
"here",
":",
"param",
"complete_xml_element",
":",
"description",
"of",
"the",
"shape",
"to",
"add"
] | def add_xml_shape(xml, complete_xml_element):
"""
Add an arbitrary shape to region to be masked
:param xml: a list of shapes to which we append here
:param complete_xml_element: description of the shape to add
"""
if not complete_xml_element.startswith('<'):
raise ValueError('Excepted xml string but found: ' + str(complete_xml_element))
xml.append(complete_xml_element) | [
"def",
"add_xml_shape",
"(",
"xml",
",",
"complete_xml_element",
")",
":",
"if",
"not",
"complete_xml_element",
".",
"startswith",
"(",
"'<'",
")",
":",
"raise",
"ValueError",
"(",
"'Excepted xml string but found: '",
"+",
"str",
"(",
"complete_xml_element",
")",
")",
"xml",
".",
"append",
"(",
"complete_xml_element",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/xml_shapes.py#L11-L19 | ||
InsightSoftwareConsortium/ITK | 87acfce9a93d928311c38bc371b666b515b9f19d | Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py | python | declaration_t.name | (self) | return self._get_name_impl() | Declaration name
@type: str | Declaration name
@type: str | [
"Declaration",
"name",
"@type",
":",
"str"
] | def name(self):
"""
Declaration name
@type: str
"""
return self._get_name_impl() | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_get_name_impl",
"(",
")"
] | https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py#L152-L159 | |
danxuhk/ContinuousCRF-CNN | 2b6dcaf179620f118b225ed12c890414ca828e21 | scripts/cpp_lint.py | python | CheckAltTokens | (filename, clean_lines, linenum, error) | Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Check alternative keywords being used in boolean expressions. | [
"Check",
"alternative",
"keywords",
"being",
"used",
"in",
"boolean",
"expressions",
"."
] | def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) | [
"def",
"CheckAltTokens",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Avoid preprocessor lines",
"if",
"Match",
"(",
"r'^\\s*#'",
",",
"line",
")",
":",
"return",
"# Last ditch effort to avoid multi-line comments. This will not help",
"# if the comment started before the current line or ended after the",
"# current line, but it catches most of the false positives. At least,",
"# it provides a way to workaround this warning for people who use",
"# multi-line comments in preprocessor macros.",
"#",
"# TODO(unknown): remove this once cpplint has better support for",
"# multi-line comments.",
"if",
"line",
".",
"find",
"(",
"'/*'",
")",
">=",
"0",
"or",
"line",
".",
"find",
"(",
"'*/'",
")",
">=",
"0",
":",
"return",
"for",
"match",
"in",
"_ALT_TOKEN_REPLACEMENT_PATTERN",
".",
"finditer",
"(",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/alt_tokens'",
",",
"2",
",",
"'Use operator %s instead of %s'",
"%",
"(",
"_ALT_TOKEN_REPLACEMENT",
"[",
"match",
".",
"group",
"(",
"1",
")",
"]",
",",
"match",
".",
"group",
"(",
"1",
")",
")",
")"
] | https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L3409-L3438 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/fourcircle_utility.py | python | get_single_pt_md_name | (exp_number, scan_number, pt_number) | return ws_name | Form the name of the MDEvnetWorkspace for a single Pt. measurement
:param exp_number:
:param scan_number:
:param pt_number:
:return: | Form the name of the MDEvnetWorkspace for a single Pt. measurement
:param exp_number:
:param scan_number:
:param pt_number:
:return: | [
"Form",
"the",
"name",
"of",
"the",
"MDEvnetWorkspace",
"for",
"a",
"single",
"Pt",
".",
"measurement",
":",
"param",
"exp_number",
":",
":",
"param",
"scan_number",
":",
":",
"param",
"pt_number",
":",
":",
"return",
":"
] | def get_single_pt_md_name(exp_number, scan_number, pt_number):
""" Form the name of the MDEvnetWorkspace for a single Pt. measurement
:param exp_number:
:param scan_number:
:param pt_number:
:return:
"""
ws_name = 'HB3A_Exp%d_Scan%d_Pt%d_MD' % (exp_number, scan_number, pt_number)
return ws_name | [
"def",
"get_single_pt_md_name",
"(",
"exp_number",
",",
"scan_number",
",",
"pt_number",
")",
":",
"ws_name",
"=",
"'HB3A_Exp%d_Scan%d_Pt%d_MD'",
"%",
"(",
"exp_number",
",",
"scan_number",
",",
"pt_number",
")",
"return",
"ws_name"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/fourcircle_utility.py#L637-L646 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/managers.py | python | dispatch | (c, id, methodname, args=(), kwds={}) | Send a message to manager using connection `c` and return response | Send a message to manager using connection `c` and return response | [
"Send",
"a",
"message",
"to",
"manager",
"using",
"connection",
"c",
"and",
"return",
"response"
] | def dispatch(c, id, methodname, args=(), kwds={}):
'''
Send a message to manager using connection `c` and return response
'''
c.send((id, methodname, args, kwds))
kind, result = c.recv()
if kind == '#RETURN':
return result
raise convert_to_error(kind, result) | [
"def",
"dispatch",
"(",
"c",
",",
"id",
",",
"methodname",
",",
"args",
"=",
"(",
")",
",",
"kwds",
"=",
"{",
"}",
")",
":",
"c",
".",
"send",
"(",
"(",
"id",
",",
"methodname",
",",
"args",
",",
"kwds",
")",
")",
"kind",
",",
"result",
"=",
"c",
".",
"recv",
"(",
")",
"if",
"kind",
"==",
"'#RETURN'",
":",
"return",
"result",
"raise",
"convert_to_error",
"(",
"kind",
",",
"result",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/managers.py#L74-L82 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | TimeSpan.IsEqualTo | (*args, **kwargs) | return _misc_.TimeSpan_IsEqualTo(*args, **kwargs) | IsEqualTo(self, TimeSpan ts) -> bool | IsEqualTo(self, TimeSpan ts) -> bool | [
"IsEqualTo",
"(",
"self",
"TimeSpan",
"ts",
")",
"-",
">",
"bool"
] | def IsEqualTo(*args, **kwargs):
"""IsEqualTo(self, TimeSpan ts) -> bool"""
return _misc_.TimeSpan_IsEqualTo(*args, **kwargs) | [
"def",
"IsEqualTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"TimeSpan_IsEqualTo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L4502-L4504 | |
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/mavlink_px4.py | python | MAVLink.safety_allowed_area_send | (self, frame, p1x, p1y, p1z, p2x, p2y, p2z) | return self.send(self.safety_allowed_area_encode(frame, p1x, p1y, p1z, p2x, p2y, p2z)) | Read out the safety zone the MAV currently assumes.
frame : Coordinate frame, as defined by MAV_FRAME enum in mavlink_types.h. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (uint8_t)
p1x : x position 1 / Latitude 1 (float)
p1y : y position 1 / Longitude 1 (float)
p1z : z position 1 / Altitude 1 (float)
p2x : x position 2 / Latitude 2 (float)
p2y : y position 2 / Longitude 2 (float)
p2z : z position 2 / Altitude 2 (float) | Read out the safety zone the MAV currently assumes. | [
"Read",
"out",
"the",
"safety",
"zone",
"the",
"MAV",
"currently",
"assumes",
"."
] | def safety_allowed_area_send(self, frame, p1x, p1y, p1z, p2x, p2y, p2z):
'''
Read out the safety zone the MAV currently assumes.
frame : Coordinate frame, as defined by MAV_FRAME enum in mavlink_types.h. Can be either global, GPS, right-handed with Z axis up or local, right handed, Z axis down. (uint8_t)
p1x : x position 1 / Latitude 1 (float)
p1y : y position 1 / Longitude 1 (float)
p1z : z position 1 / Altitude 1 (float)
p2x : x position 2 / Latitude 2 (float)
p2y : y position 2 / Longitude 2 (float)
p2z : z position 2 / Altitude 2 (float)
'''
return self.send(self.safety_allowed_area_encode(frame, p1x, p1y, p1z, p2x, p2y, p2z)) | [
"def",
"safety_allowed_area_send",
"(",
"self",
",",
"frame",
",",
"p1x",
",",
"p1y",
",",
"p1z",
",",
"p2x",
",",
"p2y",
",",
"p2z",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"safety_allowed_area_encode",
"(",
"frame",
",",
"p1x",
",",
"p1y",
",",
"p1z",
",",
"p2x",
",",
"p2y",
",",
"p2z",
")",
")"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L3914-L3927 | |
macchina-io/macchina.io | ef24ba0e18379c3dd48fb84e6dbf991101cb8db0 | platform/JS/V8/tools/gyp/pylib/gyp/MSVSProject.py | python | Writer.__init__ | (self, project_path, version, name, guid=None, platforms=None) | Initializes the project.
Args:
project_path: Path to the project file.
version: Format version to emit.
name: Name of the project.
guid: GUID to use for project, if not None.
platforms: Array of string, the supported platforms. If null, ['Win32'] | Initializes the project. | [
"Initializes",
"the",
"project",
"."
] | def __init__(self, project_path, version, name, guid=None, platforms=None):
"""Initializes the project.
Args:
project_path: Path to the project file.
version: Format version to emit.
name: Name of the project.
guid: GUID to use for project, if not None.
platforms: Array of string, the supported platforms. If null, ['Win32']
"""
self.project_path = project_path
self.version = version
self.name = name
self.guid = guid
# Default to Win32 for platforms.
if not platforms:
platforms = ['Win32']
# Initialize the specifications of the various sections.
self.platform_section = ['Platforms']
for platform in platforms:
self.platform_section.append(['Platform', {'Name': platform}])
self.tool_files_section = ['ToolFiles']
self.configurations_section = ['Configurations']
self.files_section = ['Files']
# Keep a dict keyed on filename to speed up access.
self.files_dict = dict() | [
"def",
"__init__",
"(",
"self",
",",
"project_path",
",",
"version",
",",
"name",
",",
"guid",
"=",
"None",
",",
"platforms",
"=",
"None",
")",
":",
"self",
".",
"project_path",
"=",
"project_path",
"self",
".",
"version",
"=",
"version",
"self",
".",
"name",
"=",
"name",
"self",
".",
"guid",
"=",
"guid",
"# Default to Win32 for platforms.",
"if",
"not",
"platforms",
":",
"platforms",
"=",
"[",
"'Win32'",
"]",
"# Initialize the specifications of the various sections.",
"self",
".",
"platform_section",
"=",
"[",
"'Platforms'",
"]",
"for",
"platform",
"in",
"platforms",
":",
"self",
".",
"platform_section",
".",
"append",
"(",
"[",
"'Platform'",
",",
"{",
"'Name'",
":",
"platform",
"}",
"]",
")",
"self",
".",
"tool_files_section",
"=",
"[",
"'ToolFiles'",
"]",
"self",
".",
"configurations_section",
"=",
"[",
"'Configurations'",
"]",
"self",
".",
"files_section",
"=",
"[",
"'Files'",
"]",
"# Keep a dict keyed on filename to speed up access.",
"self",
".",
"files_dict",
"=",
"dict",
"(",
")"
] | https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/MSVSProject.py#L54-L82 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/timeseries/python/timeseries/state_space_models/structural_ensemble.py | python | MultiResolutionStructuralEnsemble.__init__ | (self,
cycle_num_latent_values,
moving_average_order,
autoregressive_order,
periodicities,
use_level_noise=True,
configuration=state_space_model.StateSpaceModelConfiguration()) | Initialize the multi-resolution structural ensemble.
Args:
cycle_num_latent_values: Controls the model size and the number of latent
values cycled between (but not the periods over which they cycle).
Reducing this parameter can save significant amounts of memory, but
the tradeoff is with resolution: cycling between a smaller number of
latent values means that only smoother functions can be modeled. For
multivariate series, may either be a scalar integer (in which case it
is applied to all periodic components) or a list with length matching
`periodicities`.
moving_average_order: The number of moving average coefficients to use,
which also defines the number of steps after which transient
deviations revert to the mean defined by periodic and level/trend
components. Adds to model size.
autoregressive_order: The number of steps back for
autoregression. Learning autoregressive coefficients typically
requires more steps and a smaller step size than other components.
periodicities: Same meaning as for StructuralEnsemble: number of steps for
cyclic behavior. Floating point and Tensor values are supported. May
be a list of values, in which case one component is created for each
periodicity. If `periodicities` is a list while
`cycle_num_latent_values` is a scalar, its value is broadcast to each
periodic component. Otherwise they should be lists of the same length,
in which case they are paired.
use_level_noise: See StructuralEnsemble.
configuration: A StateSpaceModelConfiguration object.
Raises:
ValueError: If `cycle_num_latent_values` is neither a scalar nor agrees in
size with `periodicities`. | Initialize the multi-resolution structural ensemble. | [
"Initialize",
"the",
"multi",
"-",
"resolution",
"structural",
"ensemble",
"."
] | def __init__(self,
cycle_num_latent_values,
moving_average_order,
autoregressive_order,
periodicities,
use_level_noise=True,
configuration=state_space_model.StateSpaceModelConfiguration()):
"""Initialize the multi-resolution structural ensemble.
Args:
cycle_num_latent_values: Controls the model size and the number of latent
values cycled between (but not the periods over which they cycle).
Reducing this parameter can save significant amounts of memory, but
the tradeoff is with resolution: cycling between a smaller number of
latent values means that only smoother functions can be modeled. For
multivariate series, may either be a scalar integer (in which case it
is applied to all periodic components) or a list with length matching
`periodicities`.
moving_average_order: The number of moving average coefficients to use,
which also defines the number of steps after which transient
deviations revert to the mean defined by periodic and level/trend
components. Adds to model size.
autoregressive_order: The number of steps back for
autoregression. Learning autoregressive coefficients typically
requires more steps and a smaller step size than other components.
periodicities: Same meaning as for StructuralEnsemble: number of steps for
cyclic behavior. Floating point and Tensor values are supported. May
be a list of values, in which case one component is created for each
periodicity. If `periodicities` is a list while
`cycle_num_latent_values` is a scalar, its value is broadcast to each
periodic component. Otherwise they should be lists of the same length,
in which case they are paired.
use_level_noise: See StructuralEnsemble.
configuration: A StateSpaceModelConfiguration object.
Raises:
ValueError: If `cycle_num_latent_values` is neither a scalar nor agrees in
size with `periodicities`.
"""
component_model_configuration = configuration._replace(
use_observation_noise=False)
univariate_component_model_configuration = (
component_model_configuration._replace(
num_features=1))
adder_part = _replicate_level_trend_models(
multivariate_configuration=component_model_configuration,
univariate_configuration=univariate_component_model_configuration)
with variable_scope.variable_scope("varma"):
varma_part = varma.VARMA(
autoregressive_order=autoregressive_order,
moving_average_order=moving_average_order,
configuration=component_model_configuration)
cycle_parts = []
if periodicities is None:
periodicities = []
periodicity_list = nest.flatten(periodicities)
latent_values_list = nest.flatten(cycle_num_latent_values)
if len(periodicity_list) != len(latent_values_list):
if len(latent_values_list) != 1:
raise ValueError(
("`cycle_num_latent_values` must either be a list with the same "
"size as `periodicity` or a scalar. Received length {} "
"`cycle_num_latent_values`, while `periodicities` has length {}.")
.format(len(latent_values_list), len(periodicity_list)))
latent_values_list *= len(periodicity_list)
for cycle_number, (cycle_periodicity, num_latent_values) in enumerate(
zip(periodicity_list, latent_values_list)):
with variable_scope.variable_scope("cycle{}".format(cycle_number)):
cycle_features = []
for feature in range(configuration.num_features):
with variable_scope.variable_scope("feature{}".format(feature)):
cycle_features.append(
periodic.ResolutionCycleModel(
num_latent_values=num_latent_values,
periodicity=cycle_periodicity,
configuration=univariate_component_model_configuration))
cycle_parts.append(
state_space_model.StateSpaceCorrelatedFeaturesEnsemble(
ensemble_members=cycle_features,
configuration=component_model_configuration))
super(MultiResolutionStructuralEnsemble, self).__init__(
ensemble_members=[adder_part, varma_part] + cycle_parts,
configuration=configuration) | [
"def",
"__init__",
"(",
"self",
",",
"cycle_num_latent_values",
",",
"moving_average_order",
",",
"autoregressive_order",
",",
"periodicities",
",",
"use_level_noise",
"=",
"True",
",",
"configuration",
"=",
"state_space_model",
".",
"StateSpaceModelConfiguration",
"(",
")",
")",
":",
"component_model_configuration",
"=",
"configuration",
".",
"_replace",
"(",
"use_observation_noise",
"=",
"False",
")",
"univariate_component_model_configuration",
"=",
"(",
"component_model_configuration",
".",
"_replace",
"(",
"num_features",
"=",
"1",
")",
")",
"adder_part",
"=",
"_replicate_level_trend_models",
"(",
"multivariate_configuration",
"=",
"component_model_configuration",
",",
"univariate_configuration",
"=",
"univariate_component_model_configuration",
")",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"\"varma\"",
")",
":",
"varma_part",
"=",
"varma",
".",
"VARMA",
"(",
"autoregressive_order",
"=",
"autoregressive_order",
",",
"moving_average_order",
"=",
"moving_average_order",
",",
"configuration",
"=",
"component_model_configuration",
")",
"cycle_parts",
"=",
"[",
"]",
"if",
"periodicities",
"is",
"None",
":",
"periodicities",
"=",
"[",
"]",
"periodicity_list",
"=",
"nest",
".",
"flatten",
"(",
"periodicities",
")",
"latent_values_list",
"=",
"nest",
".",
"flatten",
"(",
"cycle_num_latent_values",
")",
"if",
"len",
"(",
"periodicity_list",
")",
"!=",
"len",
"(",
"latent_values_list",
")",
":",
"if",
"len",
"(",
"latent_values_list",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"(",
"\"`cycle_num_latent_values` must either be a list with the same \"",
"\"size as `periodicity` or a scalar. Received length {} \"",
"\"`cycle_num_latent_values`, while `periodicities` has length {}.\"",
")",
".",
"format",
"(",
"len",
"(",
"latent_values_list",
")",
",",
"len",
"(",
"periodicity_list",
")",
")",
")",
"latent_values_list",
"*=",
"len",
"(",
"periodicity_list",
")",
"for",
"cycle_number",
",",
"(",
"cycle_periodicity",
",",
"num_latent_values",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"periodicity_list",
",",
"latent_values_list",
")",
")",
":",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"\"cycle{}\"",
".",
"format",
"(",
"cycle_number",
")",
")",
":",
"cycle_features",
"=",
"[",
"]",
"for",
"feature",
"in",
"range",
"(",
"configuration",
".",
"num_features",
")",
":",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"\"feature{}\"",
".",
"format",
"(",
"feature",
")",
")",
":",
"cycle_features",
".",
"append",
"(",
"periodic",
".",
"ResolutionCycleModel",
"(",
"num_latent_values",
"=",
"num_latent_values",
",",
"periodicity",
"=",
"cycle_periodicity",
",",
"configuration",
"=",
"univariate_component_model_configuration",
")",
")",
"cycle_parts",
".",
"append",
"(",
"state_space_model",
".",
"StateSpaceCorrelatedFeaturesEnsemble",
"(",
"ensemble_members",
"=",
"cycle_features",
",",
"configuration",
"=",
"component_model_configuration",
")",
")",
"super",
"(",
"MultiResolutionStructuralEnsemble",
",",
"self",
")",
".",
"__init__",
"(",
"ensemble_members",
"=",
"[",
"adder_part",
",",
"varma_part",
"]",
"+",
"cycle_parts",
",",
"configuration",
"=",
"configuration",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/state_space_models/structural_ensemble.py#L182-L266 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/slim/python/slim/summaries.py | python | _get_summary_name | (tensor, name=None, prefix=None, postfix=None) | return name | Produces the summary name given.
Args:
tensor: A variable or op `Tensor`.
name: The optional name for the summary.
prefix: An optional prefix for the summary name.
postfix: An optional postfix for the summary name.
Returns:
a summary name. | Produces the summary name given. | [
"Produces",
"the",
"summary",
"name",
"given",
"."
] | def _get_summary_name(tensor, name=None, prefix=None, postfix=None):
"""Produces the summary name given.
Args:
tensor: A variable or op `Tensor`.
name: The optional name for the summary.
prefix: An optional prefix for the summary name.
postfix: An optional postfix for the summary name.
Returns:
a summary name.
"""
if not name:
name = tensor.op.name
if prefix:
name = prefix + '/' + name
if postfix:
name = name + '/' + postfix
return name | [
"def",
"_get_summary_name",
"(",
"tensor",
",",
"name",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"postfix",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"name",
"=",
"tensor",
".",
"op",
".",
"name",
"if",
"prefix",
":",
"name",
"=",
"prefix",
"+",
"'/'",
"+",
"name",
"if",
"postfix",
":",
"name",
"=",
"name",
"+",
"'/'",
"+",
"postfix",
"return",
"name"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/slim/python/slim/summaries.py#L42-L60 | |
infinisql/infinisql | 6e858e142196e20b6779e1ee84c4a501e246c1f8 | manager/infinisqlmgr/engine/state.py | python | ConfigurationState.on_get_topology_mgr_mbox_ptr | (self, sock) | Handles a GET_TOPOLOGY_MANAGER_MAILBOX_POINTER response.
:param sock: The socket to read from.
:return: None | Handles a GET_TOPOLOGY_MANAGER_MAILBOX_POINTER response.
:param sock: The socket to read from.
:return: None | [
"Handles",
"a",
"GET_TOPOLOGY_MANAGER_MAILBOX_POINTER",
"response",
".",
":",
"param",
"sock",
":",
"The",
"socket",
"to",
"read",
"from",
".",
":",
"return",
":",
"None"
] | def on_get_topology_mgr_mbox_ptr(self, sock):
"""
Handles a GET_TOPOLOGY_MANAGER_MAILBOX_POINTER response.
:param sock: The socket to read from.
:return: None
"""
stream = self._recv(sock)
result = next(stream)
if result != cfg.CMD_OK:
logging.error("Expected CMD_OK, but received %s", result)
return False
mbox_ptr = next(stream)
self.add_actor(1, cfg.ACTOR_TOPOLOGYMGR, -1, mbox_ptr)
self.update_node(sock) | [
"def",
"on_get_topology_mgr_mbox_ptr",
"(",
"self",
",",
"sock",
")",
":",
"stream",
"=",
"self",
".",
"_recv",
"(",
"sock",
")",
"result",
"=",
"next",
"(",
"stream",
")",
"if",
"result",
"!=",
"cfg",
".",
"CMD_OK",
":",
"logging",
".",
"error",
"(",
"\"Expected CMD_OK, but received %s\"",
",",
"result",
")",
"return",
"False",
"mbox_ptr",
"=",
"next",
"(",
"stream",
")",
"self",
".",
"add_actor",
"(",
"1",
",",
"cfg",
".",
"ACTOR_TOPOLOGYMGR",
",",
"-",
"1",
",",
"mbox_ptr",
")",
"self",
".",
"update_node",
"(",
"sock",
")"
] | https://github.com/infinisql/infinisql/blob/6e858e142196e20b6779e1ee84c4a501e246c1f8/manager/infinisqlmgr/engine/state.py#L88-L101 | ||
infinit/elle | a8154593c42743f45b9df09daf62b44630c24a02 | drake/src/drake/cxx/__init__.py | python | GccToolkit.basename | (self) | return self.__split()[1] | The compiler basename, e.g., `clang++`. | The compiler basename, e.g., `clang++`. | [
"The",
"compiler",
"basename",
"e",
".",
"g",
".",
"clang",
"++",
"."
] | def basename(self):
'''The compiler basename, e.g., `clang++`.'''
return self.__split()[1] | [
"def",
"basename",
"(",
"self",
")",
":",
"return",
"self",
".",
"__split",
"(",
")",
"[",
"1",
"]"
] | https://github.com/infinit/elle/blob/a8154593c42743f45b9df09daf62b44630c24a02/drake/src/drake/cxx/__init__.py#L1116-L1118 | |
lballabio/quantlib-old | 136336947ed4fea9ecc1da6edad188700e821739 | gensrc/gensrc/addins/excel.py | python | ExcelAddin.generateRegisterFunction | (self, func, categoryName, register = True) | return self.bufferRegisterFunction_.set({
'category' : categoryName,
'categoryLen' : self.checkLen(categoryName),
'delim' : delim,
'funcDesc' : funcDesc,
'funcDescLen' : self.checkLen(funcDesc),
'functionName' : func.name(),
'functionNameLen' : self.checkLen(func.name()),
'functionType' : functionType,
'numParams' : numRegisterParams,
'parameterList' : func.parameterList().generate(self.registerParameters_),
'paramNames' : paramNames,
'paramNamesLen' : self.checkLen(paramNames),
'paramStr' : paramStr,
'paramStrLen' : self.checkLen(paramStr),
'unregister' : unregister }) | Generate code to register/unregister given function. | Generate code to register/unregister given function. | [
"Generate",
"code",
"to",
"register",
"/",
"unregister",
"given",
"function",
"."
] | def generateRegisterFunction(self, func, categoryName, register = True):
"""Generate code to register/unregister given function."""
paramStr = self.xlRegisterReturn_.apply(func.returnValue()) \
+ func.parameterList().generate(self.xlRegisterParam_)
if func.xlMacro():
paramStr += '#'
paramNames = func.parameterList().generate(self.parameterList_)
if len(paramNames) > MAX_LEN_PARAMLIST:
raise excelexceptions.ExcelParameterLengthException(
func.name(), paramNames, MAX_LEN_PARAMLIST)
# Configure call to xlfRegister. We will pass in NUMDESC params to
# register the function, plus one additional param to describe each
# param in the function being registered. If we exceed the limit of
# MAXPARAM values accepted by xlfRegister we omit descriptions as necessary.
numUserParams = min(func.parameterList().parameterCount(), MAXUSERPARAM)
numRegisterParams = numUserParams + NUMDESC
# A bug in the Excel Function Wizard causes the last string to be corrupted.
# The workaround is to pad the last string with two spaces:
# - If the function has parameters then the last parameter will get padded
# in rule.py according to RuleGroup attribute "padLastParamName='True'"
# - If the function has no parameters then the function description will be
# the last parameter and we pad it here.
if numUserParams:
funcDesc = func.description()
delim = ','
else:
funcDesc = func.description() + ' '
delim = ''
if register:
functionType = func.visible()
unregister = ''
else:
functionType = 0
unregister = UNREGISTER % (len(func.name()), func.name())
# Confirm that parameter descriptions don't exceed max Excel string length.
for param in func.parameterList().parameters():
self.checkLen(param.description())
return self.bufferRegisterFunction_.set({
'category' : categoryName,
'categoryLen' : self.checkLen(categoryName),
'delim' : delim,
'funcDesc' : funcDesc,
'funcDescLen' : self.checkLen(funcDesc),
'functionName' : func.name(),
'functionNameLen' : self.checkLen(func.name()),
'functionType' : functionType,
'numParams' : numRegisterParams,
'parameterList' : func.parameterList().generate(self.registerParameters_),
'paramNames' : paramNames,
'paramNamesLen' : self.checkLen(paramNames),
'paramStr' : paramStr,
'paramStrLen' : self.checkLen(paramStr),
'unregister' : unregister }) | [
"def",
"generateRegisterFunction",
"(",
"self",
",",
"func",
",",
"categoryName",
",",
"register",
"=",
"True",
")",
":",
"paramStr",
"=",
"self",
".",
"xlRegisterReturn_",
".",
"apply",
"(",
"func",
".",
"returnValue",
"(",
")",
")",
"+",
"func",
".",
"parameterList",
"(",
")",
".",
"generate",
"(",
"self",
".",
"xlRegisterParam_",
")",
"if",
"func",
".",
"xlMacro",
"(",
")",
":",
"paramStr",
"+=",
"'#'",
"paramNames",
"=",
"func",
".",
"parameterList",
"(",
")",
".",
"generate",
"(",
"self",
".",
"parameterList_",
")",
"if",
"len",
"(",
"paramNames",
")",
">",
"MAX_LEN_PARAMLIST",
":",
"raise",
"excelexceptions",
".",
"ExcelParameterLengthException",
"(",
"func",
".",
"name",
"(",
")",
",",
"paramNames",
",",
"MAX_LEN_PARAMLIST",
")",
"# Configure call to xlfRegister. We will pass in NUMDESC params to",
"# register the function, plus one additional param to describe each",
"# param in the function being registered. If we exceed the limit of",
"# MAXPARAM values accepted by xlfRegister we omit descriptions as necessary.",
"numUserParams",
"=",
"min",
"(",
"func",
".",
"parameterList",
"(",
")",
".",
"parameterCount",
"(",
")",
",",
"MAXUSERPARAM",
")",
"numRegisterParams",
"=",
"numUserParams",
"+",
"NUMDESC",
"# A bug in the Excel Function Wizard causes the last string to be corrupted.",
"# The workaround is to pad the last string with two spaces:",
"# - If the function has parameters then the last parameter will get padded",
"# in rule.py according to RuleGroup attribute \"padLastParamName='True'\"",
"# - If the function has no parameters then the function description will be",
"# the last parameter and we pad it here.",
"if",
"numUserParams",
":",
"funcDesc",
"=",
"func",
".",
"description",
"(",
")",
"delim",
"=",
"','",
"else",
":",
"funcDesc",
"=",
"func",
".",
"description",
"(",
")",
"+",
"' '",
"delim",
"=",
"''",
"if",
"register",
":",
"functionType",
"=",
"func",
".",
"visible",
"(",
")",
"unregister",
"=",
"''",
"else",
":",
"functionType",
"=",
"0",
"unregister",
"=",
"UNREGISTER",
"%",
"(",
"len",
"(",
"func",
".",
"name",
"(",
")",
")",
",",
"func",
".",
"name",
"(",
")",
")",
"# Confirm that parameter descriptions don't exceed max Excel string length.",
"for",
"param",
"in",
"func",
".",
"parameterList",
"(",
")",
".",
"parameters",
"(",
")",
":",
"self",
".",
"checkLen",
"(",
"param",
".",
"description",
"(",
")",
")",
"return",
"self",
".",
"bufferRegisterFunction_",
".",
"set",
"(",
"{",
"'category'",
":",
"categoryName",
",",
"'categoryLen'",
":",
"self",
".",
"checkLen",
"(",
"categoryName",
")",
",",
"'delim'",
":",
"delim",
",",
"'funcDesc'",
":",
"funcDesc",
",",
"'funcDescLen'",
":",
"self",
".",
"checkLen",
"(",
"funcDesc",
")",
",",
"'functionName'",
":",
"func",
".",
"name",
"(",
")",
",",
"'functionNameLen'",
":",
"self",
".",
"checkLen",
"(",
"func",
".",
"name",
"(",
")",
")",
",",
"'functionType'",
":",
"functionType",
",",
"'numParams'",
":",
"numRegisterParams",
",",
"'parameterList'",
":",
"func",
".",
"parameterList",
"(",
")",
".",
"generate",
"(",
"self",
".",
"registerParameters_",
")",
",",
"'paramNames'",
":",
"paramNames",
",",
"'paramNamesLen'",
":",
"self",
".",
"checkLen",
"(",
"paramNames",
")",
",",
"'paramStr'",
":",
"paramStr",
",",
"'paramStrLen'",
":",
"self",
".",
"checkLen",
"(",
"paramStr",
")",
",",
"'unregister'",
":",
"unregister",
"}",
")"
] | https://github.com/lballabio/quantlib-old/blob/136336947ed4fea9ecc1da6edad188700e821739/gensrc/gensrc/addins/excel.py#L175-L233 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/SHA1.py | python | _pbkdf2_hmac_assist | (inner, outer, first_digest, iterations) | return get_raw_buffer(bfr) | Compute the expensive inner loop in PBKDF-HMAC. | Compute the expensive inner loop in PBKDF-HMAC. | [
"Compute",
"the",
"expensive",
"inner",
"loop",
"in",
"PBKDF",
"-",
"HMAC",
"."
] | def _pbkdf2_hmac_assist(inner, outer, first_digest, iterations):
"""Compute the expensive inner loop in PBKDF-HMAC."""
assert len(first_digest) == digest_size
assert iterations > 0
bfr = create_string_buffer(digest_size);
result = _raw_sha1_lib.SHA1_pbkdf2_hmac_assist(
inner._state.get(),
outer._state.get(),
first_digest,
bfr,
c_size_t(iterations))
if result:
raise ValueError("Error %d with PBKDF2-HMAC assis for SHA1" % result)
return get_raw_buffer(bfr) | [
"def",
"_pbkdf2_hmac_assist",
"(",
"inner",
",",
"outer",
",",
"first_digest",
",",
"iterations",
")",
":",
"assert",
"len",
"(",
"first_digest",
")",
"==",
"digest_size",
"assert",
"iterations",
">",
"0",
"bfr",
"=",
"create_string_buffer",
"(",
"digest_size",
")",
"result",
"=",
"_raw_sha1_lib",
".",
"SHA1_pbkdf2_hmac_assist",
"(",
"inner",
".",
"_state",
".",
"get",
"(",
")",
",",
"outer",
".",
"_state",
".",
"get",
"(",
")",
",",
"first_digest",
",",
"bfr",
",",
"c_size_t",
"(",
"iterations",
")",
")",
"if",
"result",
":",
"raise",
"ValueError",
"(",
"\"Error %d with PBKDF2-HMAC assis for SHA1\"",
"%",
"result",
")",
"return",
"get_raw_buffer",
"(",
"bfr",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Hash/SHA1.py#L168-L185 | |
rrwick/Porechop | 109e437280436d1ec27e5a5b7a34ffb752176390 | porechop/nanopore_read.py | python | NanoporeRead.formatted_start_seq | (self, end_size, extra_trim_size) | return formatted_str | Returns the start of the read sequence, with any found adapters highlighted in red. | Returns the start of the read sequence, with any found adapters highlighted in red. | [
"Returns",
"the",
"start",
"of",
"the",
"read",
"sequence",
"with",
"any",
"found",
"adapters",
"highlighted",
"in",
"red",
"."
] | def formatted_start_seq(self, end_size, extra_trim_size):
"""
Returns the start of the read sequence, with any found adapters highlighted in red.
"""
start_seq = self.seq[:end_size]
if not self.start_trim_amount:
return start_seq
red_bases = self.start_trim_amount - extra_trim_size
formatted_str = ''
if red_bases:
formatted_str = red(start_seq[:red_bases])
formatted_str += yellow(start_seq[red_bases:red_bases+extra_trim_size])
formatted_str += start_seq[red_bases+extra_trim_size:]
return formatted_str | [
"def",
"formatted_start_seq",
"(",
"self",
",",
"end_size",
",",
"extra_trim_size",
")",
":",
"start_seq",
"=",
"self",
".",
"seq",
"[",
":",
"end_size",
"]",
"if",
"not",
"self",
".",
"start_trim_amount",
":",
"return",
"start_seq",
"red_bases",
"=",
"self",
".",
"start_trim_amount",
"-",
"extra_trim_size",
"formatted_str",
"=",
"''",
"if",
"red_bases",
":",
"formatted_str",
"=",
"red",
"(",
"start_seq",
"[",
":",
"red_bases",
"]",
")",
"formatted_str",
"+=",
"yellow",
"(",
"start_seq",
"[",
"red_bases",
":",
"red_bases",
"+",
"extra_trim_size",
"]",
")",
"formatted_str",
"+=",
"start_seq",
"[",
"red_bases",
"+",
"extra_trim_size",
":",
"]",
"return",
"formatted_str"
] | https://github.com/rrwick/Porechop/blob/109e437280436d1ec27e5a5b7a34ffb752176390/porechop/nanopore_read.py#L245-L258 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | ScrollHelper.AdjustScrollbars | (*args, **kwargs) | return _windows_.ScrollHelper_AdjustScrollbars(*args, **kwargs) | AdjustScrollbars(self) | AdjustScrollbars(self) | [
"AdjustScrollbars",
"(",
"self",
")"
] | def AdjustScrollbars(*args, **kwargs):
"""AdjustScrollbars(self)"""
return _windows_.ScrollHelper_AdjustScrollbars(*args, **kwargs) | [
"def",
"AdjustScrollbars",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"ScrollHelper_AdjustScrollbars",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L233-L235 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/solvers/python/ops/linear_equations.py | python | conjugate_gradient | (operator,
rhs,
tol=1e-4,
max_iter=20,
name="conjugate_gradient") | r"""Conjugate gradient solver.
Solves a linear system of equations `A*x = rhs` for selfadjoint, positive
definite matrix `A` and righ-hand side vector `rhs`, using an iterative,
matrix-free algorithm where the action of the matrix A is represented by
`operator`. The iteration terminates when either the number of iterations
exceeds `max_iter` or when the residual norm has been reduced to `tol`
times its initial value, i.e. \\(||rhs - A x_k|| <= tol ||rhs||\\).
Args:
operator: An object representing a linear operator with attributes:
- shape: Either a list of integers or a 1-D `Tensor` of type `int32` of
length 2. `shape[0]` is the dimension on the domain of the operator,
`shape[1]` is the dimension of the co-domain of the operator. On other
words, if operator represents an N x N matrix A, `shape` must contain
`[N, N]`.
- dtype: The datatype of input to and output from `apply`.
- apply: Callable object taking a vector `x` as input and returning a
vector with the result of applying the operator to `x`, i.e. if
`operator` represents matrix `A`, `apply` should return `A * x`.
rhs: A rank-1 `Tensor` of shape `[N]` containing the right-hand size vector.
tol: A float scalar convergence tolerance.
max_iter: An integer giving the maximum number of iterations.
name: A name scope for the operation.
Returns:
output: A namedtuple representing the final state with fields:
- i: A scalar `int32` `Tensor`. Number of iterations executed.
- x: A rank-1 `Tensor` of shape `[N]` containing the computed solution.
- r: A rank-1 `Tensor` of shape `[M]` containing the residual vector.
- p: A rank-1 `Tensor` of shape `[N]`. `A`-conjugate basis vector.
- gamma: \\(||r||_2^2\\) | r"""Conjugate gradient solver. | [
"r",
"Conjugate",
"gradient",
"solver",
"."
] | def conjugate_gradient(operator,
rhs,
tol=1e-4,
max_iter=20,
name="conjugate_gradient"):
r"""Conjugate gradient solver.
Solves a linear system of equations `A*x = rhs` for selfadjoint, positive
definite matrix `A` and righ-hand side vector `rhs`, using an iterative,
matrix-free algorithm where the action of the matrix A is represented by
`operator`. The iteration terminates when either the number of iterations
exceeds `max_iter` or when the residual norm has been reduced to `tol`
times its initial value, i.e. \\(||rhs - A x_k|| <= tol ||rhs||\\).
Args:
operator: An object representing a linear operator with attributes:
- shape: Either a list of integers or a 1-D `Tensor` of type `int32` of
length 2. `shape[0]` is the dimension on the domain of the operator,
`shape[1]` is the dimension of the co-domain of the operator. On other
words, if operator represents an N x N matrix A, `shape` must contain
`[N, N]`.
- dtype: The datatype of input to and output from `apply`.
- apply: Callable object taking a vector `x` as input and returning a
vector with the result of applying the operator to `x`, i.e. if
`operator` represents matrix `A`, `apply` should return `A * x`.
rhs: A rank-1 `Tensor` of shape `[N]` containing the right-hand size vector.
tol: A float scalar convergence tolerance.
max_iter: An integer giving the maximum number of iterations.
name: A name scope for the operation.
Returns:
output: A namedtuple representing the final state with fields:
- i: A scalar `int32` `Tensor`. Number of iterations executed.
- x: A rank-1 `Tensor` of shape `[N]` containing the computed solution.
- r: A rank-1 `Tensor` of shape `[M]` containing the residual vector.
- p: A rank-1 `Tensor` of shape `[N]`. `A`-conjugate basis vector.
- gamma: \\(||r||_2^2\\)
"""
# ephemeral class holding CG state.
cg_state = collections.namedtuple("CGState", ["i", "x", "r", "p", "gamma"])
def stopping_criterion(i, state):
return math_ops.logical_and(i < max_iter, state.gamma > tol)
# TODO(rmlarsen): add preconditioning
def cg_step(i, state):
z = operator.apply(state.p)
alpha = state.gamma / util.dot(state.p, z)
x = state.x + alpha * state.p
r = state.r - alpha * z
gamma = util.l2norm_squared(r)
beta = gamma / state.gamma
p = r + beta * state.p
return i + 1, cg_state(i + 1, x, r, p, gamma)
with ops.name_scope(name):
n = operator.shape[1:]
rhs = array_ops.expand_dims(rhs, -1)
gamma0 = util.l2norm_squared(rhs)
tol = tol * tol * gamma0
x = array_ops.expand_dims(
array_ops.zeros(
n, dtype=rhs.dtype.base_dtype), -1)
i = constant_op.constant(0, dtype=dtypes.int32)
state = cg_state(i=i, x=x, r=rhs, p=rhs, gamma=gamma0)
_, state = control_flow_ops.while_loop(stopping_criterion, cg_step,
[i, state])
return cg_state(
state.i,
x=array_ops.squeeze(state.x),
r=array_ops.squeeze(state.r),
p=array_ops.squeeze(state.p),
gamma=state.gamma) | [
"def",
"conjugate_gradient",
"(",
"operator",
",",
"rhs",
",",
"tol",
"=",
"1e-4",
",",
"max_iter",
"=",
"20",
",",
"name",
"=",
"\"conjugate_gradient\"",
")",
":",
"# ephemeral class holding CG state.",
"cg_state",
"=",
"collections",
".",
"namedtuple",
"(",
"\"CGState\"",
",",
"[",
"\"i\"",
",",
"\"x\"",
",",
"\"r\"",
",",
"\"p\"",
",",
"\"gamma\"",
"]",
")",
"def",
"stopping_criterion",
"(",
"i",
",",
"state",
")",
":",
"return",
"math_ops",
".",
"logical_and",
"(",
"i",
"<",
"max_iter",
",",
"state",
".",
"gamma",
">",
"tol",
")",
"# TODO(rmlarsen): add preconditioning",
"def",
"cg_step",
"(",
"i",
",",
"state",
")",
":",
"z",
"=",
"operator",
".",
"apply",
"(",
"state",
".",
"p",
")",
"alpha",
"=",
"state",
".",
"gamma",
"/",
"util",
".",
"dot",
"(",
"state",
".",
"p",
",",
"z",
")",
"x",
"=",
"state",
".",
"x",
"+",
"alpha",
"*",
"state",
".",
"p",
"r",
"=",
"state",
".",
"r",
"-",
"alpha",
"*",
"z",
"gamma",
"=",
"util",
".",
"l2norm_squared",
"(",
"r",
")",
"beta",
"=",
"gamma",
"/",
"state",
".",
"gamma",
"p",
"=",
"r",
"+",
"beta",
"*",
"state",
".",
"p",
"return",
"i",
"+",
"1",
",",
"cg_state",
"(",
"i",
"+",
"1",
",",
"x",
",",
"r",
",",
"p",
",",
"gamma",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
")",
":",
"n",
"=",
"operator",
".",
"shape",
"[",
"1",
":",
"]",
"rhs",
"=",
"array_ops",
".",
"expand_dims",
"(",
"rhs",
",",
"-",
"1",
")",
"gamma0",
"=",
"util",
".",
"l2norm_squared",
"(",
"rhs",
")",
"tol",
"=",
"tol",
"*",
"tol",
"*",
"gamma0",
"x",
"=",
"array_ops",
".",
"expand_dims",
"(",
"array_ops",
".",
"zeros",
"(",
"n",
",",
"dtype",
"=",
"rhs",
".",
"dtype",
".",
"base_dtype",
")",
",",
"-",
"1",
")",
"i",
"=",
"constant_op",
".",
"constant",
"(",
"0",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"state",
"=",
"cg_state",
"(",
"i",
"=",
"i",
",",
"x",
"=",
"x",
",",
"r",
"=",
"rhs",
",",
"p",
"=",
"rhs",
",",
"gamma",
"=",
"gamma0",
")",
"_",
",",
"state",
"=",
"control_flow_ops",
".",
"while_loop",
"(",
"stopping_criterion",
",",
"cg_step",
",",
"[",
"i",
",",
"state",
"]",
")",
"return",
"cg_state",
"(",
"state",
".",
"i",
",",
"x",
"=",
"array_ops",
".",
"squeeze",
"(",
"state",
".",
"x",
")",
",",
"r",
"=",
"array_ops",
".",
"squeeze",
"(",
"state",
".",
"r",
")",
",",
"p",
"=",
"array_ops",
".",
"squeeze",
"(",
"state",
".",
"p",
")",
",",
"gamma",
"=",
"state",
".",
"gamma",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/solvers/python/ops/linear_equations.py#L32-L104 | ||
ArmageddonGames/ZeldaClassic | c244ae6c1d361d24a5529b1c0394e656f1f5d965 | allegro/addons/allegrogl/misc/zipup.py | python | get_files | () | return [f.path for f in files if f.is_versioned and f.entry and
f.entry.kind == pysvn.node_kind.file] | Find all SVN files to include in the release. | Find all SVN files to include in the release. | [
"Find",
"all",
"SVN",
"files",
"to",
"include",
"in",
"the",
"release",
"."
] | def get_files():
"""Find all SVN files to include in the release."""
client = pysvn.Client()
files = client.status(".", recurse = True, get_all = True)
return [f.path for f in files if f.is_versioned and f.entry and
f.entry.kind == pysvn.node_kind.file] | [
"def",
"get_files",
"(",
")",
":",
"client",
"=",
"pysvn",
".",
"Client",
"(",
")",
"files",
"=",
"client",
".",
"status",
"(",
"\".\"",
",",
"recurse",
"=",
"True",
",",
"get_all",
"=",
"True",
")",
"return",
"[",
"f",
".",
"path",
"for",
"f",
"in",
"files",
"if",
"f",
".",
"is_versioned",
"and",
"f",
".",
"entry",
"and",
"f",
".",
"entry",
".",
"kind",
"==",
"pysvn",
".",
"node_kind",
".",
"file",
"]"
] | https://github.com/ArmageddonGames/ZeldaClassic/blob/c244ae6c1d361d24a5529b1c0394e656f1f5d965/allegro/addons/allegrogl/misc/zipup.py#L12-L19 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_misc.py | python | DateTime.ToGMT | (*args, **kwargs) | return _misc_.DateTime_ToGMT(*args, **kwargs) | ToGMT(self, bool noDST=False) -> DateTime | ToGMT(self, bool noDST=False) -> DateTime | [
"ToGMT",
"(",
"self",
"bool",
"noDST",
"=",
"False",
")",
"-",
">",
"DateTime"
] | def ToGMT(*args, **kwargs):
"""ToGMT(self, bool noDST=False) -> DateTime"""
return _misc_.DateTime_ToGMT(*args, **kwargs) | [
"def",
"ToGMT",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateTime_ToGMT",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L3946-L3948 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewIndexListModel.GetAttrByRow | (*args, **kwargs) | return _dataview.DataViewIndexListModel_GetAttrByRow(*args, **kwargs) | GetAttrByRow(self, unsigned int row, unsigned int col, DataViewItemAttr attr) -> bool
Override this to indicate that the item has special font
attributes. This only affects the `DataViewTextRenderer` renderer.
Return ``False`` if the default attributes should be used. | GetAttrByRow(self, unsigned int row, unsigned int col, DataViewItemAttr attr) -> bool | [
"GetAttrByRow",
"(",
"self",
"unsigned",
"int",
"row",
"unsigned",
"int",
"col",
"DataViewItemAttr",
"attr",
")",
"-",
">",
"bool"
] | def GetAttrByRow(*args, **kwargs):
"""
GetAttrByRow(self, unsigned int row, unsigned int col, DataViewItemAttr attr) -> bool
Override this to indicate that the item has special font
attributes. This only affects the `DataViewTextRenderer` renderer.
Return ``False`` if the default attributes should be used.
"""
return _dataview.DataViewIndexListModel_GetAttrByRow(*args, **kwargs) | [
"def",
"GetAttrByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewIndexListModel_GetAttrByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L828-L836 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py | python | Semaphore | (*args, **kwargs) | return _Semaphore(*args, **kwargs) | A factory function that returns a new semaphore.
Semaphores manage a counter representing the number of release() calls minus
the number of acquire() calls, plus an initial value. The acquire() method
blocks if necessary until it can return without making the counter
negative. If not given, value defaults to 1. | A factory function that returns a new semaphore. | [
"A",
"factory",
"function",
"that",
"returns",
"a",
"new",
"semaphore",
"."
] | def Semaphore(*args, **kwargs):
"""A factory function that returns a new semaphore.
Semaphores manage a counter representing the number of release() calls minus
the number of acquire() calls, plus an initial value. The acquire() method
blocks if necessary until it can return without making the counter
negative. If not given, value defaults to 1.
"""
return _Semaphore(*args, **kwargs) | [
"def",
"Semaphore",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_Semaphore",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/threading.py#L411-L420 | |
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/internal/encoder.py | python | _VarintBytes | (value) | return "".join(pieces) | Encode the given integer as a varint and return the bytes. This is only
called at startup time so it doesn't need to be fast. | Encode the given integer as a varint and return the bytes. This is only
called at startup time so it doesn't need to be fast. | [
"Encode",
"the",
"given",
"integer",
"as",
"a",
"varint",
"and",
"return",
"the",
"bytes",
".",
"This",
"is",
"only",
"called",
"at",
"startup",
"time",
"so",
"it",
"doesn",
"t",
"need",
"to",
"be",
"fast",
"."
] | def _VarintBytes(value):
"""Encode the given integer as a varint and return the bytes. This is only
called at startup time so it doesn't need to be fast."""
pieces = []
_EncodeVarint(pieces.append, value)
return "".join(pieces) | [
"def",
"_VarintBytes",
"(",
"value",
")",
":",
"pieces",
"=",
"[",
"]",
"_EncodeVarint",
"(",
"pieces",
".",
"append",
",",
"value",
")",
"return",
"\"\"",
".",
"join",
"(",
"pieces",
")"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/internal/encoder.py#L379-L385 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py | python | MergeGlobalXcodeSettingsToSpec | (global_dict, spec) | Merges the global xcode_settings dictionary into each configuration of the
target represented by spec. For keys that are both in the global and the local
xcode_settings dict, the local key gets precedence. | Merges the global xcode_settings dictionary into each configuration of the
target represented by spec. For keys that are both in the global and the local
xcode_settings dict, the local key gets precedence. | [
"Merges",
"the",
"global",
"xcode_settings",
"dictionary",
"into",
"each",
"configuration",
"of",
"the",
"target",
"represented",
"by",
"spec",
".",
"For",
"keys",
"that",
"are",
"both",
"in",
"the",
"global",
"and",
"the",
"local",
"xcode_settings",
"dict",
"the",
"local",
"key",
"gets",
"precedence",
"."
] | def MergeGlobalXcodeSettingsToSpec(global_dict, spec):
"""Merges the global xcode_settings dictionary into each configuration of the
target represented by spec. For keys that are both in the global and the local
xcode_settings dict, the local key gets precedence.
"""
# The xcode generator special-cases global xcode_settings and does something
# that amounts to merging in the global xcode_settings into each local
# xcode_settings dict.
global_xcode_settings = global_dict.get('xcode_settings', {})
for config in spec['configurations'].values():
if 'xcode_settings' in config:
new_settings = global_xcode_settings.copy()
new_settings.update(config['xcode_settings'])
config['xcode_settings'] = new_settings | [
"def",
"MergeGlobalXcodeSettingsToSpec",
"(",
"global_dict",
",",
"spec",
")",
":",
"# The xcode generator special-cases global xcode_settings and does something",
"# that amounts to merging in the global xcode_settings into each local",
"# xcode_settings dict.",
"global_xcode_settings",
"=",
"global_dict",
".",
"get",
"(",
"'xcode_settings'",
",",
"{",
"}",
")",
"for",
"config",
"in",
"spec",
"[",
"'configurations'",
"]",
".",
"values",
"(",
")",
":",
"if",
"'xcode_settings'",
"in",
"config",
":",
"new_settings",
"=",
"global_xcode_settings",
".",
"copy",
"(",
")",
"new_settings",
".",
"update",
"(",
"config",
"[",
"'xcode_settings'",
"]",
")",
"config",
"[",
"'xcode_settings'",
"]",
"=",
"new_settings"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L1345-L1358 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | Sizer.InsertStretchSpacer | (self, index, prop=1) | return self.Insert(index, (0,0), prop) | InsertStretchSpacer(int index, int prop=1) --> SizerItem
Insert a stretchable spacer. | InsertStretchSpacer(int index, int prop=1) --> SizerItem | [
"InsertStretchSpacer",
"(",
"int",
"index",
"int",
"prop",
"=",
"1",
")",
"--",
">",
"SizerItem"
] | def InsertStretchSpacer(self, index, prop=1):
"""InsertStretchSpacer(int index, int prop=1) --> SizerItem
Insert a stretchable spacer."""
return self.Insert(index, (0,0), prop) | [
"def",
"InsertStretchSpacer",
"(",
"self",
",",
"index",
",",
"prop",
"=",
"1",
")",
":",
"return",
"self",
".",
"Insert",
"(",
"index",
",",
"(",
"0",
",",
"0",
")",
",",
"prop",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L14705-L14709 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/locale.py | python | _parse_localename | (localename) | Parses the locale code for localename and returns the
result as tuple (language code, encoding).
The localename is normalized and passed through the locale
alias engine. A ValueError is raised in case the locale name
cannot be parsed.
The language code corresponds to RFC 1766. code and encoding
can be None in case the values cannot be determined or are
unknown to this implementation. | Parses the locale code for localename and returns the
result as tuple (language code, encoding). | [
"Parses",
"the",
"locale",
"code",
"for",
"localename",
"and",
"returns",
"the",
"result",
"as",
"tuple",
"(",
"language",
"code",
"encoding",
")",
"."
] | def _parse_localename(localename):
""" Parses the locale code for localename and returns the
result as tuple (language code, encoding).
The localename is normalized and passed through the locale
alias engine. A ValueError is raised in case the locale name
cannot be parsed.
The language code corresponds to RFC 1766. code and encoding
can be None in case the values cannot be determined or are
unknown to this implementation.
"""
code = normalize(localename)
if '@' in code:
# Deal with locale modifiers
code, modifier = code.split('@', 1)
if modifier == 'euro' and '.' not in code:
# Assume Latin-9 for @euro locales. This is bogus,
# since some systems may use other encodings for these
# locales. Also, we ignore other modifiers.
return code, 'iso-8859-15'
if '.' in code:
return tuple(code.split('.')[:2])
elif code == 'C':
return None, None
elif code == 'UTF-8':
# On macOS "LC_CTYPE=UTF-8" is a valid locale setting
# for getting UTF-8 handling for text.
return None, 'UTF-8'
raise ValueError('unknown locale: %s' % localename) | [
"def",
"_parse_localename",
"(",
"localename",
")",
":",
"code",
"=",
"normalize",
"(",
"localename",
")",
"if",
"'@'",
"in",
"code",
":",
"# Deal with locale modifiers",
"code",
",",
"modifier",
"=",
"code",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"if",
"modifier",
"==",
"'euro'",
"and",
"'.'",
"not",
"in",
"code",
":",
"# Assume Latin-9 for @euro locales. This is bogus,",
"# since some systems may use other encodings for these",
"# locales. Also, we ignore other modifiers.",
"return",
"code",
",",
"'iso-8859-15'",
"if",
"'.'",
"in",
"code",
":",
"return",
"tuple",
"(",
"code",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"2",
"]",
")",
"elif",
"code",
"==",
"'C'",
":",
"return",
"None",
",",
"None",
"elif",
"code",
"==",
"'UTF-8'",
":",
"# On macOS \"LC_CTYPE=UTF-8\" is a valid locale setting",
"# for getting UTF-8 handling for text.",
"return",
"None",
",",
"'UTF-8'",
"raise",
"ValueError",
"(",
"'unknown locale: %s'",
"%",
"localename",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/locale.py#L467-L499 | ||
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus2.in.py | python | exodus.put_elem_blk_name | (self, id, name) | exo.put_elem_blk_name(elem_blk_id, elem_blk_name)
-> store the element block name
input value(s):
<int> elem_blk_id element block *ID* (not *INDEX*)
<string> elem_blk_name | exo.put_elem_blk_name(elem_blk_id, elem_blk_name) | [
"exo",
".",
"put_elem_blk_name",
"(",
"elem_blk_id",
"elem_blk_name",
")"
] | def put_elem_blk_name(self, id, name):
"""
exo.put_elem_blk_name(elem_blk_id, elem_blk_name)
-> store the element block name
input value(s):
<int> elem_blk_id element block *ID* (not *INDEX*)
<string> elem_blk_name
"""
objType = ex_entity_type("EX_ELEM_BLOCK")
self.__ex_put_name(objType, id, name) | [
"def",
"put_elem_blk_name",
"(",
"self",
",",
"id",
",",
"name",
")",
":",
"objType",
"=",
"ex_entity_type",
"(",
"\"EX_ELEM_BLOCK\"",
")",
"self",
".",
"__ex_put_name",
"(",
"objType",
",",
"id",
",",
"name",
")"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus2.in.py#L1245-L1256 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/python2_version/klampt/robotsim.py | python | SimBody.setTransform | (self, R, t) | return _robotsim.SimBody_setTransform(self, R, t) | setTransform(SimBody self, double const [9] R, double const [3] t)
Sets the body's transformation at the current simulation time step (in center-
of-mass centered coordinates). | setTransform(SimBody self, double const [9] R, double const [3] t) | [
"setTransform",
"(",
"SimBody",
"self",
"double",
"const",
"[",
"9",
"]",
"R",
"double",
"const",
"[",
"3",
"]",
"t",
")"
] | def setTransform(self, R, t):
"""
setTransform(SimBody self, double const [9] R, double const [3] t)
Sets the body's transformation at the current simulation time step (in center-
of-mass centered coordinates).
"""
return _robotsim.SimBody_setTransform(self, R, t) | [
"def",
"setTransform",
"(",
"self",
",",
"R",
",",
"t",
")",
":",
"return",
"_robotsim",
".",
"SimBody_setTransform",
"(",
"self",
",",
"R",
",",
"t",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L7943-L7953 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py | python | yield_lines | (strs) | Yield non-empty/non-comment lines of a string or sequence | Yield non-empty/non-comment lines of a string or sequence | [
"Yield",
"non",
"-",
"empty",
"/",
"non",
"-",
"comment",
"lines",
"of",
"a",
"string",
"or",
"sequence"
] | def yield_lines(strs):
"""Yield non-empty/non-comment lines of a string or sequence"""
if isinstance(strs, six.string_types):
for s in strs.splitlines():
s = s.strip()
# skip blank lines/comments
if s and not s.startswith('#'):
yield s
else:
for ss in strs:
for s in yield_lines(ss):
yield s | [
"def",
"yield_lines",
"(",
"strs",
")",
":",
"if",
"isinstance",
"(",
"strs",
",",
"six",
".",
"string_types",
")",
":",
"for",
"s",
"in",
"strs",
".",
"splitlines",
"(",
")",
":",
"s",
"=",
"s",
".",
"strip",
"(",
")",
"# skip blank lines/comments",
"if",
"s",
"and",
"not",
"s",
".",
"startswith",
"(",
"'#'",
")",
":",
"yield",
"s",
"else",
":",
"for",
"ss",
"in",
"strs",
":",
"for",
"s",
"in",
"yield_lines",
"(",
"ss",
")",
":",
"yield",
"s"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py#L2369-L2380 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | ConfigBase.Get | (*args, **kwargs) | return _misc_.ConfigBase_Get(*args, **kwargs) | Get(bool createOnDemand=True) -> ConfigBase
Returns the current global config object, creating one if neccessary. | Get(bool createOnDemand=True) -> ConfigBase | [
"Get",
"(",
"bool",
"createOnDemand",
"=",
"True",
")",
"-",
">",
"ConfigBase"
] | def Get(*args, **kwargs):
"""
Get(bool createOnDemand=True) -> ConfigBase
Returns the current global config object, creating one if neccessary.
"""
return _misc_.ConfigBase_Get(*args, **kwargs) | [
"def",
"Get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"ConfigBase_Get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L3113-L3119 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pydocview.py | python | DocTabbedChildFrame.OnTitleIsModified | (self) | Add/remove to the frame's title an indication that the document is dirty.
If the document is dirty, an '*' is appended to the title | Add/remove to the frame's title an indication that the document is dirty.
If the document is dirty, an '*' is appended to the title | [
"Add",
"/",
"remove",
"to",
"the",
"frame",
"s",
"title",
"an",
"indication",
"that",
"the",
"document",
"is",
"dirty",
".",
"If",
"the",
"document",
"is",
"dirty",
"an",
"*",
"is",
"appended",
"to",
"the",
"title"
] | def OnTitleIsModified(self):
"""
Add/remove to the frame's title an indication that the document is dirty.
If the document is dirty, an '*' is appended to the title
"""
title = self.GetTitle()
if title:
if self.GetDocument().IsModified():
if not title.endswith("*"):
title = title + "*"
self.SetTitle(title)
else:
if title.endswith("*"):
title = title[:-1]
self.SetTitle(title) | [
"def",
"OnTitleIsModified",
"(",
"self",
")",
":",
"title",
"=",
"self",
".",
"GetTitle",
"(",
")",
"if",
"title",
":",
"if",
"self",
".",
"GetDocument",
"(",
")",
".",
"IsModified",
"(",
")",
":",
"if",
"not",
"title",
".",
"endswith",
"(",
"\"*\"",
")",
":",
"title",
"=",
"title",
"+",
"\"*\"",
"self",
".",
"SetTitle",
"(",
"title",
")",
"else",
":",
"if",
"title",
".",
"endswith",
"(",
"\"*\"",
")",
":",
"title",
"=",
"title",
"[",
":",
"-",
"1",
"]",
"self",
".",
"SetTitle",
"(",
"title",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pydocview.py#L666-L680 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/gui/Dialogs.py | python | show_keyboard_shortcuts | (parent) | Display keyboard shortcut-keys. | Display keyboard shortcut-keys. | [
"Display",
"keyboard",
"shortcut",
"-",
"keys",
"."
] | def show_keyboard_shortcuts(parent):
""" Display keyboard shortcut-keys. """
markup = textwrap.dedent("""\
<b>Keyboard Shortcuts</b>
\n\
<u>Ctrl+N</u>: Create a new flowgraph.
<u>Ctrl+O</u>: Open an existing flowgraph.
<u>Ctrl+S</u>: Save the current flowgraph or save as for new.
<u>Ctrl+W</u>: Close the current flowgraph.
<u>Ctrl+Z</u>: Undo a change to the flowgraph.
<u>Ctrl+Y</u>: Redo a change to the flowgraph.
<u>Ctrl+A</u>: Selects all blocks and connections.
<u>Ctrl+P</u>: Screen Capture of the Flowgraph.
<u>Ctrl+Shift+P</u>: Save the console output to file.
<u>Ctrl+L</u>: Clear the console.
<u>Ctrl+E</u>: Show variable editor.
<u>Ctrl+F</u>: Search for a block by name.
<u>Ctrl+Q</u>: Quit.
<u>F1</u> : Help menu.
<u>F5</u> : Generate the Flowgraph.
<u>F6</u> : Execute the Flowgraph.
<u>F7</u> : Kill the Flowgraph.
<u>Ctrl+Shift+S</u>: Save as the current flowgraph.
<u>Ctrl+Shift+D</u>: Create a duplicate of current flow graph.
<u>Ctrl+X/C/V</u>: Edit-cut/copy/paste.
<u>Ctrl+D/B/R</u>: Toggle visibility of disabled blocks or
connections/block tree widget/console.
<u>Shift+T/M/B/L/C/R</u>: Vertical Align Top/Middle/Bottom and
Horizontal Align Left/Center/Right respectively of the
selected block.
<u>Ctrl+0</u>: Reset the zoom level
<u>Ctrl++/-</u>: Zoom in and out
\
""")
markup = markup.replace("Ctrl", Utils.get_modifier_key())
MessageDialogWrapper(
parent, Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, title='Keyboard - Shortcuts', markup=markup
).run_and_destroy() | [
"def",
"show_keyboard_shortcuts",
"(",
"parent",
")",
":",
"markup",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\\\n <b>Keyboard Shortcuts</b>\n \\n\\\n <u>Ctrl+N</u>: Create a new flowgraph.\n <u>Ctrl+O</u>: Open an existing flowgraph.\n <u>Ctrl+S</u>: Save the current flowgraph or save as for new.\n <u>Ctrl+W</u>: Close the current flowgraph.\n <u>Ctrl+Z</u>: Undo a change to the flowgraph.\n <u>Ctrl+Y</u>: Redo a change to the flowgraph.\n <u>Ctrl+A</u>: Selects all blocks and connections.\n <u>Ctrl+P</u>: Screen Capture of the Flowgraph.\n <u>Ctrl+Shift+P</u>: Save the console output to file.\n <u>Ctrl+L</u>: Clear the console.\n <u>Ctrl+E</u>: Show variable editor.\n <u>Ctrl+F</u>: Search for a block by name.\n <u>Ctrl+Q</u>: Quit.\n <u>F1</u> : Help menu.\n <u>F5</u> : Generate the Flowgraph.\n <u>F6</u> : Execute the Flowgraph.\n <u>F7</u> : Kill the Flowgraph.\n <u>Ctrl+Shift+S</u>: Save as the current flowgraph.\n <u>Ctrl+Shift+D</u>: Create a duplicate of current flow graph.\n\n <u>Ctrl+X/C/V</u>: Edit-cut/copy/paste.\n <u>Ctrl+D/B/R</u>: Toggle visibility of disabled blocks or\n connections/block tree widget/console.\n <u>Shift+T/M/B/L/C/R</u>: Vertical Align Top/Middle/Bottom and\n Horizontal Align Left/Center/Right respectively of the\n selected block.\n <u>Ctrl+0</u>: Reset the zoom level\n <u>Ctrl++/-</u>: Zoom in and out\n \\\n \"\"\"",
")",
"markup",
"=",
"markup",
".",
"replace",
"(",
"\"Ctrl\"",
",",
"Utils",
".",
"get_modifier_key",
"(",
")",
")",
"MessageDialogWrapper",
"(",
"parent",
",",
"Gtk",
".",
"MessageType",
".",
"INFO",
",",
"Gtk",
".",
"ButtonsType",
".",
"CLOSE",
",",
"title",
"=",
"'Keyboard - Shortcuts'",
",",
"markup",
"=",
"markup",
")",
".",
"run_and_destroy",
"(",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/Dialogs.py#L316-L355 | ||
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/constraint_solver/doc/routing_svg.py | python | SVGPrinter.draw_demands | (self) | Draws all the demands. | Draws all the demands. | [
"Draws",
"all",
"the",
"demands",
"."
] | def draw_demands(self):
"""Draws all the demands."""
print(r'<!-- Print demands -->')
for idx, loc in enumerate(self._data.locations):
if idx == self._data.depot:
continue
demand = self._data.demands[idx]
position = [
x + y
for x, y in zip(loc, [self._radius * 1.2, self._radius * 1.1])
]
color = self._color_palette.value_from_name('red')
# color = self._color_palette.value(int(math.log(demand, 2)))
self._svg.draw_text(demand, position, self._radius, 'none', color) | [
"def",
"draw_demands",
"(",
"self",
")",
":",
"print",
"(",
"r'<!-- Print demands -->'",
")",
"for",
"idx",
",",
"loc",
"in",
"enumerate",
"(",
"self",
".",
"_data",
".",
"locations",
")",
":",
"if",
"idx",
"==",
"self",
".",
"_data",
".",
"depot",
":",
"continue",
"demand",
"=",
"self",
".",
"_data",
".",
"demands",
"[",
"idx",
"]",
"position",
"=",
"[",
"x",
"+",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"loc",
",",
"[",
"self",
".",
"_radius",
"*",
"1.2",
",",
"self",
".",
"_radius",
"*",
"1.1",
"]",
")",
"]",
"color",
"=",
"self",
".",
"_color_palette",
".",
"value_from_name",
"(",
"'red'",
")",
"# color = self._color_palette.value(int(math.log(demand, 2)))",
"self",
".",
"_svg",
".",
"draw_text",
"(",
"demand",
",",
"position",
",",
"self",
".",
"_radius",
",",
"'none'",
",",
"color",
")"
] | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/constraint_solver/doc/routing_svg.py#L486-L499 | ||
physercoe/starquant | c00cad64d1de2da05081b3dc320ef264c6295e08 | source/engine/strategy_engine.py | python | StrategyEngine._init_strategy | (self) | Init strategies in queue. | Init strategies in queue. | [
"Init",
"strategies",
"in",
"queue",
"."
] | def _init_strategy(self):
"""
Init strategies in queue.
"""
while not self.init_queue.empty():
strategy_name = self.init_queue.get()
strategy = self.strategies[strategy_name]
if strategy.inited:
self.write_log(f"{strategy_name}已经完成初始化,禁止重复操作")
continue
self.write_log(f"{strategy_name}开始执行初始化")
# Call on_init function of strategy
self.call_strategy_func(strategy, strategy.on_init)
# Restore strategy data(variables)
data = self.strategy_data.get(strategy_name, None)
if data:
for name in strategy.variables:
value = data.get(name, None)
if value:
setattr(strategy, name, value)
# Subscribe market data
contract = self.get_contract(strategy.full_symbol)
if contract:
m = Event(type=EventType.SUBSCRIBE,
msgtype=MSG_TYPE.MSG_TYPE_SUBSCRIBE_MARKET_DATA)
m.destination = "CTP.MD"
m.source = str(self.id)
req = SubscribeRequest()
req.sym_type = SYMBOL_TYPE.CTP
req.content = contract.symbol
m.data = req
self._send_sock.send(m.serialize())
else:
self.write_log(f"行情订阅失败,找不到合约{strategy.full_symbol}", strategy)
# qry pos and acc
m = Event(type=EventType.QRY, msgtype=MSG_TYPE.MSG_TYPE_QRY_POS)
m.destination = strategy.api + '.' + strategy.account
m.source = str(self.id)
self._send_sock.send(m.serialize())
m = Event(type=EventType.QRY,
msgtype=MSG_TYPE.MSG_TYPE_QRY_ACCOUNT)
m.destination = strategy.api + '.' + strategy.account
m.source = str(self.id)
self._send_sock.send(m.serialize())
# Put event to update init completed status.
strategy.inited = True
self.put_strategy_event(strategy)
self.write_log(f"{strategy_name}初始化完成")
self.init_thread = None | [
"def",
"_init_strategy",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"init_queue",
".",
"empty",
"(",
")",
":",
"strategy_name",
"=",
"self",
".",
"init_queue",
".",
"get",
"(",
")",
"strategy",
"=",
"self",
".",
"strategies",
"[",
"strategy_name",
"]",
"if",
"strategy",
".",
"inited",
":",
"self",
".",
"write_log",
"(",
"f\"{strategy_name}已经完成初始化,禁止重复操作\")",
"",
"continue",
"self",
".",
"write_log",
"(",
"f\"{strategy_name}开始执行初始化\")",
"",
"# Call on_init function of strategy",
"self",
".",
"call_strategy_func",
"(",
"strategy",
",",
"strategy",
".",
"on_init",
")",
"# Restore strategy data(variables)",
"data",
"=",
"self",
".",
"strategy_data",
".",
"get",
"(",
"strategy_name",
",",
"None",
")",
"if",
"data",
":",
"for",
"name",
"in",
"strategy",
".",
"variables",
":",
"value",
"=",
"data",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"value",
":",
"setattr",
"(",
"strategy",
",",
"name",
",",
"value",
")",
"# Subscribe market data",
"contract",
"=",
"self",
".",
"get_contract",
"(",
"strategy",
".",
"full_symbol",
")",
"if",
"contract",
":",
"m",
"=",
"Event",
"(",
"type",
"=",
"EventType",
".",
"SUBSCRIBE",
",",
"msgtype",
"=",
"MSG_TYPE",
".",
"MSG_TYPE_SUBSCRIBE_MARKET_DATA",
")",
"m",
".",
"destination",
"=",
"\"CTP.MD\"",
"m",
".",
"source",
"=",
"str",
"(",
"self",
".",
"id",
")",
"req",
"=",
"SubscribeRequest",
"(",
")",
"req",
".",
"sym_type",
"=",
"SYMBOL_TYPE",
".",
"CTP",
"req",
".",
"content",
"=",
"contract",
".",
"symbol",
"m",
".",
"data",
"=",
"req",
"self",
".",
"_send_sock",
".",
"send",
"(",
"m",
".",
"serialize",
"(",
")",
")",
"else",
":",
"self",
".",
"write_log",
"(",
"f\"行情订阅失败,找不到合约{strategy.full_symbol}\", strategy)",
"",
"",
"",
"# qry pos and acc",
"m",
"=",
"Event",
"(",
"type",
"=",
"EventType",
".",
"QRY",
",",
"msgtype",
"=",
"MSG_TYPE",
".",
"MSG_TYPE_QRY_POS",
")",
"m",
".",
"destination",
"=",
"strategy",
".",
"api",
"+",
"'.'",
"+",
"strategy",
".",
"account",
"m",
".",
"source",
"=",
"str",
"(",
"self",
".",
"id",
")",
"self",
".",
"_send_sock",
".",
"send",
"(",
"m",
".",
"serialize",
"(",
")",
")",
"m",
"=",
"Event",
"(",
"type",
"=",
"EventType",
".",
"QRY",
",",
"msgtype",
"=",
"MSG_TYPE",
".",
"MSG_TYPE_QRY_ACCOUNT",
")",
"m",
".",
"destination",
"=",
"strategy",
".",
"api",
"+",
"'.'",
"+",
"strategy",
".",
"account",
"m",
".",
"source",
"=",
"str",
"(",
"self",
".",
"id",
")",
"self",
".",
"_send_sock",
".",
"send",
"(",
"m",
".",
"serialize",
"(",
")",
")",
"# Put event to update init completed status.",
"strategy",
".",
"inited",
"=",
"True",
"self",
".",
"put_strategy_event",
"(",
"strategy",
")",
"self",
".",
"write_log",
"(",
"f\"{strategy_name}初始化完成\")",
"",
"self",
".",
"init_thread",
"=",
"None"
] | https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/source/engine/strategy_engine.py#L452-L509 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | addon-sdk/source/python-lib/mozrunner/killableprocess.py | python | check_call | (*args, **kwargs) | Call a program with an optional timeout. If the program has a non-zero
exit status, raises a CalledProcessError. | Call a program with an optional timeout. If the program has a non-zero
exit status, raises a CalledProcessError. | [
"Call",
"a",
"program",
"with",
"an",
"optional",
"timeout",
".",
"If",
"the",
"program",
"has",
"a",
"non",
"-",
"zero",
"exit",
"status",
"raises",
"a",
"CalledProcessError",
"."
] | def check_call(*args, **kwargs):
"""Call a program with an optional timeout. If the program has a non-zero
exit status, raises a CalledProcessError."""
retcode = call(*args, **kwargs)
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = args[0]
raise CalledProcessError(retcode, cmd) | [
"def",
"check_call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"retcode",
"=",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"retcode",
":",
"cmd",
"=",
"kwargs",
".",
"get",
"(",
"\"args\"",
")",
"if",
"cmd",
"is",
"None",
":",
"cmd",
"=",
"args",
"[",
"0",
"]",
"raise",
"CalledProcessError",
"(",
"retcode",
",",
"cmd",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/addon-sdk/source/python-lib/mozrunner/killableprocess.py#L91-L100 | ||
smilehao/xlua-framework | a03801538be2b0e92d39332d445b22caca1ef61f | ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/text_format.py | python | _Tokenizer.TryConsume | (self, token) | return False | Tries to consume a given piece of text.
Args:
token: Text to consume.
Returns:
True iff the text was consumed. | Tries to consume a given piece of text. | [
"Tries",
"to",
"consume",
"a",
"given",
"piece",
"of",
"text",
"."
] | def TryConsume(self, token):
"""Tries to consume a given piece of text.
Args:
token: Text to consume.
Returns:
True iff the text was consumed.
"""
if self.token == token:
self.NextToken()
return True
return False | [
"def",
"TryConsume",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"token",
"==",
"token",
":",
"self",
".",
"NextToken",
"(",
")",
"return",
"True",
"return",
"False"
] | https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/text_format.py#L354-L366 | |
facebookincubator/BOLT | 88c70afe9d388ad430cc150cc158641701397f70 | clang/tools/scan-build-py/lib/libscanbuild/report.py | python | read_bugs | (output_dir, html) | Generate a unique sequence of bugs from given output directory.
Duplicates can be in a project if the same module was compiled multiple
times with different compiler options. These would be better to show in
the final report (cover) only once. | Generate a unique sequence of bugs from given output directory. | [
"Generate",
"a",
"unique",
"sequence",
"of",
"bugs",
"from",
"given",
"output",
"directory",
"."
] | def read_bugs(output_dir, html):
# type: (str, bool) -> Generator[Dict[str, Any], None, None]
""" Generate a unique sequence of bugs from given output directory.
Duplicates can be in a project if the same module was compiled multiple
times with different compiler options. These would be better to show in
the final report (cover) only once. """
def empty(file_name):
return os.stat(file_name).st_size == 0
duplicate = duplicate_check(
lambda bug: '{bug_line}.{bug_path_length}:{bug_file}'.format(**bug))
# get the right parser for the job.
parser = parse_bug_html if html else parse_bug_plist
# get the input files, which are not empty.
pattern = os.path.join(output_dir, '*.html' if html else '*.plist')
bug_files = (file for file in glob.iglob(pattern) if not empty(file))
for bug_file in bug_files:
for bug in parser(bug_file):
if not duplicate(bug):
yield bug | [
"def",
"read_bugs",
"(",
"output_dir",
",",
"html",
")",
":",
"# type: (str, bool) -> Generator[Dict[str, Any], None, None]",
"def",
"empty",
"(",
"file_name",
")",
":",
"return",
"os",
".",
"stat",
"(",
"file_name",
")",
".",
"st_size",
"==",
"0",
"duplicate",
"=",
"duplicate_check",
"(",
"lambda",
"bug",
":",
"'{bug_line}.{bug_path_length}:{bug_file}'",
".",
"format",
"(",
"*",
"*",
"bug",
")",
")",
"# get the right parser for the job.",
"parser",
"=",
"parse_bug_html",
"if",
"html",
"else",
"parse_bug_plist",
"# get the input files, which are not empty.",
"pattern",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'*.html'",
"if",
"html",
"else",
"'*.plist'",
")",
"bug_files",
"=",
"(",
"file",
"for",
"file",
"in",
"glob",
".",
"iglob",
"(",
"pattern",
")",
"if",
"not",
"empty",
"(",
"file",
")",
")",
"for",
"bug_file",
"in",
"bug_files",
":",
"for",
"bug",
"in",
"parser",
"(",
"bug_file",
")",
":",
"if",
"not",
"duplicate",
"(",
"bug",
")",
":",
"yield",
"bug"
] | https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/tools/scan-build-py/lib/libscanbuild/report.py#L261-L284 | ||
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/PathList.py | python | _PathList.__init__ | (self, pathlist) | Initializes a PathList object, canonicalizing the input and
pre-processing it for quicker substitution later.
The stored representation of the PathList is a list of tuples
containing (type, value), where the "type" is one of the TYPE_*
variables defined above. We distinguish between:
strings that contain no '$' and therefore need no
delayed-evaluation string substitution (we expect that there
will be many of these and that we therefore get a pretty
big win from avoiding string substitution)
strings that contain '$' and therefore need substitution
(the hard case is things like '${TARGET.dir}/include',
which require re-evaluation for every target + source)
other objects (which may be something like an EntryProxy
that needs a method called to return a Node)
Pre-identifying the type of each element in the PathList up-front
and storing the type in the list of tuples is intended to reduce
the amount of calculation when we actually do the substitution
over and over for each target. | Initializes a PathList object, canonicalizing the input and
pre-processing it for quicker substitution later. | [
"Initializes",
"a",
"PathList",
"object",
"canonicalizing",
"the",
"input",
"and",
"pre",
"-",
"processing",
"it",
"for",
"quicker",
"substitution",
"later",
"."
] | def __init__(self, pathlist):
"""
Initializes a PathList object, canonicalizing the input and
pre-processing it for quicker substitution later.
The stored representation of the PathList is a list of tuples
containing (type, value), where the "type" is one of the TYPE_*
variables defined above. We distinguish between:
strings that contain no '$' and therefore need no
delayed-evaluation string substitution (we expect that there
will be many of these and that we therefore get a pretty
big win from avoiding string substitution)
strings that contain '$' and therefore need substitution
(the hard case is things like '${TARGET.dir}/include',
which require re-evaluation for every target + source)
other objects (which may be something like an EntryProxy
that needs a method called to return a Node)
Pre-identifying the type of each element in the PathList up-front
and storing the type in the list of tuples is intended to reduce
the amount of calculation when we actually do the substitution
over and over for each target.
"""
if SCons.Util.is_String(pathlist):
pathlist = pathlist.split(os.pathsep)
elif not SCons.Util.is_Sequence(pathlist):
pathlist = [pathlist]
pl = []
for p in pathlist:
try:
found = '$' in p
except (AttributeError, TypeError):
type = TYPE_OBJECT
else:
if not found:
type = TYPE_STRING_NO_SUBST
else:
type = TYPE_STRING_SUBST
pl.append((type, p))
self.pathlist = tuple(pl) | [
"def",
"__init__",
"(",
"self",
",",
"pathlist",
")",
":",
"if",
"SCons",
".",
"Util",
".",
"is_String",
"(",
"pathlist",
")",
":",
"pathlist",
"=",
"pathlist",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"elif",
"not",
"SCons",
".",
"Util",
".",
"is_Sequence",
"(",
"pathlist",
")",
":",
"pathlist",
"=",
"[",
"pathlist",
"]",
"pl",
"=",
"[",
"]",
"for",
"p",
"in",
"pathlist",
":",
"try",
":",
"found",
"=",
"'$'",
"in",
"p",
"except",
"(",
"AttributeError",
",",
"TypeError",
")",
":",
"type",
"=",
"TYPE_OBJECT",
"else",
":",
"if",
"not",
"found",
":",
"type",
"=",
"TYPE_STRING_NO_SUBST",
"else",
":",
"type",
"=",
"TYPE_STRING_SUBST",
"pl",
".",
"append",
"(",
"(",
"type",
",",
"p",
")",
")",
"self",
".",
"pathlist",
"=",
"tuple",
"(",
"pl",
")"
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/PathList.py#L73-L117 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/imghdr.py | python | test_pgm | (h, f) | PGM (portable graymap) | PGM (portable graymap) | [
"PGM",
"(",
"portable",
"graymap",
")"
] | def test_pgm(h, f):
"""PGM (portable graymap)"""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r':
return 'pgm' | [
"def",
"test_pgm",
"(",
"h",
",",
"f",
")",
":",
"if",
"len",
"(",
"h",
")",
">=",
"3",
"and",
"h",
"[",
"0",
"]",
"==",
"ord",
"(",
"b'P'",
")",
"and",
"h",
"[",
"1",
"]",
"in",
"b'25'",
"and",
"h",
"[",
"2",
"]",
"in",
"b' \\t\\n\\r'",
":",
"return",
"'pgm'"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/imghdr.py#L79-L83 | ||
Lavender105/DFF | 152397cec4a3dac2aa86e92a65cc27e6c8016ab9 | exps/models/dff.py | python | get_dff | (dataset='cityscapes', backbone='resnet50', pretrained=False,
root='./pretrain_models', **kwargs) | return model | r"""DFF model from the paper "Dynamic Feature Fusion for Semantic Edge Detection" | r"""DFF model from the paper "Dynamic Feature Fusion for Semantic Edge Detection" | [
"r",
"DFF",
"model",
"from",
"the",
"paper",
"Dynamic",
"Feature",
"Fusion",
"for",
"Semantic",
"Edge",
"Detection"
] | def get_dff(dataset='cityscapes', backbone='resnet50', pretrained=False,
root='./pretrain_models', **kwargs):
r"""DFF model from the paper "Dynamic Feature Fusion for Semantic Edge Detection"
"""
acronyms = {
'cityscapes': 'cityscapes',
'sbd': 'sbd',
}
# infer number of classes
from datasets import datasets
model = DFF(datasets[dataset.lower()].NUM_CLASS, backbone=backbone, root=root, **kwargs)
if pretrained:
from .model_store import get_model_file
model.load_state_dict(torch.load(
get_model_file('fcn_%s_%s'%(backbone, acronyms[dataset]), root=root)),
strict=False)
return model | [
"def",
"get_dff",
"(",
"dataset",
"=",
"'cityscapes'",
",",
"backbone",
"=",
"'resnet50'",
",",
"pretrained",
"=",
"False",
",",
"root",
"=",
"'./pretrain_models'",
",",
"*",
"*",
"kwargs",
")",
":",
"acronyms",
"=",
"{",
"'cityscapes'",
":",
"'cityscapes'",
",",
"'sbd'",
":",
"'sbd'",
",",
"}",
"# infer number of classes",
"from",
"datasets",
"import",
"datasets",
"model",
"=",
"DFF",
"(",
"datasets",
"[",
"dataset",
".",
"lower",
"(",
")",
"]",
".",
"NUM_CLASS",
",",
"backbone",
"=",
"backbone",
",",
"root",
"=",
"root",
",",
"*",
"*",
"kwargs",
")",
"if",
"pretrained",
":",
"from",
".",
"model_store",
"import",
"get_model_file",
"model",
".",
"load_state_dict",
"(",
"torch",
".",
"load",
"(",
"get_model_file",
"(",
"'fcn_%s_%s'",
"%",
"(",
"backbone",
",",
"acronyms",
"[",
"dataset",
"]",
")",
",",
"root",
"=",
"root",
")",
")",
",",
"strict",
"=",
"False",
")",
"return",
"model"
] | https://github.com/Lavender105/DFF/blob/152397cec4a3dac2aa86e92a65cc27e6c8016ab9/exps/models/dff.py#L108-L124 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py2/numpy/lib/mixins.py | python | _numeric_methods | (ufunc, name) | return (_binary_method(ufunc, name),
_reflected_binary_method(ufunc, name),
_inplace_binary_method(ufunc, name)) | Implement forward, reflected and inplace binary methods with a ufunc. | Implement forward, reflected and inplace binary methods with a ufunc. | [
"Implement",
"forward",
"reflected",
"and",
"inplace",
"binary",
"methods",
"with",
"a",
"ufunc",
"."
] | def _numeric_methods(ufunc, name):
"""Implement forward, reflected and inplace binary methods with a ufunc."""
return (_binary_method(ufunc, name),
_reflected_binary_method(ufunc, name),
_inplace_binary_method(ufunc, name)) | [
"def",
"_numeric_methods",
"(",
"ufunc",
",",
"name",
")",
":",
"return",
"(",
"_binary_method",
"(",
"ufunc",
",",
"name",
")",
",",
"_reflected_binary_method",
"(",
"ufunc",
",",
"name",
")",
",",
"_inplace_binary_method",
"(",
"ufunc",
",",
"name",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/lib/mixins.py#L48-L52 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/SANS/isis_reduction_steps.py | python | DarkRunSubtraction._execute_dark_run_subtraction_monitors | (self, monitor_workspace, setting, workspace_was_event) | return out_ws | Apply one dark run setting to a monitor workspace
@param monitor_workspace: the monitor data set associated with the scatter data
@param setting: a dark run settings tuple
@param workspace_was_event: flag if the original workspace was derived from histo or event
@returns a monitor for the dark run | Apply one dark run setting to a monitor workspace | [
"Apply",
"one",
"dark",
"run",
"setting",
"to",
"a",
"monitor",
"workspace"
] | def _execute_dark_run_subtraction_monitors(self, monitor_workspace, setting, workspace_was_event):
'''
Apply one dark run setting to a monitor workspace
@param monitor_workspace: the monitor data set associated with the scatter data
@param setting: a dark run settings tuple
@param workspace_was_event: flag if the original workspace was derived from histo or event
@returns a monitor for the dark run
'''
# Get the dark run name and path for the monitor
dark_run_name, dark_run_file_path = self._get_dark_run_name_and_path(setting)
# Load the dark run workspace is it has not already been loaded
monitor_dark_run_ws = self._load_dark_run_monitors(dark_run_name, dark_run_file_path)
# Check if the original workspace is based on Histo or Event. If it was an event workspace,
# then the monitor workspace of the dark run should match (note that for event workspaces
# the monitor workspace is separate). In the case of histo workspaces the monitor data
# has all the histo data appended.
out_ws = None
if workspace_was_event:
# Rebin to the dark run monitor workspace to the original monitor workspace
monitor_dark_run_ws = self._rebin_to_match(monitor_workspace, monitor_dark_run_ws)
out_ws = self._subtract_dark_run(monitor_workspace, monitor_dark_run_ws, setting)
else:
out_ws = self._get_monitor_workspace_from_original_histo_input(monitor_workspace, monitor_dark_run_ws, setting)
return out_ws | [
"def",
"_execute_dark_run_subtraction_monitors",
"(",
"self",
",",
"monitor_workspace",
",",
"setting",
",",
"workspace_was_event",
")",
":",
"# Get the dark run name and path for the monitor",
"dark_run_name",
",",
"dark_run_file_path",
"=",
"self",
".",
"_get_dark_run_name_and_path",
"(",
"setting",
")",
"# Load the dark run workspace is it has not already been loaded",
"monitor_dark_run_ws",
"=",
"self",
".",
"_load_dark_run_monitors",
"(",
"dark_run_name",
",",
"dark_run_file_path",
")",
"# Check if the original workspace is based on Histo or Event. If it was an event workspace,",
"# then the monitor workspace of the dark run should match (note that for event workspaces",
"# the monitor workspace is separate). In the case of histo workspaces the monitor data",
"# has all the histo data appended.",
"out_ws",
"=",
"None",
"if",
"workspace_was_event",
":",
"# Rebin to the dark run monitor workspace to the original monitor workspace",
"monitor_dark_run_ws",
"=",
"self",
".",
"_rebin_to_match",
"(",
"monitor_workspace",
",",
"monitor_dark_run_ws",
")",
"out_ws",
"=",
"self",
".",
"_subtract_dark_run",
"(",
"monitor_workspace",
",",
"monitor_dark_run_ws",
",",
"setting",
")",
"else",
":",
"out_ws",
"=",
"self",
".",
"_get_monitor_workspace_from_original_histo_input",
"(",
"monitor_workspace",
",",
"monitor_dark_run_ws",
",",
"setting",
")",
"return",
"out_ws"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_reduction_steps.py#L1440-L1465 | |
shoaibrayeen/Programmers-Community | 1d352fb3e6ac5e2e7d9472d90527bdcc8d5ec355 | Basic/Reverse A String/SolutionByTanmay.py | python | rev_string | (strng) | return rev_str | Objective : To Reverse A Given String
Input : A String - Str Object
Return Value : A Reversed String - Str Object | Objective : To Reverse A Given String
Input : A String - Str Object
Return Value : A Reversed String - Str Object | [
"Objective",
":",
"To",
"Reverse",
"A",
"Given",
"String",
"Input",
":",
"A",
"String",
"-",
"Str",
"Object",
"Return",
"Value",
":",
"A",
"Reversed",
"String",
"-",
"Str",
"Object"
] | def rev_string(strng):
'''
Objective : To Reverse A Given String
Input : A String - Str Object
Return Value : A Reversed String - Str Object
'''
rev_str = ''
for i in range(len(strng)-1,-1,-1):
rev_str+=strng[i]
return rev_str | [
"def",
"rev_string",
"(",
"strng",
")",
":",
"rev_str",
"=",
"''",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"strng",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"rev_str",
"+=",
"strng",
"[",
"i",
"]",
"return",
"rev_str"
] | https://github.com/shoaibrayeen/Programmers-Community/blob/1d352fb3e6ac5e2e7d9472d90527bdcc8d5ec355/Basic/Reverse A String/SolutionByTanmay.py#L1-L15 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/memory_inspector/memory_inspector/core/backends.py | python | Device.IsMmapTracingEnabled | (self) | Check if the device is ready to capture memory map traces. | Check if the device is ready to capture memory map traces. | [
"Check",
"if",
"the",
"device",
"is",
"ready",
"to",
"capture",
"memory",
"map",
"traces",
"."
] | def IsMmapTracingEnabled(self):
"""Check if the device is ready to capture memory map traces."""
raise NotImplementedError() | [
"def",
"IsMmapTracingEnabled",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/memory_inspector/memory_inspector/core/backends.py#L83-L85 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AzCodeGenerator/bin/linux/az_code_gen/clang_cpp.py | python | format_cpp_annotations | (json_object) | Does a pass over the entire JSON output from clang and organizes it into:
{
"objects": [
{
"fields": [
{
"annotations": {
"AzProperty": {}
}
}
],
"methods": [],
"annotations": {
"AzClass": {}
"AzComponent": {}
}
}
],
"enums": [
{
"annotations": {
"AzEnum": {}
}
}
]
}
This includes resolving annotations that are attached to special codegen virtual variables
and generally cleaning up the top-level structure and annotation hierarchy of the input JSON
@param json_object The output from the clang AST parse/dump | Does a pass over the entire JSON output from clang and organizes it into:
{
"objects": [
{
"fields": [
{
"annotations": {
"AzProperty": {}
}
}
],
"methods": [],
"annotations": {
"AzClass": {}
"AzComponent": {}
}
}
],
"enums": [
{
"annotations": {
"AzEnum": {}
}
}
]
}
This includes resolving annotations that are attached to special codegen virtual variables
and generally cleaning up the top-level structure and annotation hierarchy of the input JSON | [
"Does",
"a",
"pass",
"over",
"the",
"entire",
"JSON",
"output",
"from",
"clang",
"and",
"organizes",
"it",
"into",
":",
"{",
"objects",
":",
"[",
"{",
"fields",
":",
"[",
"{",
"annotations",
":",
"{",
"AzProperty",
":",
"{}",
"}",
"}",
"]",
"methods",
":",
"[]",
"annotations",
":",
"{",
"AzClass",
":",
"{}",
"AzComponent",
":",
"{}",
"}",
"}",
"]",
"enums",
":",
"[",
"{",
"annotations",
":",
"{",
"AzEnum",
":",
"{}",
"}",
"}",
"]",
"}",
"This",
"includes",
"resolving",
"annotations",
"that",
"are",
"attached",
"to",
"special",
"codegen",
"virtual",
"variables",
"and",
"generally",
"cleaning",
"up",
"the",
"top",
"-",
"level",
"structure",
"and",
"annotation",
"hierarchy",
"of",
"the",
"input",
"JSON"
] | def format_cpp_annotations(json_object):
""" Does a pass over the entire JSON output from clang and organizes it into:
{
"objects": [
{
"fields": [
{
"annotations": {
"AzProperty": {}
}
}
],
"methods": [],
"annotations": {
"AzClass": {}
"AzComponent": {}
}
}
],
"enums": [
{
"annotations": {
"AzEnum": {}
}
}
]
}
This includes resolving annotations that are attached to special codegen virtual variables
and generally cleaning up the top-level structure and annotation hierarchy of the input JSON
@param json_object The output from the clang AST parse/dump
"""
promote_field_tags_to_class(json_object)
format_enums(json_object)
format_globals(json_object)
for object in json_object.get('objects', []):
# convert tokens -> nested dicts
for field in object.get('fields', []):
expand_annotations( field )
for method in object.get('methods', []):
expand_annotations( method )
expand_annotations(object)
for enum in json_object.get('enums', []):
expand_annotations(enum)
coalesce_enum_values(enum) | [
"def",
"format_cpp_annotations",
"(",
"json_object",
")",
":",
"promote_field_tags_to_class",
"(",
"json_object",
")",
"format_enums",
"(",
"json_object",
")",
"format_globals",
"(",
"json_object",
")",
"for",
"object",
"in",
"json_object",
".",
"get",
"(",
"'objects'",
",",
"[",
"]",
")",
":",
"# convert tokens -> nested dicts",
"for",
"field",
"in",
"object",
".",
"get",
"(",
"'fields'",
",",
"[",
"]",
")",
":",
"expand_annotations",
"(",
"field",
")",
"for",
"method",
"in",
"object",
".",
"get",
"(",
"'methods'",
",",
"[",
"]",
")",
":",
"expand_annotations",
"(",
"method",
")",
"expand_annotations",
"(",
"object",
")",
"for",
"enum",
"in",
"json_object",
".",
"get",
"(",
"'enums'",
",",
"[",
"]",
")",
":",
"expand_annotations",
"(",
"enum",
")",
"coalesce_enum_values",
"(",
"enum",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AzCodeGenerator/bin/linux/az_code_gen/clang_cpp.py#L67-L111 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextParagraph.GetContiguousPlainText | (*args, **kwargs) | return _richtext.RichTextParagraph_GetContiguousPlainText(*args, **kwargs) | GetContiguousPlainText(self, String text, RichTextRange range, bool fromStart=True) -> bool | GetContiguousPlainText(self, String text, RichTextRange range, bool fromStart=True) -> bool | [
"GetContiguousPlainText",
"(",
"self",
"String",
"text",
"RichTextRange",
"range",
"bool",
"fromStart",
"=",
"True",
")",
"-",
">",
"bool"
] | def GetContiguousPlainText(*args, **kwargs):
"""GetContiguousPlainText(self, String text, RichTextRange range, bool fromStart=True) -> bool"""
return _richtext.RichTextParagraph_GetContiguousPlainText(*args, **kwargs) | [
"def",
"GetContiguousPlainText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextParagraph_GetContiguousPlainText",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L2015-L2017 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/control_flow_ops.py | python | CondContext.__init__ | (self, pred=None, pivot=None, branch=None,
name="cond_text", context_def=None, import_scope=None) | Creates a `CondContext`.
Args:
pred: The `boolean` tensor for the conditional predicate.
pivot: The predicate tensor in this branch.
branch: 0 or 1 representing this branch.
name: Name of the `CondContext` python object.
context_def: Optional `ContextDef` protocol buffer to initialize the
`CondContext` object from.
import_scope: Optional `string`. Name scope to add. Only used when
initialing from protocol buffer. | Creates a `CondContext`. | [
"Creates",
"a",
"CondContext",
"."
] | def __init__(self, pred=None, pivot=None, branch=None,
name="cond_text", context_def=None, import_scope=None):
"""Creates a `CondContext`.
Args:
pred: The `boolean` tensor for the conditional predicate.
pivot: The predicate tensor in this branch.
branch: 0 or 1 representing this branch.
name: Name of the `CondContext` python object.
context_def: Optional `ContextDef` protocol buffer to initialize the
`CondContext` object from.
import_scope: Optional `string`. Name scope to add. Only used when
initialing from protocol buffer.
"""
self._name = ops.get_default_graph().unique_name(name)
if context_def:
self._init_from_proto(context_def, import_scope=import_scope)
else:
# Initializes the default fields.
ControlFlowContext.__init__(self)
self._pred = pred # The boolean tensor for the cond predicate
self._pivot = pivot # The predicate tensor in this branch
self._branch = branch # 0 or 1 representing this branch
# Values considered to have been already seen in this context.
self._values.add(pred.name)
self._values.add(pivot.name) | [
"def",
"__init__",
"(",
"self",
",",
"pred",
"=",
"None",
",",
"pivot",
"=",
"None",
",",
"branch",
"=",
"None",
",",
"name",
"=",
"\"cond_text\"",
",",
"context_def",
"=",
"None",
",",
"import_scope",
"=",
"None",
")",
":",
"self",
".",
"_name",
"=",
"ops",
".",
"get_default_graph",
"(",
")",
".",
"unique_name",
"(",
"name",
")",
"if",
"context_def",
":",
"self",
".",
"_init_from_proto",
"(",
"context_def",
",",
"import_scope",
"=",
"import_scope",
")",
"else",
":",
"# Initializes the default fields.",
"ControlFlowContext",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"_pred",
"=",
"pred",
"# The boolean tensor for the cond predicate",
"self",
".",
"_pivot",
"=",
"pivot",
"# The predicate tensor in this branch",
"self",
".",
"_branch",
"=",
"branch",
"# 0 or 1 representing this branch",
"# Values considered to have been already seen in this context.",
"self",
".",
"_values",
".",
"add",
"(",
"pred",
".",
"name",
")",
"self",
".",
"_values",
".",
"add",
"(",
"pivot",
".",
"name",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/control_flow_ops.py#L1515-L1542 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/gdb/libpython.py | python | move_in_stack | (move_up) | Move up or down the stack (for the py-up/py-down command) | Move up or down the stack (for the py-up/py-down command) | [
"Move",
"up",
"or",
"down",
"the",
"stack",
"(",
"for",
"the",
"py",
"-",
"up",
"/",
"py",
"-",
"down",
"command",
")"
] | def move_in_stack(move_up):
'''Move up or down the stack (for the py-up/py-down command)'''
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
while frame:
if move_up:
iter_frame = frame.older()
else:
iter_frame = frame.newer()
if not iter_frame:
break
if iter_frame.is_python_frame():
# Result:
if iter_frame.select():
iter_frame.print_summary()
return
frame = iter_frame
if move_up:
print('Unable to find an older python frame')
else:
print('Unable to find a newer python frame') | [
"def",
"move_in_stack",
"(",
"move_up",
")",
":",
"frame",
"=",
"Frame",
".",
"get_selected_python_frame",
"(",
")",
"if",
"not",
"frame",
":",
"print",
"(",
"'Unable to locate python frame'",
")",
"return",
"while",
"frame",
":",
"if",
"move_up",
":",
"iter_frame",
"=",
"frame",
".",
"older",
"(",
")",
"else",
":",
"iter_frame",
"=",
"frame",
".",
"newer",
"(",
")",
"if",
"not",
"iter_frame",
":",
"break",
"if",
"iter_frame",
".",
"is_python_frame",
"(",
")",
":",
"# Result:",
"if",
"iter_frame",
".",
"select",
"(",
")",
":",
"iter_frame",
".",
"print_summary",
"(",
")",
"return",
"frame",
"=",
"iter_frame",
"if",
"move_up",
":",
"print",
"(",
"'Unable to find an older python frame'",
")",
"else",
":",
"print",
"(",
"'Unable to find a newer python frame'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/gdb/libpython.py#L1787-L1814 | ||
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/sets_impl.py | python | _set_operation | (a, b, set_operation, validate_indices=True) | return sparse_tensor.SparseTensor(indices, values, shape) | Compute set operation of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be
sorted in row-major order.
set_operation: String indicating set operation. See
SetOperationOp::SetOperationFromContext for valid values.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the results
of the set operation.
Raises:
TypeError: If inputs are invalid types.
ValueError: If `a` is sparse and `b` is dense. | Compute set operation of elements in last dimension of `a` and `b`. | [
"Compute",
"set",
"operation",
"of",
"elements",
"in",
"last",
"dimension",
"of",
"a",
"and",
"b",
"."
] | def _set_operation(a, b, set_operation, validate_indices=True):
"""Compute set operation of elements in last dimension of `a` and `b`.
All but the last dimension of `a` and `b` must match.
Args:
a: `Tensor` or `SparseTensor` of the same type as `b`. If sparse, indices
must be sorted in row-major order.
b: `Tensor` or `SparseTensor` of the same type as `a`. Must be
`SparseTensor` if `a` is `SparseTensor`. If sparse, indices must be
sorted in row-major order.
set_operation: String indicating set operation. See
SetOperationOp::SetOperationFromContext for valid values.
validate_indices: Whether to validate the order and range of sparse indices
in `a` and `b`.
Returns:
A `SparseTensor` with the same rank as `a` and `b`, and all but the last
dimension the same. Elements along the last dimension contain the results
of the set operation.
Raises:
TypeError: If inputs are invalid types.
ValueError: If `a` is sparse and `b` is dense.
"""
if isinstance(a, sparse_tensor.SparseTensor):
if isinstance(b, sparse_tensor.SparseTensor):
indices, values, shape = gen_set_ops.sparse_to_sparse_set_operation(
a.indices, a.values, a.dense_shape,
b.indices, b.values, b.dense_shape,
set_operation, validate_indices)
else:
raise ValueError("Sparse,Dense is not supported, but Dense,Sparse is. "
"Please flip the order of your inputs.")
elif isinstance(b, sparse_tensor.SparseTensor):
indices, values, shape = gen_set_ops.dense_to_sparse_set_operation(
a, b.indices, b.values, b.dense_shape, set_operation, validate_indices)
else:
indices, values, shape = gen_set_ops.dense_to_dense_set_operation(
a, b, set_operation, validate_indices)
return sparse_tensor.SparseTensor(indices, values, shape) | [
"def",
"_set_operation",
"(",
"a",
",",
"b",
",",
"set_operation",
",",
"validate_indices",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
":",
"if",
"isinstance",
"(",
"b",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
":",
"indices",
",",
"values",
",",
"shape",
"=",
"gen_set_ops",
".",
"sparse_to_sparse_set_operation",
"(",
"a",
".",
"indices",
",",
"a",
".",
"values",
",",
"a",
".",
"dense_shape",
",",
"b",
".",
"indices",
",",
"b",
".",
"values",
",",
"b",
".",
"dense_shape",
",",
"set_operation",
",",
"validate_indices",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Sparse,Dense is not supported, but Dense,Sparse is. \"",
"\"Please flip the order of your inputs.\"",
")",
"elif",
"isinstance",
"(",
"b",
",",
"sparse_tensor",
".",
"SparseTensor",
")",
":",
"indices",
",",
"values",
",",
"shape",
"=",
"gen_set_ops",
".",
"dense_to_sparse_set_operation",
"(",
"a",
",",
"b",
".",
"indices",
",",
"b",
".",
"values",
",",
"b",
".",
"dense_shape",
",",
"set_operation",
",",
"validate_indices",
")",
"else",
":",
"indices",
",",
"values",
",",
"shape",
"=",
"gen_set_ops",
".",
"dense_to_dense_set_operation",
"(",
"a",
",",
"b",
",",
"set_operation",
",",
"validate_indices",
")",
"return",
"sparse_tensor",
".",
"SparseTensor",
"(",
"indices",
",",
"values",
",",
"shape",
")"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/sets_impl.py#L91-L131 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/ops/data_flow_ops.py | python | Barrier.barrier_ref | (self) | return self._barrier_ref | Get the underlying barrier reference. | Get the underlying barrier reference. | [
"Get",
"the",
"underlying",
"barrier",
"reference",
"."
] | def barrier_ref(self):
"""Get the underlying barrier reference."""
return self._barrier_ref | [
"def",
"barrier_ref",
"(",
"self",
")",
":",
"return",
"self",
".",
"_barrier_ref"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/data_flow_ops.py#L902-L904 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_misc.py | python | GetActiveWindow | (*args) | return _misc_.GetActiveWindow(*args) | GetActiveWindow() -> Window
Get the currently active window of this application, or None | GetActiveWindow() -> Window | [
"GetActiveWindow",
"()",
"-",
">",
"Window"
] | def GetActiveWindow(*args):
"""
GetActiveWindow() -> Window
Get the currently active window of this application, or None
"""
return _misc_.GetActiveWindow(*args) | [
"def",
"GetActiveWindow",
"(",
"*",
"args",
")",
":",
"return",
"_misc_",
".",
"GetActiveWindow",
"(",
"*",
"args",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L575-L581 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewVirtualListModel.GetCount | (*args, **kwargs) | return _dataview.DataViewVirtualListModel_GetCount(*args, **kwargs) | GetCount(self) -> unsigned int
returns the number of rows | GetCount(self) -> unsigned int | [
"GetCount",
"(",
"self",
")",
"-",
">",
"unsigned",
"int"
] | def GetCount(*args, **kwargs):
"""
GetCount(self) -> unsigned int
returns the number of rows
"""
return _dataview.DataViewVirtualListModel_GetCount(*args, **kwargs) | [
"def",
"GetCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewVirtualListModel_GetCount",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1064-L1070 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py | python | Calendar.monthdayscalendar | (self, year, month) | return [ days[i:i+7] for i in range(0, len(days), 7) ] | Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero. | Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero. | [
"Return",
"a",
"matrix",
"representing",
"a",
"month",
"s",
"calendar",
".",
"Each",
"row",
"represents",
"a",
"week",
";",
"days",
"outside",
"this",
"month",
"are",
"zero",
"."
] | def monthdayscalendar(self, year, month):
"""
Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero.
"""
days = list(self.itermonthdays(year, month))
return [ days[i:i+7] for i in range(0, len(days), 7) ] | [
"def",
"monthdayscalendar",
"(",
"self",
",",
"year",
",",
"month",
")",
":",
"days",
"=",
"list",
"(",
"self",
".",
"itermonthdays",
"(",
"year",
",",
"month",
")",
")",
"return",
"[",
"days",
"[",
"i",
":",
"i",
"+",
"7",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"days",
")",
",",
"7",
")",
"]"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py#L212-L218 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py | python | embedding_tied_rnn_seq2seq | (encoder_inputs,
decoder_inputs,
cell,
num_symbols,
embedding_size,
num_decoder_symbols=None,
output_projection=None,
feed_previous=False,
dtype=None,
scope=None) | Embedding RNN sequence-to-sequence model with tied (shared) parameters.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_symbols x input_size]). Then it runs an RNN to encode embedded
encoder_inputs into a state vector. Next, it embeds decoder_inputs using
the same embedding. Then it runs RNN decoder, initialized with the last
encoder state, on embedded decoder_inputs. The decoder output is over symbols
from 0 to num_decoder_symbols - 1 if num_decoder_symbols is none; otherwise it
is over 0 to num_symbols - 1.
Args:
encoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
decoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
cell: tf.compat.v1.nn.rnn_cell.RNNCell defining the cell function and size.
num_symbols: Integer; number of symbols for both encoder and decoder.
embedding_size: Integer, the length of the embedding vector for each symbol.
num_decoder_symbols: Integer; number of output symbols for decoder. If
provided, the decoder output is over symbols 0 to num_decoder_symbols - 1.
Otherwise, decoder output is over symbols 0 to num_symbols - 1. Note that
this assumes that the vocabulary is set up such that the first
num_decoder_symbols of num_symbols are part of decoding.
output_projection: None or a pair (W, B) of output projection weights and
biases; W has shape [output_size x num_symbols] and B has shape
[num_symbols]; if provided and feed_previous=True, each fed previous
output will first be multiplied by W and added B.
feed_previous: Boolean or scalar Boolean Tensor; if True, only the first of
decoder_inputs will be used (the "GO" symbol), and all other decoder
inputs will be taken from previous outputs (as in embedding_rnn_decoder).
If False, decoder_inputs are used as given (the standard decoder case).
dtype: The dtype to use for the initial RNN states (default: tf.float32).
scope: VariableScope for the created subgraph; defaults to
"embedding_tied_rnn_seq2seq".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_symbols] containing the generated
outputs where output_symbols = num_decoder_symbols if
num_decoder_symbols is not None otherwise output_symbols = num_symbols.
state: The state of each decoder cell at the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
Raises:
ValueError: When output_projection has the wrong shape. | Embedding RNN sequence-to-sequence model with tied (shared) parameters. | [
"Embedding",
"RNN",
"sequence",
"-",
"to",
"-",
"sequence",
"model",
"with",
"tied",
"(",
"shared",
")",
"parameters",
"."
] | def embedding_tied_rnn_seq2seq(encoder_inputs,
decoder_inputs,
cell,
num_symbols,
embedding_size,
num_decoder_symbols=None,
output_projection=None,
feed_previous=False,
dtype=None,
scope=None):
"""Embedding RNN sequence-to-sequence model with tied (shared) parameters.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_symbols x input_size]). Then it runs an RNN to encode embedded
encoder_inputs into a state vector. Next, it embeds decoder_inputs using
the same embedding. Then it runs RNN decoder, initialized with the last
encoder state, on embedded decoder_inputs. The decoder output is over symbols
from 0 to num_decoder_symbols - 1 if num_decoder_symbols is none; otherwise it
is over 0 to num_symbols - 1.
Args:
encoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
decoder_inputs: A list of 1D int32 Tensors of shape [batch_size].
cell: tf.compat.v1.nn.rnn_cell.RNNCell defining the cell function and size.
num_symbols: Integer; number of symbols for both encoder and decoder.
embedding_size: Integer, the length of the embedding vector for each symbol.
num_decoder_symbols: Integer; number of output symbols for decoder. If
provided, the decoder output is over symbols 0 to num_decoder_symbols - 1.
Otherwise, decoder output is over symbols 0 to num_symbols - 1. Note that
this assumes that the vocabulary is set up such that the first
num_decoder_symbols of num_symbols are part of decoding.
output_projection: None or a pair (W, B) of output projection weights and
biases; W has shape [output_size x num_symbols] and B has shape
[num_symbols]; if provided and feed_previous=True, each fed previous
output will first be multiplied by W and added B.
feed_previous: Boolean or scalar Boolean Tensor; if True, only the first of
decoder_inputs will be used (the "GO" symbol), and all other decoder
inputs will be taken from previous outputs (as in embedding_rnn_decoder).
If False, decoder_inputs are used as given (the standard decoder case).
dtype: The dtype to use for the initial RNN states (default: tf.float32).
scope: VariableScope for the created subgraph; defaults to
"embedding_tied_rnn_seq2seq".
Returns:
A tuple of the form (outputs, state), where:
outputs: A list of the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_symbols] containing the generated
outputs where output_symbols = num_decoder_symbols if
num_decoder_symbols is not None otherwise output_symbols = num_symbols.
state: The state of each decoder cell at the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
Raises:
ValueError: When output_projection has the wrong shape.
"""
with variable_scope.variable_scope(
scope or "embedding_tied_rnn_seq2seq", dtype=dtype) as scope:
dtype = scope.dtype
if output_projection is not None:
proj_weights = ops.convert_to_tensor(output_projection[0], dtype=dtype)
proj_weights.get_shape().assert_is_compatible_with([None, num_symbols])
proj_biases = ops.convert_to_tensor(output_projection[1], dtype=dtype)
proj_biases.get_shape().assert_is_compatible_with([num_symbols])
embedding = variable_scope.get_variable(
"embedding", [num_symbols, embedding_size], dtype=dtype)
emb_encoder_inputs = [
embedding_ops.embedding_lookup(embedding, x) for x in encoder_inputs
]
emb_decoder_inputs = [
embedding_ops.embedding_lookup(embedding, x) for x in decoder_inputs
]
output_symbols = num_symbols
if num_decoder_symbols is not None:
output_symbols = num_decoder_symbols
if output_projection is None:
cell = core_rnn_cell.OutputProjectionWrapper(cell, output_symbols)
if isinstance(feed_previous, bool):
loop_function = _extract_argmax_and_embed(embedding, output_projection,
True) if feed_previous else None
return tied_rnn_seq2seq(
emb_encoder_inputs,
emb_decoder_inputs,
cell,
loop_function=loop_function,
dtype=dtype)
# If feed_previous is a Tensor, we construct 2 graphs and use cond.
def decoder(feed_previous_bool):
loop_function = _extract_argmax_and_embed(
embedding, output_projection, False) if feed_previous_bool else None
reuse = None if feed_previous_bool else True
with variable_scope.variable_scope(
variable_scope.get_variable_scope(), reuse=reuse):
outputs, state = tied_rnn_seq2seq(
emb_encoder_inputs,
emb_decoder_inputs,
cell,
loop_function=loop_function,
dtype=dtype)
state_list = [state]
if nest.is_sequence(state):
state_list = nest.flatten(state)
return outputs + state_list
outputs_and_state = control_flow_ops.cond(
feed_previous, lambda: decoder(True), lambda: decoder(False))
outputs_len = len(decoder_inputs) # Outputs length same as decoder inputs.
state_list = outputs_and_state[outputs_len:]
state = state_list[0]
# Calculate zero-state to know it's structure.
static_batch_size = encoder_inputs[0].get_shape()[0]
for inp in encoder_inputs[1:]:
static_batch_size.merge_with(inp.get_shape()[0])
batch_size = static_batch_size.value
if batch_size is None:
batch_size = array_ops.shape(encoder_inputs[0])[0]
zero_state = cell.zero_state(batch_size, dtype)
if nest.is_sequence(zero_state):
state = nest.pack_sequence_as(
structure=zero_state, flat_sequence=state_list)
return outputs_and_state[:outputs_len], state | [
"def",
"embedding_tied_rnn_seq2seq",
"(",
"encoder_inputs",
",",
"decoder_inputs",
",",
"cell",
",",
"num_symbols",
",",
"embedding_size",
",",
"num_decoder_symbols",
"=",
"None",
",",
"output_projection",
"=",
"None",
",",
"feed_previous",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
"scope",
"=",
"None",
")",
":",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"scope",
"or",
"\"embedding_tied_rnn_seq2seq\"",
",",
"dtype",
"=",
"dtype",
")",
"as",
"scope",
":",
"dtype",
"=",
"scope",
".",
"dtype",
"if",
"output_projection",
"is",
"not",
"None",
":",
"proj_weights",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"output_projection",
"[",
"0",
"]",
",",
"dtype",
"=",
"dtype",
")",
"proj_weights",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"[",
"None",
",",
"num_symbols",
"]",
")",
"proj_biases",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"output_projection",
"[",
"1",
"]",
",",
"dtype",
"=",
"dtype",
")",
"proj_biases",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"[",
"num_symbols",
"]",
")",
"embedding",
"=",
"variable_scope",
".",
"get_variable",
"(",
"\"embedding\"",
",",
"[",
"num_symbols",
",",
"embedding_size",
"]",
",",
"dtype",
"=",
"dtype",
")",
"emb_encoder_inputs",
"=",
"[",
"embedding_ops",
".",
"embedding_lookup",
"(",
"embedding",
",",
"x",
")",
"for",
"x",
"in",
"encoder_inputs",
"]",
"emb_decoder_inputs",
"=",
"[",
"embedding_ops",
".",
"embedding_lookup",
"(",
"embedding",
",",
"x",
")",
"for",
"x",
"in",
"decoder_inputs",
"]",
"output_symbols",
"=",
"num_symbols",
"if",
"num_decoder_symbols",
"is",
"not",
"None",
":",
"output_symbols",
"=",
"num_decoder_symbols",
"if",
"output_projection",
"is",
"None",
":",
"cell",
"=",
"core_rnn_cell",
".",
"OutputProjectionWrapper",
"(",
"cell",
",",
"output_symbols",
")",
"if",
"isinstance",
"(",
"feed_previous",
",",
"bool",
")",
":",
"loop_function",
"=",
"_extract_argmax_and_embed",
"(",
"embedding",
",",
"output_projection",
",",
"True",
")",
"if",
"feed_previous",
"else",
"None",
"return",
"tied_rnn_seq2seq",
"(",
"emb_encoder_inputs",
",",
"emb_decoder_inputs",
",",
"cell",
",",
"loop_function",
"=",
"loop_function",
",",
"dtype",
"=",
"dtype",
")",
"# If feed_previous is a Tensor, we construct 2 graphs and use cond.",
"def",
"decoder",
"(",
"feed_previous_bool",
")",
":",
"loop_function",
"=",
"_extract_argmax_and_embed",
"(",
"embedding",
",",
"output_projection",
",",
"False",
")",
"if",
"feed_previous_bool",
"else",
"None",
"reuse",
"=",
"None",
"if",
"feed_previous_bool",
"else",
"True",
"with",
"variable_scope",
".",
"variable_scope",
"(",
"variable_scope",
".",
"get_variable_scope",
"(",
")",
",",
"reuse",
"=",
"reuse",
")",
":",
"outputs",
",",
"state",
"=",
"tied_rnn_seq2seq",
"(",
"emb_encoder_inputs",
",",
"emb_decoder_inputs",
",",
"cell",
",",
"loop_function",
"=",
"loop_function",
",",
"dtype",
"=",
"dtype",
")",
"state_list",
"=",
"[",
"state",
"]",
"if",
"nest",
".",
"is_sequence",
"(",
"state",
")",
":",
"state_list",
"=",
"nest",
".",
"flatten",
"(",
"state",
")",
"return",
"outputs",
"+",
"state_list",
"outputs_and_state",
"=",
"control_flow_ops",
".",
"cond",
"(",
"feed_previous",
",",
"lambda",
":",
"decoder",
"(",
"True",
")",
",",
"lambda",
":",
"decoder",
"(",
"False",
")",
")",
"outputs_len",
"=",
"len",
"(",
"decoder_inputs",
")",
"# Outputs length same as decoder inputs.",
"state_list",
"=",
"outputs_and_state",
"[",
"outputs_len",
":",
"]",
"state",
"=",
"state_list",
"[",
"0",
"]",
"# Calculate zero-state to know it's structure.",
"static_batch_size",
"=",
"encoder_inputs",
"[",
"0",
"]",
".",
"get_shape",
"(",
")",
"[",
"0",
"]",
"for",
"inp",
"in",
"encoder_inputs",
"[",
"1",
":",
"]",
":",
"static_batch_size",
".",
"merge_with",
"(",
"inp",
".",
"get_shape",
"(",
")",
"[",
"0",
"]",
")",
"batch_size",
"=",
"static_batch_size",
".",
"value",
"if",
"batch_size",
"is",
"None",
":",
"batch_size",
"=",
"array_ops",
".",
"shape",
"(",
"encoder_inputs",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"zero_state",
"=",
"cell",
".",
"zero_state",
"(",
"batch_size",
",",
"dtype",
")",
"if",
"nest",
".",
"is_sequence",
"(",
"zero_state",
")",
":",
"state",
"=",
"nest",
".",
"pack_sequence_as",
"(",
"structure",
"=",
"zero_state",
",",
"flat_sequence",
"=",
"state_list",
")",
"return",
"outputs_and_state",
"[",
":",
"outputs_len",
"]",
",",
"state"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py#L409-L534 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/logging/handlers.py | python | SMTPHandler.date_time | (self) | return s | Return the current date and time formatted for a MIME header.
Needed for Python 1.5.2 (no email package available) | Return the current date and time formatted for a MIME header.
Needed for Python 1.5.2 (no email package available) | [
"Return",
"the",
"current",
"date",
"and",
"time",
"formatted",
"for",
"a",
"MIME",
"header",
".",
"Needed",
"for",
"Python",
"1",
".",
"5",
".",
"2",
"(",
"no",
"email",
"package",
"available",
")"
] | def date_time(self):
"""
Return the current date and time formatted for a MIME header.
Needed for Python 1.5.2 (no email package available)
"""
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time())
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
self.weekdayname[wd],
day, self.monthname[month], year,
hh, mm, ss)
return s | [
"def",
"date_time",
"(",
"self",
")",
":",
"year",
",",
"month",
",",
"day",
",",
"hh",
",",
"mm",
",",
"ss",
",",
"wd",
",",
"y",
",",
"z",
"=",
"time",
".",
"gmtime",
"(",
"time",
".",
"time",
"(",
")",
")",
"s",
"=",
"\"%s, %02d %3s %4d %02d:%02d:%02d GMT\"",
"%",
"(",
"self",
".",
"weekdayname",
"[",
"wd",
"]",
",",
"day",
",",
"self",
".",
"monthname",
"[",
"month",
"]",
",",
"year",
",",
"hh",
",",
"mm",
",",
"ss",
")",
"return",
"s"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/handlers.py#L838-L848 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/ma/mrecords.py | python | MaskedRecords.view | (self, dtype=None, type=None) | return output | Returns a view of the mrecarray. | Returns a view of the mrecarray. | [
"Returns",
"a",
"view",
"of",
"the",
"mrecarray",
"."
] | def view(self, dtype=None, type=None):
"""Returns a view of the mrecarray."""
# OK, basic copy-paste from MaskedArray.view...
if dtype is None:
if type is None:
output = ndarray.view(self)
else:
output = ndarray.view(self, type)
# Here again...
elif type is None:
try:
if issubclass(dtype, ndarray):
output = ndarray.view(self, dtype)
dtype = None
else:
output = ndarray.view(self, dtype)
# OK, there's the change
except TypeError:
dtype = np.dtype(dtype)
# we need to revert to MaskedArray, but keeping the possibility
# ...of subclasses (eg, TimeSeriesRecords), so we'll force a type
# ...set to the first parent
if dtype.fields is None:
basetype = self.__class__.__bases__[0]
output = self.__array__().view(dtype, basetype)
output._update_from(self)
else:
output = ndarray.view(self, dtype)
output._fill_value = None
else:
output = ndarray.view(self, dtype, type)
# Update the mask, just like in MaskedArray.view
if (getattr(output, '_mask', nomask) is not nomask):
mdtype = ma.make_mask_descr(output.dtype)
output._mask = self._mask.view(mdtype, ndarray)
output._mask.shape = output.shape
return output | [
"def",
"view",
"(",
"self",
",",
"dtype",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"# OK, basic copy-paste from MaskedArray.view...",
"if",
"dtype",
"is",
"None",
":",
"if",
"type",
"is",
"None",
":",
"output",
"=",
"ndarray",
".",
"view",
"(",
"self",
")",
"else",
":",
"output",
"=",
"ndarray",
".",
"view",
"(",
"self",
",",
"type",
")",
"# Here again...",
"elif",
"type",
"is",
"None",
":",
"try",
":",
"if",
"issubclass",
"(",
"dtype",
",",
"ndarray",
")",
":",
"output",
"=",
"ndarray",
".",
"view",
"(",
"self",
",",
"dtype",
")",
"dtype",
"=",
"None",
"else",
":",
"output",
"=",
"ndarray",
".",
"view",
"(",
"self",
",",
"dtype",
")",
"# OK, there's the change",
"except",
"TypeError",
":",
"dtype",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
"# we need to revert to MaskedArray, but keeping the possibility",
"# ...of subclasses (eg, TimeSeriesRecords), so we'll force a type",
"# ...set to the first parent",
"if",
"dtype",
".",
"fields",
"is",
"None",
":",
"basetype",
"=",
"self",
".",
"__class__",
".",
"__bases__",
"[",
"0",
"]",
"output",
"=",
"self",
".",
"__array__",
"(",
")",
".",
"view",
"(",
"dtype",
",",
"basetype",
")",
"output",
".",
"_update_from",
"(",
"self",
")",
"else",
":",
"output",
"=",
"ndarray",
".",
"view",
"(",
"self",
",",
"dtype",
")",
"output",
".",
"_fill_value",
"=",
"None",
"else",
":",
"output",
"=",
"ndarray",
".",
"view",
"(",
"self",
",",
"dtype",
",",
"type",
")",
"# Update the mask, just like in MaskedArray.view",
"if",
"(",
"getattr",
"(",
"output",
",",
"'_mask'",
",",
"nomask",
")",
"is",
"not",
"nomask",
")",
":",
"mdtype",
"=",
"ma",
".",
"make_mask_descr",
"(",
"output",
".",
"dtype",
")",
"output",
".",
"_mask",
"=",
"self",
".",
"_mask",
".",
"view",
"(",
"mdtype",
",",
"ndarray",
")",
"output",
".",
"_mask",
".",
"shape",
"=",
"output",
".",
"shape",
"return",
"output"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/mrecords.py#L345-L381 | |
google-coral/edgetpu | 5020de9386ff370dcc1f63291a2d0f98eeb98adb | edgetpu/utils/dataset_utils.py | python | read_label_file | (file_path) | return ret | Reads labels from text file and store it in a dict.
This function supports following formats:
1. Each line contains id and description separated by colon or space.
Example: '0:cat' or '0 cat'.
2. Each line contains description only. Label's id equals to row number.
Args:
file_path: String, path to the label file.
Returns:
Dict of (int, string) which maps label id to description. | Reads labels from text file and store it in a dict. | [
"Reads",
"labels",
"from",
"text",
"file",
"and",
"store",
"it",
"in",
"a",
"dict",
"."
] | def read_label_file(file_path):
"""Reads labels from text file and store it in a dict.
This function supports following formats:
1. Each line contains id and description separated by colon or space.
Example: '0:cat' or '0 cat'.
2. Each line contains description only. Label's id equals to row number.
Args:
file_path: String, path to the label file.
Returns:
Dict of (int, string) which maps label id to description.
"""
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
ret = {}
for row_number, content in enumerate(lines):
pair = re.split(r'[:\s]+', content.strip(), maxsplit=1)
if len(pair) == 2 and pair[0].strip().isdigit():
ret[int(pair[0])] = pair[1].strip()
else:
ret[row_number] = pair[0].strip()
return ret | [
"def",
"read_label_file",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"ret",
"=",
"{",
"}",
"for",
"row_number",
",",
"content",
"in",
"enumerate",
"(",
"lines",
")",
":",
"pair",
"=",
"re",
".",
"split",
"(",
"r'[:\\s]+'",
",",
"content",
".",
"strip",
"(",
")",
",",
"maxsplit",
"=",
"1",
")",
"if",
"len",
"(",
"pair",
")",
"==",
"2",
"and",
"pair",
"[",
"0",
"]",
".",
"strip",
"(",
")",
".",
"isdigit",
"(",
")",
":",
"ret",
"[",
"int",
"(",
"pair",
"[",
"0",
"]",
")",
"]",
"=",
"pair",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"else",
":",
"ret",
"[",
"row_number",
"]",
"=",
"pair",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"return",
"ret"
] | https://github.com/google-coral/edgetpu/blob/5020de9386ff370dcc1f63291a2d0f98eeb98adb/edgetpu/utils/dataset_utils.py#L19-L43 | |
cmu-db/noisepage | 79276e68fe83322f1249e8a8be96bd63c583ae56 | build-support/cpplint.py | python | CheckIncludeLine | (filename, clean_lines, linenum, include_state, error) | Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Check rules that are applicable to #include lines. | [
"Check",
"rules",
"that",
"are",
"applicable",
"to",
"#include",
"lines",
"."
] | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
# Only do this check if the included header follows google naming
# conventions. If not, assume that it's a 3rd party API that
# requires special include conventions.
#
# We also make an exception for Lua headers, which follow google
# naming convention but not the include convention.
match = Match(r'#include\s*"([^/]+\.h)"', line)
if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
error(filename, linenum, 'build/include_subdir', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
duplicate_line = include_state.FindHeader(include)
if duplicate_line >= 0:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, duplicate_line))
return
for extension in GetNonHeaderExtensions():
if (include.endswith('.' + extension) and
os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
error(filename, linenum, 'build/include', 4,
'Do not include .' + extension + ' files from other packages')
return
# We DO want to include a 3rd party looking header if it matches the
# filename. Otherwise we get an erroneous error "...should include its
# header" error later.
third_src_header = False
for ext in GetHeaderExtensions():
basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
headerfile = basefilename + '.' + ext
headername = FileInfo(headerfile).RepositoryName()
if headername in include or include in headername:
third_src_header = True
break
if third_src_header or not _THIRD_PARTY_HEADERS_PATTERN.match(include):
include_state.include_list[-1].append((include, linenum))
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include) | [
"def",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"",
"# Only do this check if the included header follows google naming",
"# conventions. If not, assume that it's a 3rd party API that",
"# requires special include conventions.",
"#",
"# We also make an exception for Lua headers, which follow google",
"# naming convention but not the include convention.",
"match",
"=",
"Match",
"(",
"r'#include\\s*\"([^/]+\\.h)\"'",
",",
"line",
")",
"if",
"match",
"and",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_subdir'",
",",
"4",
",",
"'Include the directory when naming .h files'",
")",
"# we shouldn't include a file more than once. actually, there are a",
"# handful of instances where doing so is okay, but in general it's",
"# not.",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"include",
"=",
"match",
".",
"group",
"(",
"2",
")",
"is_system",
"=",
"(",
"match",
".",
"group",
"(",
"1",
")",
"==",
"'<'",
")",
"duplicate_line",
"=",
"include_state",
".",
"FindHeader",
"(",
"include",
")",
"if",
"duplicate_line",
">=",
"0",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'\"%s\" already included at %s:%s'",
"%",
"(",
"include",
",",
"filename",
",",
"duplicate_line",
")",
")",
"return",
"for",
"extension",
"in",
"GetNonHeaderExtensions",
"(",
")",
":",
"if",
"(",
"include",
".",
"endswith",
"(",
"'.'",
"+",
"extension",
")",
"and",
"os",
".",
"path",
".",
"dirname",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
")",
"!=",
"os",
".",
"path",
".",
"dirname",
"(",
"include",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'Do not include .'",
"+",
"extension",
"+",
"' files from other packages'",
")",
"return",
"# We DO want to include a 3rd party looking header if it matches the",
"# filename. Otherwise we get an erroneous error \"...should include its",
"# header\" error later.",
"third_src_header",
"=",
"False",
"for",
"ext",
"in",
"GetHeaderExtensions",
"(",
")",
":",
"basefilename",
"=",
"filename",
"[",
"0",
":",
"len",
"(",
"filename",
")",
"-",
"len",
"(",
"fileinfo",
".",
"Extension",
"(",
")",
")",
"]",
"headerfile",
"=",
"basefilename",
"+",
"'.'",
"+",
"ext",
"headername",
"=",
"FileInfo",
"(",
"headerfile",
")",
".",
"RepositoryName",
"(",
")",
"if",
"headername",
"in",
"include",
"or",
"include",
"in",
"headername",
":",
"third_src_header",
"=",
"True",
"break",
"if",
"third_src_header",
"or",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"include",
")",
":",
"include_state",
".",
"include_list",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"(",
"include",
",",
"linenum",
")",
")",
"# We want to ensure that headers appear in the right order:",
"# 1) for foo.cc, foo.h (preferred location)",
"# 2) c system files",
"# 3) cpp system files",
"# 4) for foo.cc, foo.h (deprecated location)",
"# 5) other google headers",
"#",
"# We classify each include statement as one of those 5 types",
"# using a number of techniques. The include_state object keeps",
"# track of the highest type seen, and complains if we see a",
"# lower type after that.",
"error_message",
"=",
"include_state",
".",
"CheckNextIncludeOrder",
"(",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
")",
"if",
"error_message",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_order'",
",",
"4",
",",
"'%s. Should be: %s.h, c system, c++ system, other.'",
"%",
"(",
"error_message",
",",
"fileinfo",
".",
"BaseName",
"(",
")",
")",
")",
"canonical_include",
"=",
"include_state",
".",
"CanonicalizeAlphabeticalOrder",
"(",
"include",
")",
"if",
"not",
"include_state",
".",
"IsInAlphabeticalOrder",
"(",
"clean_lines",
",",
"linenum",
",",
"canonical_include",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_alpha'",
",",
"4",
",",
"'Include \"%s\" not in alphabetical order'",
"%",
"include",
")",
"include_state",
".",
"SetLastHeader",
"(",
"canonical_include",
")"
] | https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/build-support/cpplint.py#L4777-L4864 | ||
toggl-open-source/toggldesktop | 91865205885531cc8fd9e8d613dad49d625d56e7 | third_party/cpplint/cpplint.py | python | FilesBelongToSameModule | (filename_cc, filename_h) | return files_belong_to_same_module, common_path | Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file. | Check if these two filenames belong to the same module. | [
"Check",
"if",
"these",
"two",
"filenames",
"belong",
"to",
"the",
"same",
"module",
"."
] | def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file.
"""
if not filename_cc.endswith('.cc'):
return (False, '')
filename_cc = filename_cc[:-len('.cc')]
if filename_cc.endswith('_unittest'):
filename_cc = filename_cc[:-len('_unittest')]
elif filename_cc.endswith('_test'):
filename_cc = filename_cc[:-len('_test')]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
if not filename_h.endswith('.h'):
return (False, '')
filename_h = filename_h[:-len('.h')]
if filename_h.endswith('-inl'):
filename_h = filename_h[:-len('-inl')]
filename_h = filename_h.replace('/public/', '/')
filename_h = filename_h.replace('/internal/', '/')
files_belong_to_same_module = filename_cc.endswith(filename_h)
common_path = ''
if files_belong_to_same_module:
common_path = filename_cc[:-len(filename_h)]
return files_belong_to_same_module, common_path | [
"def",
"FilesBelongToSameModule",
"(",
"filename_cc",
",",
"filename_h",
")",
":",
"if",
"not",
"filename_cc",
".",
"endswith",
"(",
"'.cc'",
")",
":",
"return",
"(",
"False",
",",
"''",
")",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'.cc'",
")",
"]",
"if",
"filename_cc",
".",
"endswith",
"(",
"'_unittest'",
")",
":",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'_unittest'",
")",
"]",
"elif",
"filename_cc",
".",
"endswith",
"(",
"'_test'",
")",
":",
"filename_cc",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"'_test'",
")",
"]",
"filename_cc",
"=",
"filename_cc",
".",
"replace",
"(",
"'/public/'",
",",
"'/'",
")",
"filename_cc",
"=",
"filename_cc",
".",
"replace",
"(",
"'/internal/'",
",",
"'/'",
")",
"if",
"not",
"filename_h",
".",
"endswith",
"(",
"'.h'",
")",
":",
"return",
"(",
"False",
",",
"''",
")",
"filename_h",
"=",
"filename_h",
"[",
":",
"-",
"len",
"(",
"'.h'",
")",
"]",
"if",
"filename_h",
".",
"endswith",
"(",
"'-inl'",
")",
":",
"filename_h",
"=",
"filename_h",
"[",
":",
"-",
"len",
"(",
"'-inl'",
")",
"]",
"filename_h",
"=",
"filename_h",
".",
"replace",
"(",
"'/public/'",
",",
"'/'",
")",
"filename_h",
"=",
"filename_h",
".",
"replace",
"(",
"'/internal/'",
",",
"'/'",
")",
"files_belong_to_same_module",
"=",
"filename_cc",
".",
"endswith",
"(",
"filename_h",
")",
"common_path",
"=",
"''",
"if",
"files_belong_to_same_module",
":",
"common_path",
"=",
"filename_cc",
"[",
":",
"-",
"len",
"(",
"filename_h",
")",
"]",
"return",
"files_belong_to_same_module",
",",
"common_path"
] | https://github.com/toggl-open-source/toggldesktop/blob/91865205885531cc8fd9e8d613dad49d625d56e7/third_party/cpplint/cpplint.py#L5522-L5574 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/idlelib/autocomplete_w.py | python | AutoCompleteWindow._selection_changed | (self) | Call when the selection of the Listbox has changed.
Updates the Listbox display and calls _change_start. | Call when the selection of the Listbox has changed. | [
"Call",
"when",
"the",
"selection",
"of",
"the",
"Listbox",
"has",
"changed",
"."
] | def _selection_changed(self):
"""Call when the selection of the Listbox has changed.
Updates the Listbox display and calls _change_start.
"""
cursel = int(self.listbox.curselection()[0])
self.listbox.see(cursel)
lts = self.lasttypedstart
selstart = self.completions[cursel]
if self._binary_search(lts) == cursel:
newstart = lts
else:
min_len = min(len(lts), len(selstart))
i = 0
while i < min_len and lts[i] == selstart[i]:
i += 1
newstart = selstart[:i]
self._change_start(newstart)
if self.completions[cursel][:len(self.start)] == self.start:
# start is a prefix of the selected completion
self.listbox.configure(selectbackground=self.origselbackground,
selectforeground=self.origselforeground)
else:
self.listbox.configure(selectbackground=self.listbox.cget("bg"),
selectforeground=self.listbox.cget("fg"))
# If there are more completions, show them, and call me again.
if self.morecompletions:
self.completions = self.morecompletions
self.morecompletions = None
self.listbox.delete(0, END)
for item in self.completions:
self.listbox.insert(END, item)
self.listbox.select_set(self._binary_search(self.start))
self._selection_changed() | [
"def",
"_selection_changed",
"(",
"self",
")",
":",
"cursel",
"=",
"int",
"(",
"self",
".",
"listbox",
".",
"curselection",
"(",
")",
"[",
"0",
"]",
")",
"self",
".",
"listbox",
".",
"see",
"(",
"cursel",
")",
"lts",
"=",
"self",
".",
"lasttypedstart",
"selstart",
"=",
"self",
".",
"completions",
"[",
"cursel",
"]",
"if",
"self",
".",
"_binary_search",
"(",
"lts",
")",
"==",
"cursel",
":",
"newstart",
"=",
"lts",
"else",
":",
"min_len",
"=",
"min",
"(",
"len",
"(",
"lts",
")",
",",
"len",
"(",
"selstart",
")",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"min_len",
"and",
"lts",
"[",
"i",
"]",
"==",
"selstart",
"[",
"i",
"]",
":",
"i",
"+=",
"1",
"newstart",
"=",
"selstart",
"[",
":",
"i",
"]",
"self",
".",
"_change_start",
"(",
"newstart",
")",
"if",
"self",
".",
"completions",
"[",
"cursel",
"]",
"[",
":",
"len",
"(",
"self",
".",
"start",
")",
"]",
"==",
"self",
".",
"start",
":",
"# start is a prefix of the selected completion",
"self",
".",
"listbox",
".",
"configure",
"(",
"selectbackground",
"=",
"self",
".",
"origselbackground",
",",
"selectforeground",
"=",
"self",
".",
"origselforeground",
")",
"else",
":",
"self",
".",
"listbox",
".",
"configure",
"(",
"selectbackground",
"=",
"self",
".",
"listbox",
".",
"cget",
"(",
"\"bg\"",
")",
",",
"selectforeground",
"=",
"self",
".",
"listbox",
".",
"cget",
"(",
"\"fg\"",
")",
")",
"# If there are more completions, show them, and call me again.",
"if",
"self",
".",
"morecompletions",
":",
"self",
".",
"completions",
"=",
"self",
".",
"morecompletions",
"self",
".",
"morecompletions",
"=",
"None",
"self",
".",
"listbox",
".",
"delete",
"(",
"0",
",",
"END",
")",
"for",
"item",
"in",
"self",
".",
"completions",
":",
"self",
".",
"listbox",
".",
"insert",
"(",
"END",
",",
"item",
")",
"self",
".",
"listbox",
".",
"select_set",
"(",
"self",
".",
"_binary_search",
"(",
"self",
".",
"start",
")",
")",
"self",
".",
"_selection_changed",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/autocomplete_w.py#L120-L156 | ||
rodeofx/OpenWalter | 6116fbe3f04f1146c854afbfbdbe944feaee647e | walter/maya/scripts/AEwalterOverrideTemplate.py | python | AEwalterOverrideTemplate.renameAttr | (self, node, old, new, nameLayout, attrLayout, buttonLayout) | Rename the given attribute to the name given in the "new" argument.
Update the UI layout. | Rename the given attribute to the name given in the "new" argument.
Update the UI layout. | [
"Rename",
"the",
"given",
"attribute",
"to",
"the",
"name",
"given",
"in",
"the",
"new",
"argument",
".",
"Update",
"the",
"UI",
"layout",
"."
] | def renameAttr(self, node, old, new, nameLayout, attrLayout, buttonLayout):
"""
Rename the given attribute to the name given in the "new" argument.
Update the UI layout.
"""
# Rename Maya attribute
plug = '.'.join([node, old])
cmds.renameAttr(plug, new)
# Update the layout
cmds.textField(
nameLayout,
edit=True,
changeCommand=
lambda
text,
n=node,
a=new,
nl=nameLayout,
al=attrLayout,
bl=buttonLayout:
self.renameAttr(n, a, PREFIX + '_' + text, nl, al, bl))
# Update the button.
cmds.button(
buttonLayout,
edit=True,
command=lambda c, a=new: self.deleteAttr(a))
# Update the field.
plug = '.'.join([node, new])
control = self.getControllerGroup(plug)
control(attrLayout, edit=True, attribute=plug) | [
"def",
"renameAttr",
"(",
"self",
",",
"node",
",",
"old",
",",
"new",
",",
"nameLayout",
",",
"attrLayout",
",",
"buttonLayout",
")",
":",
"# Rename Maya attribute",
"plug",
"=",
"'.'",
".",
"join",
"(",
"[",
"node",
",",
"old",
"]",
")",
"cmds",
".",
"renameAttr",
"(",
"plug",
",",
"new",
")",
"# Update the layout",
"cmds",
".",
"textField",
"(",
"nameLayout",
",",
"edit",
"=",
"True",
",",
"changeCommand",
"=",
"lambda",
"text",
",",
"n",
"=",
"node",
",",
"a",
"=",
"new",
",",
"nl",
"=",
"nameLayout",
",",
"al",
"=",
"attrLayout",
",",
"bl",
"=",
"buttonLayout",
":",
"self",
".",
"renameAttr",
"(",
"n",
",",
"a",
",",
"PREFIX",
"+",
"'_'",
"+",
"text",
",",
"nl",
",",
"al",
",",
"bl",
")",
")",
"# Update the button.",
"cmds",
".",
"button",
"(",
"buttonLayout",
",",
"edit",
"=",
"True",
",",
"command",
"=",
"lambda",
"c",
",",
"a",
"=",
"new",
":",
"self",
".",
"deleteAttr",
"(",
"a",
")",
")",
"# Update the field.",
"plug",
"=",
"'.'",
".",
"join",
"(",
"[",
"node",
",",
"new",
"]",
")",
"control",
"=",
"self",
".",
"getControllerGroup",
"(",
"plug",
")",
"control",
"(",
"attrLayout",
",",
"edit",
"=",
"True",
",",
"attribute",
"=",
"plug",
")"
] | https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/maya/scripts/AEwalterOverrideTemplate.py#L615-L647 | ||
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | ortools/sat/python/cp_model.py | python | CpModel.AddBoolXOr | (self, literals) | return ct | Adds `XOr(literals) == true`.
In contrast to AddBoolOr and AddBoolAnd, it does not support
.OnlyEnforceIf().
Args:
literals: the list of literals in the constraint.
Returns:
An `Constraint` object. | Adds `XOr(literals) == true`. | [
"Adds",
"XOr",
"(",
"literals",
")",
"==",
"true",
"."
] | def AddBoolXOr(self, literals):
"""Adds `XOr(literals) == true`.
In contrast to AddBoolOr and AddBoolAnd, it does not support
.OnlyEnforceIf().
Args:
literals: the list of literals in the constraint.
Returns:
An `Constraint` object.
"""
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
model_ct.bool_xor.literals.extend(
[self.GetOrMakeBooleanIndex(x) for x in literals])
return ct | [
"def",
"AddBoolXOr",
"(",
"self",
",",
"literals",
")",
":",
"ct",
"=",
"Constraint",
"(",
"self",
".",
"__model",
".",
"constraints",
")",
"model_ct",
"=",
"self",
".",
"__model",
".",
"constraints",
"[",
"ct",
".",
"Index",
"(",
")",
"]",
"model_ct",
".",
"bool_xor",
".",
"literals",
".",
"extend",
"(",
"[",
"self",
".",
"GetOrMakeBooleanIndex",
"(",
"x",
")",
"for",
"x",
"in",
"literals",
"]",
")",
"return",
"ct"
] | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/python/cp_model.py#L1477-L1493 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/ros_comm/rospy/src/rospy/impl/registration.py | python | RegistrationListener.reg_added | (self, resolved_name, data_type_or_uri, reg_type) | New pub/sub/service declared.
@param resolved_name: resolved topic/service name
@param data_type_or_uri: topic type or service uri
@type data_type_or_uri: str
@param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV}
@type reg_type: str | New pub/sub/service declared. | [
"New",
"pub",
"/",
"sub",
"/",
"service",
"declared",
"."
] | def reg_added(self, resolved_name, data_type_or_uri, reg_type):
"""
New pub/sub/service declared.
@param resolved_name: resolved topic/service name
@param data_type_or_uri: topic type or service uri
@type data_type_or_uri: str
@param reg_type: Valid values are L{Registration.PUB}, L{Registration.SUB}, L{Registration.SRV}
@type reg_type: str
"""
pass | [
"def",
"reg_added",
"(",
"self",
",",
"resolved_name",
",",
"data_type_or_uri",
",",
"reg_type",
")",
":",
"pass"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/registration.py#L100-L109 | ||
flexflow/FlexFlow | 581fad8ba8d10a16a3102ee2b406b0319586df24 | python/flexflow/keras/datasets/mnist.py | python | load_data | (path='mnist.npz') | return (x_train, y_train), (x_test, y_test) | Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. | Loads the MNIST dataset. | [
"Loads",
"the",
"MNIST",
"dataset",
"."
] | def load_data(path='mnist.npz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path,
origin='https://s3.amazonaws.com/img-datasets/mnist.npz',
file_hash='8a61469f7ea1b51cbae51d4f78837e45')
with np.load(path, allow_pickle=True) as f:
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
return (x_train, y_train), (x_test, y_test) | [
"def",
"load_data",
"(",
"path",
"=",
"'mnist.npz'",
")",
":",
"path",
"=",
"get_file",
"(",
"path",
",",
"origin",
"=",
"'https://s3.amazonaws.com/img-datasets/mnist.npz'",
",",
"file_hash",
"=",
"'8a61469f7ea1b51cbae51d4f78837e45'",
")",
"with",
"np",
".",
"load",
"(",
"path",
",",
"allow_pickle",
"=",
"True",
")",
"as",
"f",
":",
"x_train",
",",
"y_train",
"=",
"f",
"[",
"'x_train'",
"]",
",",
"f",
"[",
"'y_train'",
"]",
"x_test",
",",
"y_test",
"=",
"f",
"[",
"'x_test'",
"]",
",",
"f",
"[",
"'y_test'",
"]",
"return",
"(",
"x_train",
",",
"y_train",
")",
",",
"(",
"x_test",
",",
"y_test",
")"
] | https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/python/flexflow/keras/datasets/mnist.py#L11-L27 | |
google/or-tools | 2cb85b4eead4c38e1c54b48044f92087cf165bce | examples/python/transit_time.py | python | Vehicle.speed | (self) | return self._speed | Gets the average travel speed of a vehicle | Gets the average travel speed of a vehicle | [
"Gets",
"the",
"average",
"travel",
"speed",
"of",
"a",
"vehicle"
] | def speed(self):
"""Gets the average travel speed of a vehicle"""
return self._speed | [
"def",
"speed",
"(",
"self",
")",
":",
"return",
"self",
".",
"_speed"
] | https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/examples/python/transit_time.py#L41-L43 | |
intel-iot-devkit/how-to-code-samples | b4ea616f36bbfa2e042beb1698f968cfd651d79f | watering-system/python/iot_watering_system/log.py | python | increment | () | Publish timestamp to MQTT server and data store. | Publish timestamp to MQTT server and data store. | [
"Publish",
"timestamp",
"to",
"MQTT",
"server",
"and",
"data",
"store",
"."
] | def increment():
"""
Publish timestamp to MQTT server and data store.
"""
payload = {"counter": datetime.utcnow().isoformat()}
send(payload) | [
"def",
"increment",
"(",
")",
":",
"payload",
"=",
"{",
"\"counter\"",
":",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"}",
"send",
"(",
"payload",
")"
] | https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/watering-system/python/iot_watering_system/log.py#L36-L43 | ||
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | utils/cpplint.py | python | _IsTestFilename | (filename) | Determines if the given filename has a suffix that identifies it as a test.
Args:
filename: The input filename.
Returns:
True if 'filename' looks like a test, False otherwise. | Determines if the given filename has a suffix that identifies it as a test. | [
"Determines",
"if",
"the",
"given",
"filename",
"has",
"a",
"suffix",
"that",
"identifies",
"it",
"as",
"a",
"test",
"."
] | def _IsTestFilename(filename):
"""Determines if the given filename has a suffix that identifies it as a test.
Args:
filename: The input filename.
Returns:
True if 'filename' looks like a test, False otherwise.
"""
if (filename.endswith('_test.cc') or
filename.endswith('_unittest.cc') or
filename.endswith('_regtest.cc')):
return True
else:
return False | [
"def",
"_IsTestFilename",
"(",
"filename",
")",
":",
"if",
"(",
"filename",
".",
"endswith",
"(",
"'_test.cc'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'_unittest.cc'",
")",
"or",
"filename",
".",
"endswith",
"(",
"'_regtest.cc'",
")",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/utils/cpplint.py#L4532-L4546 | ||
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/pexpect/pexpect.py | python | spawn.readlines | (self, sizehint=-1) | return lines | This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored. | This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored. | [
"This",
"reads",
"until",
"EOF",
"using",
"readline",
"()",
"and",
"returns",
"a",
"list",
"containing",
"the",
"lines",
"thus",
"read",
".",
"The",
"optional",
"sizehint",
"argument",
"is",
"ignored",
"."
] | def readlines(self, sizehint=-1):
"""This reads until EOF using readline() and returns a list containing
the lines thus read. The optional 'sizehint' argument is ignored. """
lines = []
while True:
line = self.readline()
if not line:
break
lines.append(line)
return lines | [
"def",
"readlines",
"(",
"self",
",",
"sizehint",
"=",
"-",
"1",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"lines",
".",
"append",
"(",
"line",
")",
"return",
"lines"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pexpect/pexpect.py#L963-L974 | |
mongodb/mongo | d8ff665343ad29cf286ee2cf4a1960d29371937b | buildscripts/benchmarks/analyze.py | python | get_baseline_task_id | (evg_api_config: str, current_task_id: str) | return "" | Get the most recent successful task prior to the current task. | Get the most recent successful task prior to the current task. | [
"Get",
"the",
"most",
"recent",
"successful",
"task",
"prior",
"to",
"the",
"current",
"task",
"."
] | def get_baseline_task_id(evg_api_config: str, current_task_id: str) -> str:
"""Get the most recent successful task prior to the current task."""
evg_api = RetryingEvergreenApi.get_api(config_file=evg_api_config)
current_task = evg_api.task_by_id(current_task_id)
base_version = evg_api.version_by_id(
f"{current_task.json['project_identifier'].replace('-', '_')}_{current_task.revision}")
prior_versions = evg_api.versions_by_project(current_task.project_id, start=base_version.order)
for version in prior_versions:
baseline_task_candidate = None
build = version.build_by_variant(current_task.build_variant)
for task in build.get_tasks():
if task.display_name == current_task.display_name:
baseline_task_candidate = task
break
# If previous build doesn't contain the task with the same 'display_name'
# assume that this is a new task and there is no baseline task
if baseline_task_candidate is None:
return ""
if baseline_task_candidate.is_success():
return baseline_task_candidate.task_id
return "" | [
"def",
"get_baseline_task_id",
"(",
"evg_api_config",
":",
"str",
",",
"current_task_id",
":",
"str",
")",
"->",
"str",
":",
"evg_api",
"=",
"RetryingEvergreenApi",
".",
"get_api",
"(",
"config_file",
"=",
"evg_api_config",
")",
"current_task",
"=",
"evg_api",
".",
"task_by_id",
"(",
"current_task_id",
")",
"base_version",
"=",
"evg_api",
".",
"version_by_id",
"(",
"f\"{current_task.json['project_identifier'].replace('-', '_')}_{current_task.revision}\"",
")",
"prior_versions",
"=",
"evg_api",
".",
"versions_by_project",
"(",
"current_task",
".",
"project_id",
",",
"start",
"=",
"base_version",
".",
"order",
")",
"for",
"version",
"in",
"prior_versions",
":",
"baseline_task_candidate",
"=",
"None",
"build",
"=",
"version",
".",
"build_by_variant",
"(",
"current_task",
".",
"build_variant",
")",
"for",
"task",
"in",
"build",
".",
"get_tasks",
"(",
")",
":",
"if",
"task",
".",
"display_name",
"==",
"current_task",
".",
"display_name",
":",
"baseline_task_candidate",
"=",
"task",
"break",
"# If previous build doesn't contain the task with the same 'display_name'",
"# assume that this is a new task and there is no baseline task",
"if",
"baseline_task_candidate",
"is",
"None",
":",
"return",
"\"\"",
"if",
"baseline_task_candidate",
".",
"is_success",
"(",
")",
":",
"return",
"baseline_task_candidate",
".",
"task_id",
"return",
"\"\""
] | https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/benchmarks/analyze.py#L18-L41 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/abins/input/casteploader.py | python | CASTEPLoader._parse_phonon_eigenvectors | (self, f_handle) | return np.asarray(vectors) | :param f_handle: file object to read
:returns: eigenvectors (atomic displacements) for all k-points | [] | def _parse_phonon_eigenvectors(self, f_handle):
"""
:param f_handle: file object to read
:returns: eigenvectors (atomic displacements) for all k-points
"""
dim = 3 # we have 3D space
# in general case eigenvectors are complex
vectors = np.zeros((self._num_atoms, self._num_phonons, dim), dtype=COMPLEX_TYPE)
for freq in range(self._num_phonons):
for atom in range(self._num_atoms):
line = f_handle.readline()
if not line:
raise IOError("Could not parse file. Invalid file format.")
line_data = line.split()
vector_components = line_data[2:]
# we have dimension 3, eigenvectors are complex, 3 * 2 = 6 number of all fields to parse
for n in range(dim):
vectors[atom, freq, n] = complex(float(vector_components[2 * n]),
float(vector_components[2 * n + 1]))
return np.asarray(vectors) | [
"def",
"_parse_phonon_eigenvectors",
"(",
"self",
",",
"f_handle",
")",
":",
"dim",
"=",
"3",
"# we have 3D space",
"# in general case eigenvectors are complex",
"vectors",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"_num_atoms",
",",
"self",
".",
"_num_phonons",
",",
"dim",
")",
",",
"dtype",
"=",
"COMPLEX_TYPE",
")",
"for",
"freq",
"in",
"range",
"(",
"self",
".",
"_num_phonons",
")",
":",
"for",
"atom",
"in",
"range",
"(",
"self",
".",
"_num_atoms",
")",
":",
"line",
"=",
"f_handle",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"raise",
"IOError",
"(",
"\"Could not parse file. Invalid file format.\"",
")",
"line_data",
"=",
"line",
".",
"split",
"(",
")",
"vector_components",
"=",
"line_data",
"[",
"2",
":",
"]",
"# we have dimension 3, eigenvectors are complex, 3 * 2 = 6 number of all fields to parse",
"for",
"n",
"in",
"range",
"(",
"dim",
")",
":",
"vectors",
"[",
"atom",
",",
"freq",
",",
"n",
"]",
"=",
"complex",
"(",
"float",
"(",
"vector_components",
"[",
"2",
"*",
"n",
"]",
")",
",",
"float",
"(",
"vector_components",
"[",
"2",
"*",
"n",
"+",
"1",
"]",
")",
")",
"return",
"np",
".",
"asarray",
"(",
"vectors",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/input/casteploader.py#L144-L169 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | Window.SetEventHandler | (*args, **kwargs) | return _core_.Window_SetEventHandler(*args, **kwargs) | SetEventHandler(self, EvtHandler handler)
Sets the event handler for this window. An event handler is an object
that is capable of processing the events sent to a window. (In other
words, is able to dispatch the events to handler function.) By
default, the window is its own event handler, but an application may
wish to substitute another, for example to allow central
implementation of event-handling for a variety of different window
classes.
It is usually better to use `wx.Window.PushEventHandler` since this sets
up a chain of event handlers, where an event not handled by one event
handler is handed off to the next one in the chain. | SetEventHandler(self, EvtHandler handler) | [
"SetEventHandler",
"(",
"self",
"EvtHandler",
"handler",
")"
] | def SetEventHandler(*args, **kwargs):
"""
SetEventHandler(self, EvtHandler handler)
Sets the event handler for this window. An event handler is an object
that is capable of processing the events sent to a window. (In other
words, is able to dispatch the events to handler function.) By
default, the window is its own event handler, but an application may
wish to substitute another, for example to allow central
implementation of event-handling for a variety of different window
classes.
It is usually better to use `wx.Window.PushEventHandler` since this sets
up a chain of event handlers, where an event not handled by one event
handler is handed off to the next one in the chain.
"""
return _core_.Window_SetEventHandler(*args, **kwargs) | [
"def",
"SetEventHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Window_SetEventHandler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L10364-L10380 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/base.py | python | RegressorMixin.score | (self, X, y, sample_weight=None) | return r2_score(y, y_pred, sample_weight=sample_weight,
multioutput='variance_weighted') | Return the coefficient of determination R^2 of the prediction.
The coefficient R^2 is defined as (1 - u/v), where u is the residual
sum of squares ((y_true - y_pred) ** 2).sum() and v is the total
sum of squares ((y_true - y_true.mean()) ** 2).sum().
The best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always
predicts the expected value of y, disregarding the input features,
would get a R^2 score of 0.0.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a
precomputed kernel matrix or a list of generic objects instead,
shape = (n_samples, n_samples_fitted),
where n_samples_fitted is the number of
samples used in the fitting for the estimator.
y : array-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights.
Returns
-------
score : float
R^2 of self.predict(X) wrt. y.
Notes
-----
The R2 score used when calling ``score`` on a regressor will use
``multioutput='uniform_average'`` from version 0.23 to keep consistent
with :func:`~sklearn.metrics.r2_score`. This will influence the
``score`` method of all the multioutput regressors (except for
:class:`~sklearn.multioutput.MultiOutputRegressor`). To specify the
default value manually and avoid the warning, please either call
:func:`~sklearn.metrics.r2_score` directly or make a custom scorer with
:func:`~sklearn.metrics.make_scorer` (the built-in scorer ``'r2'`` uses
``multioutput='uniform_average'``). | Return the coefficient of determination R^2 of the prediction. | [
"Return",
"the",
"coefficient",
"of",
"determination",
"R^2",
"of",
"the",
"prediction",
"."
] | def score(self, X, y, sample_weight=None):
"""Return the coefficient of determination R^2 of the prediction.
The coefficient R^2 is defined as (1 - u/v), where u is the residual
sum of squares ((y_true - y_pred) ** 2).sum() and v is the total
sum of squares ((y_true - y_true.mean()) ** 2).sum().
The best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always
predicts the expected value of y, disregarding the input features,
would get a R^2 score of 0.0.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a
precomputed kernel matrix or a list of generic objects instead,
shape = (n_samples, n_samples_fitted),
where n_samples_fitted is the number of
samples used in the fitting for the estimator.
y : array-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights.
Returns
-------
score : float
R^2 of self.predict(X) wrt. y.
Notes
-----
The R2 score used when calling ``score`` on a regressor will use
``multioutput='uniform_average'`` from version 0.23 to keep consistent
with :func:`~sklearn.metrics.r2_score`. This will influence the
``score`` method of all the multioutput regressors (except for
:class:`~sklearn.multioutput.MultiOutputRegressor`). To specify the
default value manually and avoid the warning, please either call
:func:`~sklearn.metrics.r2_score` directly or make a custom scorer with
:func:`~sklearn.metrics.make_scorer` (the built-in scorer ``'r2'`` uses
``multioutput='uniform_average'``).
"""
from .metrics import r2_score
from .metrics._regression import _check_reg_targets
y_pred = self.predict(X)
# XXX: Remove the check in 0.23
y_type, _, _, _ = _check_reg_targets(y, y_pred, None)
if y_type == 'continuous-multioutput':
warnings.warn("The default value of multioutput (not exposed in "
"score method) will change from 'variance_weighted' "
"to 'uniform_average' in 0.23 to keep consistent "
"with 'metrics.r2_score'. To specify the default "
"value manually and avoid the warning, please "
"either call 'metrics.r2_score' directly or make a "
"custom scorer with 'metrics.make_scorer' (the "
"built-in scorer 'r2' uses "
"multioutput='uniform_average').", FutureWarning)
return r2_score(y, y_pred, sample_weight=sample_weight,
multioutput='variance_weighted') | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
")",
":",
"from",
".",
"metrics",
"import",
"r2_score",
"from",
".",
"metrics",
".",
"_regression",
"import",
"_check_reg_targets",
"y_pred",
"=",
"self",
".",
"predict",
"(",
"X",
")",
"# XXX: Remove the check in 0.23",
"y_type",
",",
"_",
",",
"_",
",",
"_",
"=",
"_check_reg_targets",
"(",
"y",
",",
"y_pred",
",",
"None",
")",
"if",
"y_type",
"==",
"'continuous-multioutput'",
":",
"warnings",
".",
"warn",
"(",
"\"The default value of multioutput (not exposed in \"",
"\"score method) will change from 'variance_weighted' \"",
"\"to 'uniform_average' in 0.23 to keep consistent \"",
"\"with 'metrics.r2_score'. To specify the default \"",
"\"value manually and avoid the warning, please \"",
"\"either call 'metrics.r2_score' directly or make a \"",
"\"custom scorer with 'metrics.make_scorer' (the \"",
"\"built-in scorer 'r2' uses \"",
"\"multioutput='uniform_average').\"",
",",
"FutureWarning",
")",
"return",
"r2_score",
"(",
"y",
",",
"y_pred",
",",
"sample_weight",
"=",
"sample_weight",
",",
"multioutput",
"=",
"'variance_weighted'",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/base.py#L376-L436 | |
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/nn/layer/container.py | python | SequentialCell.__init__ | (self, *args) | Initialize SequentialCell. | Initialize SequentialCell. | [
"Initialize",
"SequentialCell",
"."
] | def __init__(self, *args):
"""Initialize SequentialCell."""
super(SequentialCell, self).__init__()
self._is_dynamic_name = []
if len(args) == 1:
cells = args[0]
if isinstance(cells, list):
for index, cell in enumerate(cells):
self.insert_child_to_cell(str(index), cell)
cell.update_parameters_name(str(index) + ".")
self._is_dynamic_name.append(True)
elif isinstance(cells, OrderedDict):
for name, cell in cells.items():
self.insert_child_to_cell(name, cell)
cell.update_parameters_name(name + ".")
self._is_dynamic_name.append(False)
else:
raise TypeError(f"For '{self.__class__.__name__}', the 'args[0]' must be list or orderedDict, "
f"but got {type(cells).__name__}")
else:
for index, cell in enumerate(args):
self.insert_child_to_cell(str(index), cell)
cell.update_parameters_name(str(index) + ".")
self._is_dynamic_name.append(True)
self.cell_list = list(self._cells.values()) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"super",
"(",
"SequentialCell",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_is_dynamic_name",
"=",
"[",
"]",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"cells",
"=",
"args",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"cells",
",",
"list",
")",
":",
"for",
"index",
",",
"cell",
"in",
"enumerate",
"(",
"cells",
")",
":",
"self",
".",
"insert_child_to_cell",
"(",
"str",
"(",
"index",
")",
",",
"cell",
")",
"cell",
".",
"update_parameters_name",
"(",
"str",
"(",
"index",
")",
"+",
"\".\"",
")",
"self",
".",
"_is_dynamic_name",
".",
"append",
"(",
"True",
")",
"elif",
"isinstance",
"(",
"cells",
",",
"OrderedDict",
")",
":",
"for",
"name",
",",
"cell",
"in",
"cells",
".",
"items",
"(",
")",
":",
"self",
".",
"insert_child_to_cell",
"(",
"name",
",",
"cell",
")",
"cell",
".",
"update_parameters_name",
"(",
"name",
"+",
"\".\"",
")",
"self",
".",
"_is_dynamic_name",
".",
"append",
"(",
"False",
")",
"else",
":",
"raise",
"TypeError",
"(",
"f\"For '{self.__class__.__name__}', the 'args[0]' must be list or orderedDict, \"",
"f\"but got {type(cells).__name__}\"",
")",
"else",
":",
"for",
"index",
",",
"cell",
"in",
"enumerate",
"(",
"args",
")",
":",
"self",
".",
"insert_child_to_cell",
"(",
"str",
"(",
"index",
")",
",",
"cell",
")",
"cell",
".",
"update_parameters_name",
"(",
"str",
"(",
"index",
")",
"+",
"\".\"",
")",
"self",
".",
"_is_dynamic_name",
".",
"append",
"(",
"True",
")",
"self",
".",
"cell_list",
"=",
"list",
"(",
"self",
".",
"_cells",
".",
"values",
"(",
")",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/layer/container.py#L140-L164 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/rospack.py | python | ManifestManager.get_manifest | (self, name) | :raises: :exc:`InvalidManifest` | :raises: :exc:`InvalidManifest` | [
":",
"raises",
":",
":",
"exc",
":",
"InvalidManifest"
] | def get_manifest(self, name):
"""
:raises: :exc:`InvalidManifest`
"""
if name in self._manifests:
return self._manifests[name]
else:
return self._load_manifest(name) | [
"def",
"get_manifest",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_manifests",
":",
"return",
"self",
".",
"_manifests",
"[",
"name",
"]",
"else",
":",
"return",
"self",
".",
"_load_manifest",
"(",
"name",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/rospack.py#L157-L164 | ||
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | CustomHandler.WriteImmediateServiceUnitTest | (self, func, f, *extras) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteImmediateServiceUnitTest(self, func, f, *extras):
"""Overrriden from TypeHandler."""
pass | [
"def",
"WriteImmediateServiceUnitTest",
"(",
"self",
",",
"func",
",",
"f",
",",
"*",
"extras",
")",
":",
"pass"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L5702-L5704 | ||
mapnik/mapnik | f3da900c355e1d15059c4a91b00203dcc9d9f0ef | scons/scons-local-4.1.0/SCons/Util.py | python | make_path_relative | (path) | return path | makes an absolute path name to a relative pathname. | makes an absolute path name to a relative pathname. | [
"makes",
"an",
"absolute",
"path",
"name",
"to",
"a",
"relative",
"pathname",
"."
] | def make_path_relative(path):
""" makes an absolute path name to a relative pathname.
"""
if os.path.isabs(path):
drive_s,path = os.path.splitdrive(path)
import re
if not drive_s:
path=re.compile("/*(.*)").findall(path)[0]
else:
path=path[1:]
assert( not os.path.isabs( path ) ), path
return path | [
"def",
"make_path_relative",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"drive_s",
",",
"path",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"import",
"re",
"if",
"not",
"drive_s",
":",
"path",
"=",
"re",
".",
"compile",
"(",
"\"/*(.*)\"",
")",
".",
"findall",
"(",
"path",
")",
"[",
"0",
"]",
"else",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"assert",
"(",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
")",
",",
"path",
"return",
"path"
] | https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Util.py#L1393-L1406 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/distutils/ccompiler.py | python | get_default_compiler | (osname=None, platform=None) | return 'unix' | Determine the default compiler to use for the given platform.
osname should be one of the standard Python OS names (i.e. the
ones returned by os.name) and platform the common value
returned by sys.platform for the platform in question.
The default values are os.name and sys.platform in case the
parameters are not given. | Determine the default compiler to use for the given platform. | [
"Determine",
"the",
"default",
"compiler",
"to",
"use",
"for",
"the",
"given",
"platform",
"."
] | def get_default_compiler(osname=None, platform=None):
""" Determine the default compiler to use for the given platform.
osname should be one of the standard Python OS names (i.e. the
ones returned by os.name) and platform the common value
returned by sys.platform for the platform in question.
The default values are os.name and sys.platform in case the
parameters are not given.
"""
if osname is None:
osname = os.name
if platform is None:
platform = sys.platform
for pattern, compiler in _default_compilers:
if re.match(pattern, platform) is not None or \
re.match(pattern, osname) is not None:
return compiler
# Default to Unix compiler
return 'unix' | [
"def",
"get_default_compiler",
"(",
"osname",
"=",
"None",
",",
"platform",
"=",
"None",
")",
":",
"if",
"osname",
"is",
"None",
":",
"osname",
"=",
"os",
".",
"name",
"if",
"platform",
"is",
"None",
":",
"platform",
"=",
"sys",
".",
"platform",
"for",
"pattern",
",",
"compiler",
"in",
"_default_compilers",
":",
"if",
"re",
".",
"match",
"(",
"pattern",
",",
"platform",
")",
"is",
"not",
"None",
"or",
"re",
".",
"match",
"(",
"pattern",
",",
"osname",
")",
"is",
"not",
"None",
":",
"return",
"compiler",
"# Default to Unix compiler",
"return",
"'unix'"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/ccompiler.py#L913-L933 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/mixins.py | python | _numeric_methods | (ufunc, name) | return (_binary_method(ufunc, name),
_reflected_binary_method(ufunc, name),
_inplace_binary_method(ufunc, name)) | Implement forward, reflected and inplace binary methods with a ufunc. | Implement forward, reflected and inplace binary methods with a ufunc. | [
"Implement",
"forward",
"reflected",
"and",
"inplace",
"binary",
"methods",
"with",
"a",
"ufunc",
"."
] | def _numeric_methods(ufunc, name):
"""Implement forward, reflected and inplace binary methods with a ufunc."""
return (_binary_method(ufunc, name),
_reflected_binary_method(ufunc, name),
_inplace_binary_method(ufunc, name)) | [
"def",
"_numeric_methods",
"(",
"ufunc",
",",
"name",
")",
":",
"return",
"(",
"_binary_method",
"(",
"ufunc",
",",
"name",
")",
",",
"_reflected_binary_method",
"(",
"ufunc",
",",
"name",
")",
",",
"_inplace_binary_method",
"(",
"ufunc",
",",
"name",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/lib/mixins.py#L48-L52 | |
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/win/Source/bin/jinja2/filters.py | python | do_urlize | (environment, value, trim_url_limit=None, nofollow=False) | return rv | Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow" | Converts URLs in plain text into clickable links. | [
"Converts",
"URLs",
"in",
"plain",
"text",
"into",
"clickable",
"links",
"."
] | def do_urlize(environment, value, trim_url_limit=None, nofollow=False):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
"""
rv = urlize(value, trim_url_limit, nofollow)
if environment.autoescape:
rv = Markup(rv)
return rv | [
"def",
"do_urlize",
"(",
"environment",
",",
"value",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
")",
":",
"rv",
"=",
"urlize",
"(",
"value",
",",
"trim_url_limit",
",",
"nofollow",
")",
"if",
"environment",
".",
"autoescape",
":",
"rv",
"=",
"Markup",
"(",
"rv",
")",
"return",
"rv"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/win/Source/bin/jinja2/filters.py#L313-L328 | |
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Diffraction/isis_powder/abstract_inst.py | python | AbstractInst._apply_absorb_corrections | (self, run_details, ws_to_correct) | Generates absorption corrections to compensate for the container. The overriding instrument
should handle the difference between a vanadium workspace and regular workspace
:param ws_to_correct: A reference vanadium workspace to match the binning of or correct
:return: A workspace containing the corrections | Generates absorption corrections to compensate for the container. The overriding instrument
should handle the difference between a vanadium workspace and regular workspace
:param ws_to_correct: A reference vanadium workspace to match the binning of or correct
:return: A workspace containing the corrections | [
"Generates",
"absorption",
"corrections",
"to",
"compensate",
"for",
"the",
"container",
".",
"The",
"overriding",
"instrument",
"should",
"handle",
"the",
"difference",
"between",
"a",
"vanadium",
"workspace",
"and",
"regular",
"workspace",
":",
"param",
"ws_to_correct",
":",
"A",
"reference",
"vanadium",
"workspace",
"to",
"match",
"the",
"binning",
"of",
"or",
"correct",
":",
"return",
":",
"A",
"workspace",
"containing",
"the",
"corrections"
] | def _apply_absorb_corrections(self, run_details, ws_to_correct):
"""
Generates absorption corrections to compensate for the container. The overriding instrument
should handle the difference between a vanadium workspace and regular workspace
:param ws_to_correct: A reference vanadium workspace to match the binning of or correct
:return: A workspace containing the corrections
"""
raise NotImplementedError(
"apply_absorb_corrections Not implemented for this instrument yet") | [
"def",
"_apply_absorb_corrections",
"(",
"self",
",",
"run_details",
",",
"ws_to_correct",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"apply_absorb_corrections Not implemented for this instrument yet\"",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Diffraction/isis_powder/abstract_inst.py#L134-L142 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/function_base.py | python | linspace | (start, stop, num=50, endpoint=True, retstep=False, dtype=None,
axis=0) | Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].
The endpoint of the interval can optionally be excluded.
.. versionchanged:: 1.16.0
Non-scalar `start` and `stop` are now supported.
Parameters
----------
start : array_like
The starting value of the sequence.
stop : array_like
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
.. versionadded:: 1.9.0
axis : int, optional
The axis in the result to store the samples. Relevant only if start
or stop are array-like. By default (0), the samples will be along a
new axis inserted at the beginning. Use -1 to get an axis at the end.
.. versionadded:: 1.16.0
Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float, optional
Only returned if `retstep` is True
Size of spacing between samples.
See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
number of samples).
geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
scale (a geometric progression).
logspace : Similar to `geomspace`, but with the end points specified as
logarithms.
Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show() | Return evenly spaced numbers over a specified interval. | [
"Return",
"evenly",
"spaced",
"numbers",
"over",
"a",
"specified",
"interval",
"."
] | def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
axis=0):
"""
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].
The endpoint of the interval can optionally be excluded.
.. versionchanged:: 1.16.0
Non-scalar `start` and `stop` are now supported.
Parameters
----------
start : array_like
The starting value of the sequence.
stop : array_like
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
.. versionadded:: 1.9.0
axis : int, optional
The axis in the result to store the samples. Relevant only if start
or stop are array-like. By default (0), the samples will be along a
new axis inserted at the beginning. Use -1 to get an axis at the end.
.. versionadded:: 1.16.0
Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float, optional
Only returned if `retstep` is True
Size of spacing between samples.
See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
number of samples).
geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
scale (a geometric progression).
logspace : Similar to `geomspace`, but with the end points specified as
logarithms.
Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
"""
try:
num = operator.index(num)
except TypeError:
raise TypeError(
"object of type {} cannot be safely interpreted as an integer."
.format(type(num)))
if num < 0:
raise ValueError("Number of samples, %s, must be non-negative." % num)
div = (num - 1) if endpoint else num
# Convert float/complex array scalars to float, gh-3504
# and make sure one can use variables that have an __array_interface__, gh-6634
start = asanyarray(start) * 1.0
stop = asanyarray(stop) * 1.0
dt = result_type(start, stop, float(num))
if dtype is None:
dtype = dt
delta = stop - start
y = _nx.arange(0, num, dtype=dt).reshape((-1,) + (1,) * ndim(delta))
# In-place multiplication y *= delta/div is faster, but prevents the multiplicant
# from overriding what class is produced, and thus prevents, e.g. use of Quantities,
# see gh-7142. Hence, we multiply in place only for standard scalar types.
_mult_inplace = _nx.isscalar(delta)
if div > 0:
step = delta / div
if _nx.any(step == 0):
# Special handling for denormal numbers, gh-5437
y /= div
if _mult_inplace:
y *= delta
else:
y = y * delta
else:
if _mult_inplace:
y *= step
else:
y = y * step
else:
# sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
# have an undefined step
step = NaN
# Multiply with delta to allow possible override of output class.
y = y * delta
y += start
if endpoint and num > 1:
y[-1] = stop
if axis != 0:
y = _nx.moveaxis(y, 0, axis)
if retstep:
return y.astype(dtype, copy=False), step
else:
return y.astype(dtype, copy=False) | [
"def",
"linspace",
"(",
"start",
",",
"stop",
",",
"num",
"=",
"50",
",",
"endpoint",
"=",
"True",
",",
"retstep",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
"axis",
"=",
"0",
")",
":",
"try",
":",
"num",
"=",
"operator",
".",
"index",
"(",
"num",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"object of type {} cannot be safely interpreted as an integer.\"",
".",
"format",
"(",
"type",
"(",
"num",
")",
")",
")",
"if",
"num",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Number of samples, %s, must be non-negative.\"",
"%",
"num",
")",
"div",
"=",
"(",
"num",
"-",
"1",
")",
"if",
"endpoint",
"else",
"num",
"# Convert float/complex array scalars to float, gh-3504",
"# and make sure one can use variables that have an __array_interface__, gh-6634",
"start",
"=",
"asanyarray",
"(",
"start",
")",
"*",
"1.0",
"stop",
"=",
"asanyarray",
"(",
"stop",
")",
"*",
"1.0",
"dt",
"=",
"result_type",
"(",
"start",
",",
"stop",
",",
"float",
"(",
"num",
")",
")",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"dt",
"delta",
"=",
"stop",
"-",
"start",
"y",
"=",
"_nx",
".",
"arange",
"(",
"0",
",",
"num",
",",
"dtype",
"=",
"dt",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
")",
"+",
"(",
"1",
",",
")",
"*",
"ndim",
"(",
"delta",
")",
")",
"# In-place multiplication y *= delta/div is faster, but prevents the multiplicant",
"# from overriding what class is produced, and thus prevents, e.g. use of Quantities,",
"# see gh-7142. Hence, we multiply in place only for standard scalar types.",
"_mult_inplace",
"=",
"_nx",
".",
"isscalar",
"(",
"delta",
")",
"if",
"div",
">",
"0",
":",
"step",
"=",
"delta",
"/",
"div",
"if",
"_nx",
".",
"any",
"(",
"step",
"==",
"0",
")",
":",
"# Special handling for denormal numbers, gh-5437",
"y",
"/=",
"div",
"if",
"_mult_inplace",
":",
"y",
"*=",
"delta",
"else",
":",
"y",
"=",
"y",
"*",
"delta",
"else",
":",
"if",
"_mult_inplace",
":",
"y",
"*=",
"step",
"else",
":",
"y",
"=",
"y",
"*",
"step",
"else",
":",
"# sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)",
"# have an undefined step",
"step",
"=",
"NaN",
"# Multiply with delta to allow possible override of output class.",
"y",
"=",
"y",
"*",
"delta",
"y",
"+=",
"start",
"if",
"endpoint",
"and",
"num",
">",
"1",
":",
"y",
"[",
"-",
"1",
"]",
"=",
"stop",
"if",
"axis",
"!=",
"0",
":",
"y",
"=",
"_nx",
".",
"moveaxis",
"(",
"y",
",",
"0",
",",
"axis",
")",
"if",
"retstep",
":",
"return",
"y",
".",
"astype",
"(",
"dtype",
",",
"copy",
"=",
"False",
")",
",",
"step",
"else",
":",
"return",
"y",
".",
"astype",
"(",
"dtype",
",",
"copy",
"=",
"False",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/core/function_base.py#L27-L174 | ||
zhuli19901106/leetcode-zhuli | 0f8fc29ccb8c33ea91149ecb2d4e961024c11db7 | algorithms/0501-1000/0702_search-in-a-sorted-array-of-unknown-size_1_AC.py | python | Solution.search | (self, reader, target) | return -1 | :type reader: ArrayReader
:type target: int
:rtype: int | :type reader: ArrayReader
:type target: int
:rtype: int | [
":",
"type",
"reader",
":",
"ArrayReader",
":",
"type",
"target",
":",
"int",
":",
"rtype",
":",
"int"
] | def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
low = 0
high = 2 ** 31 - 1
while high - low > 1:
mid = low + (high - low) // 2
val = reader.get(mid)
if val == Solution.INT_MAX:
high = mid
else:
low = mid
n = high
low = 0
high = n - 1
while low <= high:
mid = low + (high - low) // 2
val = reader.get(mid)
if target < val:
high = mid - 1
elif target > val:
low = mid + 1
else:
return mid
return -1 | [
"def",
"search",
"(",
"self",
",",
"reader",
",",
"target",
")",
":",
"low",
"=",
"0",
"high",
"=",
"2",
"**",
"31",
"-",
"1",
"while",
"high",
"-",
"low",
">",
"1",
":",
"mid",
"=",
"low",
"+",
"(",
"high",
"-",
"low",
")",
"//",
"2",
"val",
"=",
"reader",
".",
"get",
"(",
"mid",
")",
"if",
"val",
"==",
"Solution",
".",
"INT_MAX",
":",
"high",
"=",
"mid",
"else",
":",
"low",
"=",
"mid",
"n",
"=",
"high",
"low",
"=",
"0",
"high",
"=",
"n",
"-",
"1",
"while",
"low",
"<=",
"high",
":",
"mid",
"=",
"low",
"+",
"(",
"high",
"-",
"low",
")",
"//",
"2",
"val",
"=",
"reader",
".",
"get",
"(",
"mid",
")",
"if",
"target",
"<",
"val",
":",
"high",
"=",
"mid",
"-",
"1",
"elif",
"target",
">",
"val",
":",
"low",
"=",
"mid",
"+",
"1",
"else",
":",
"return",
"mid",
"return",
"-",
"1"
] | https://github.com/zhuli19901106/leetcode-zhuli/blob/0f8fc29ccb8c33ea91149ecb2d4e961024c11db7/algorithms/0501-1000/0702_search-in-a-sorted-array-of-unknown-size_1_AC.py#L13-L42 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | tile | (A, reps) | return _mx_nd_np.tile(A, reps) | r"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promote `A` to d-dimensions manually before calling this
function.
If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
(1, 1, 2, 2).
Parameters
----------
A : ndarray or scalar
An input array or a scalar to repeat.
reps : a single integer or tuple of integers
The number of repetitions of `A` along each axis.
Returns
-------
c : ndarray
The tiled output array.
Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0., 1., 2., 0., 1., 2.])
>>> np.tile(a, (2, 2))
array([[0., 1., 2., 0., 1., 2.],
[0., 1., 2., 0., 1., 2.]])
>>> np.tile(a, (2, 1, 2))
array([[[0., 1., 2., 0., 1., 2.]],
[[0., 1., 2., 0., 1., 2.]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1., 2., 1., 2.],
[3., 4., 3., 4.]])
>>> np.tile(b, (2, 1))
array([[1., 2.],
[3., 4.],
[1., 2.],
[3., 4.]])
>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.]])
Scalar as input:
>>> np.tile(2, 3)
array([2, 2, 2]) # repeating integer `2` | r"""
Construct an array by repeating A the number of times given by reps. | [
"r",
"Construct",
"an",
"array",
"by",
"repeating",
"A",
"the",
"number",
"of",
"times",
"given",
"by",
"reps",
"."
] | def tile(A, reps):
r"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promote `A` to d-dimensions manually before calling this
function.
If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
(1, 1, 2, 2).
Parameters
----------
A : ndarray or scalar
An input array or a scalar to repeat.
reps : a single integer or tuple of integers
The number of repetitions of `A` along each axis.
Returns
-------
c : ndarray
The tiled output array.
Examples
--------
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0., 1., 2., 0., 1., 2.])
>>> np.tile(a, (2, 2))
array([[0., 1., 2., 0., 1., 2.],
[0., 1., 2., 0., 1., 2.]])
>>> np.tile(a, (2, 1, 2))
array([[[0., 1., 2., 0., 1., 2.]],
[[0., 1., 2., 0., 1., 2.]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1., 2., 1., 2.],
[3., 4., 3., 4.]])
>>> np.tile(b, (2, 1))
array([[1., 2.],
[3., 4.],
[1., 2.],
[3., 4.]])
>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.],
[1., 2., 3., 4.]])
Scalar as input:
>>> np.tile(2, 3)
array([2, 2, 2]) # repeating integer `2`
"""
return _mx_nd_np.tile(A, reps) | [
"def",
"tile",
"(",
"A",
",",
"reps",
")",
":",
"return",
"_mx_nd_np",
".",
"tile",
"(",
"A",
",",
"reps",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L6476-L6540 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/data_structures/gframe.py | python | GFrame.add_columns | (self, data, column_names=None, inplace=False) | Adds columns to the SFrame. The number of elements in all columns must
match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, returning self.
Parameters
----------
data : list[SArray] or SFrame
The columns to add.
column_names: list of string, optional
A list of column names. All names must be specified. ``column_names`` is
ignored if data is an SFrame.
inplace : bool, optional. Defaults to False.
Whether the SFrame is modified in place. | Adds columns to the SFrame. The number of elements in all columns must
match every other column of the SFrame. | [
"Adds",
"columns",
"to",
"the",
"SFrame",
".",
"The",
"number",
"of",
"elements",
"in",
"all",
"columns",
"must",
"match",
"every",
"other",
"column",
"of",
"the",
"SFrame",
"."
] | def add_columns(self, data, column_names=None, inplace=False):
"""
Adds columns to the SFrame. The number of elements in all columns must
match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, returning self.
Parameters
----------
data : list[SArray] or SFrame
The columns to add.
column_names: list of string, optional
A list of column names. All names must be specified. ``column_names`` is
ignored if data is an SFrame.
inplace : bool, optional. Defaults to False.
Whether the SFrame is modified in place.
"""
datalist = data
if isinstance(data, SFrame):
other = data
datalist = [other.select_column(name) for name in other.column_names()]
column_names = other.column_names()
my_columns = set(self.column_names())
for name in column_names:
if name in my_columns:
raise ValueError(
"Column '" + name + "' already exists in current SFrame"
)
else:
if not _is_non_string_iterable(datalist):
raise TypeError("datalist must be an iterable")
if not _is_non_string_iterable(column_names):
raise TypeError("column_names must be an iterable")
if not all([isinstance(x, SArray) for x in datalist]):
raise TypeError("Must give column as SArray")
if not all([isinstance(x, str) for x in column_names]):
raise TypeError("Invalid column name in list : must all be str")
if inplace:
for (data, name) in zip(datalist, column_names):
self.add_column(data, name)
return self
else:
return super(GFrame, self).add_column(
datalist, column_names, inplace=inplace
) | [
"def",
"add_columns",
"(",
"self",
",",
"data",
",",
"column_names",
"=",
"None",
",",
"inplace",
"=",
"False",
")",
":",
"datalist",
"=",
"data",
"if",
"isinstance",
"(",
"data",
",",
"SFrame",
")",
":",
"other",
"=",
"data",
"datalist",
"=",
"[",
"other",
".",
"select_column",
"(",
"name",
")",
"for",
"name",
"in",
"other",
".",
"column_names",
"(",
")",
"]",
"column_names",
"=",
"other",
".",
"column_names",
"(",
")",
"my_columns",
"=",
"set",
"(",
"self",
".",
"column_names",
"(",
")",
")",
"for",
"name",
"in",
"column_names",
":",
"if",
"name",
"in",
"my_columns",
":",
"raise",
"ValueError",
"(",
"\"Column '\"",
"+",
"name",
"+",
"\"' already exists in current SFrame\"",
")",
"else",
":",
"if",
"not",
"_is_non_string_iterable",
"(",
"datalist",
")",
":",
"raise",
"TypeError",
"(",
"\"datalist must be an iterable\"",
")",
"if",
"not",
"_is_non_string_iterable",
"(",
"column_names",
")",
":",
"raise",
"TypeError",
"(",
"\"column_names must be an iterable\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"SArray",
")",
"for",
"x",
"in",
"datalist",
"]",
")",
":",
"raise",
"TypeError",
"(",
"\"Must give column as SArray\"",
")",
"if",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"str",
")",
"for",
"x",
"in",
"column_names",
"]",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid column name in list : must all be str\"",
")",
"if",
"inplace",
":",
"for",
"(",
"data",
",",
"name",
")",
"in",
"zip",
"(",
"datalist",
",",
"column_names",
")",
":",
"self",
".",
"add_column",
"(",
"data",
",",
"name",
")",
"return",
"self",
"else",
":",
"return",
"super",
"(",
"GFrame",
",",
"self",
")",
".",
"add_column",
"(",
"datalist",
",",
"column_names",
",",
"inplace",
"=",
"inplace",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/gframe.py#L108-L162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.