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/importlib/_bootstrap_external.py | python | FileFinder.find_spec | (self, fullname, target=None) | return None | Try to find a spec for the specified module.
Returns the matching spec, or None if not found. | Try to find a spec for the specified module. | [
"Try",
"to",
"find",
"a",
"spec",
"for",
"the",
"specified",
"module",
"."
] | def find_spec(self, fullname, target=None):
"""Try to find a spec for the specified module.
Returns the matching spec, or None if not found.
"""
is_namespace = False
tail_module = fullname.rpartition('.')[2]
try:
mtime = _path_stat(self.path or _os.getcwd()).st_mtime
except OSError:
mtime = -1
if mtime != self._path_mtime:
self._fill_cache()
self._path_mtime = mtime
# tail_module keeps the original casing, for __file__ and friends
if _relax_case():
cache = self._relaxed_path_cache
cache_module = tail_module.lower()
else:
cache = self._path_cache
cache_module = tail_module
# Check if the module is the name of a directory (and thus a package).
if cache_module in cache:
base_path = _path_join(self.path, tail_module)
for suffix, loader_class in self._loaders:
init_filename = '__init__' + suffix
full_path = _path_join(base_path, init_filename)
if _path_isfile(full_path):
return self._get_spec(loader_class, fullname, full_path, [base_path], target)
else:
# If a namespace package, return the path if we don't
# find a module in the next section.
is_namespace = _path_isdir(base_path)
# Check for a file w/ a proper suffix exists.
for suffix, loader_class in self._loaders:
full_path = _path_join(self.path, tail_module + suffix)
_bootstrap._verbose_message('trying {}', full_path, verbosity=2)
if cache_module + suffix in cache:
if _path_isfile(full_path):
return self._get_spec(loader_class, fullname, full_path,
None, target)
if is_namespace:
_bootstrap._verbose_message('possible namespace for {}', base_path)
spec = _bootstrap.ModuleSpec(fullname, None)
spec.submodule_search_locations = [base_path]
return spec
return None | [
"def",
"find_spec",
"(",
"self",
",",
"fullname",
",",
"target",
"=",
"None",
")",
":",
"is_namespace",
"=",
"False",
"tail_module",
"=",
"fullname",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"2",
"]",
"try",
":",
"mtime",
"=",
"_path_stat",
"(",
"self",
".",
"path",
"or",
"_os",
".",
"getcwd",
"(",
")",
")",
".",
"st_mtime",
"except",
"OSError",
":",
"mtime",
"=",
"-",
"1",
"if",
"mtime",
"!=",
"self",
".",
"_path_mtime",
":",
"self",
".",
"_fill_cache",
"(",
")",
"self",
".",
"_path_mtime",
"=",
"mtime",
"# tail_module keeps the original casing, for __file__ and friends",
"if",
"_relax_case",
"(",
")",
":",
"cache",
"=",
"self",
".",
"_relaxed_path_cache",
"cache_module",
"=",
"tail_module",
".",
"lower",
"(",
")",
"else",
":",
"cache",
"=",
"self",
".",
"_path_cache",
"cache_module",
"=",
"tail_module",
"# Check if the module is the name of a directory (and thus a package).",
"if",
"cache_module",
"in",
"cache",
":",
"base_path",
"=",
"_path_join",
"(",
"self",
".",
"path",
",",
"tail_module",
")",
"for",
"suffix",
",",
"loader_class",
"in",
"self",
".",
"_loaders",
":",
"init_filename",
"=",
"'__init__'",
"+",
"suffix",
"full_path",
"=",
"_path_join",
"(",
"base_path",
",",
"init_filename",
")",
"if",
"_path_isfile",
"(",
"full_path",
")",
":",
"return",
"self",
".",
"_get_spec",
"(",
"loader_class",
",",
"fullname",
",",
"full_path",
",",
"[",
"base_path",
"]",
",",
"target",
")",
"else",
":",
"# If a namespace package, return the path if we don't",
"# find a module in the next section.",
"is_namespace",
"=",
"_path_isdir",
"(",
"base_path",
")",
"# Check for a file w/ a proper suffix exists.",
"for",
"suffix",
",",
"loader_class",
"in",
"self",
".",
"_loaders",
":",
"full_path",
"=",
"_path_join",
"(",
"self",
".",
"path",
",",
"tail_module",
"+",
"suffix",
")",
"_bootstrap",
".",
"_verbose_message",
"(",
"'trying {}'",
",",
"full_path",
",",
"verbosity",
"=",
"2",
")",
"if",
"cache_module",
"+",
"suffix",
"in",
"cache",
":",
"if",
"_path_isfile",
"(",
"full_path",
")",
":",
"return",
"self",
".",
"_get_spec",
"(",
"loader_class",
",",
"fullname",
",",
"full_path",
",",
"None",
",",
"target",
")",
"if",
"is_namespace",
":",
"_bootstrap",
".",
"_verbose_message",
"(",
"'possible namespace for {}'",
",",
"base_path",
")",
"spec",
"=",
"_bootstrap",
".",
"ModuleSpec",
"(",
"fullname",
",",
"None",
")",
"spec",
".",
"submodule_search_locations",
"=",
"[",
"base_path",
"]",
"return",
"spec",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap_external.py#L1356-L1402 | |
commaai/openpilot | 4416c21b1e738ab7d04147c5ae52b5135e0cdb40 | pyextra/acados_template/acados_ocp.py | python | AcadosOcpConstraints.idxsphi_e | (self) | return self.__idxsphi_e | Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N.
Can be set by using :py:attr:`Jsphi_e`.
Type: :code:`np.ndarray`; default: :code:`np.array([])` | Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N.
Can be set by using :py:attr:`Jsphi_e`.
Type: :code:`np.ndarray`; default: :code:`np.array([])` | [
"Indices",
"of",
"soft",
"nonlinear",
"constraints",
"at",
"shooting",
"node",
"N",
"within",
"the",
"indices",
"of",
"nonlinear",
"constraints",
"at",
"terminal",
"shooting",
"node",
"N",
".",
"Can",
"be",
"set",
"by",
"using",
":",
"py",
":",
"attr",
":",
"Jsphi_e",
".",
"Type",
":",
":",
"code",
":",
"np",
".",
"ndarray",
";",
"default",
":",
":",
"code",
":",
"np",
".",
"array",
"(",
"[]",
")"
] | def idxsphi_e(self):
"""Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N.
Can be set by using :py:attr:`Jsphi_e`.
Type: :code:`np.ndarray`; default: :code:`np.array([])`"""
return self.__idxsphi_e | [
"def",
"idxsphi_e",
"(",
"self",
")",
":",
"return",
"self",
".",
"__idxsphi_e"
] | https://github.com/commaai/openpilot/blob/4416c21b1e738ab7d04147c5ae52b5135e0cdb40/pyextra/acados_template/acados_ocp.py#L1549-L1553 | |
espressomd/espresso | 7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a | samples/gibbs_ensemble/gibbs_ensemble.py | python | Client.add_particle | (self) | Add a particle at random inside box | Add a particle at random inside box | [
"Add",
"a",
"particle",
"at",
"random",
"inside",
"box"
] | def add_particle(self):
""" Add a particle at random inside box """
self.last_added_particle = self.system.part.add(
pos=np.random.random(3) * self.system.box_l)
self.send_energy() | [
"def",
"add_particle",
"(",
"self",
")",
":",
"self",
".",
"last_added_particle",
"=",
"self",
".",
"system",
".",
"part",
".",
"add",
"(",
"pos",
"=",
"np",
".",
"random",
".",
"random",
"(",
"3",
")",
"*",
"self",
".",
"system",
".",
"box_l",
")",
"self",
".",
"send_energy",
"(",
")"
] | https://github.com/espressomd/espresso/blob/7e29f9052e710fe1ebf0f5d2a8076b32921fbc6a/samples/gibbs_ensemble/gibbs_ensemble.py#L96-L100 | ||
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | grc/gui/ParamWidgets.py | python | DirectoryParam._handle_clicked | (self, widget=None) | Open the directory selector, when the button is clicked.
On success, update the entry. | Open the directory selector, when the button is clicked.
On success, update the entry. | [
"Open",
"the",
"directory",
"selector",
"when",
"the",
"button",
"is",
"clicked",
".",
"On",
"success",
"update",
"the",
"entry",
"."
] | def _handle_clicked(self, widget=None):
"""
Open the directory selector, when the button is clicked.
On success, update the entry.
"""
dirname = self.param.get_evaluated() if self.param.is_valid() else ''
# Check if directory exists, if not fall back to workdir
if not os.path.isdir(dirname):
dirname = os.getcwd()
if self.param.dtype == "dir_select": # Setup directory selection dialog, and fail for unexpected dtype
dir_dialog = Gtk.FileChooserDialog(
title='Select a Directory...', action=Gtk.FileChooserAction.SELECT_FOLDER,
transient_for=self._transient_for
)
else:
raise ValueError(
"Can't open directory chooser dialog for type " + repr(self.param.dtype))
# Set dialog properties
dir_dialog.add_buttons(
'gtk-cancel', Gtk.ResponseType.CANCEL, 'gtk-open', Gtk.ResponseType.OK)
dir_dialog.set_current_folder(dirname)
dir_dialog.set_local_only(True)
dir_dialog.set_select_multiple(False)
# Show dialog and update parameter on success
if Gtk.ResponseType.OK == dir_dialog.run():
path = dir_dialog.get_filename()
self._input.set_text(path)
self._editing_callback()
self._apply_change()
# Cleanup dialog
dir_dialog.destroy() | [
"def",
"_handle_clicked",
"(",
"self",
",",
"widget",
"=",
"None",
")",
":",
"dirname",
"=",
"self",
".",
"param",
".",
"get_evaluated",
"(",
")",
"if",
"self",
".",
"param",
".",
"is_valid",
"(",
")",
"else",
"''",
"# Check if directory exists, if not fall back to workdir",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dirname",
")",
":",
"dirname",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"self",
".",
"param",
".",
"dtype",
"==",
"\"dir_select\"",
":",
"# Setup directory selection dialog, and fail for unexpected dtype",
"dir_dialog",
"=",
"Gtk",
".",
"FileChooserDialog",
"(",
"title",
"=",
"'Select a Directory...'",
",",
"action",
"=",
"Gtk",
".",
"FileChooserAction",
".",
"SELECT_FOLDER",
",",
"transient_for",
"=",
"self",
".",
"_transient_for",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Can't open directory chooser dialog for type \"",
"+",
"repr",
"(",
"self",
".",
"param",
".",
"dtype",
")",
")",
"# Set dialog properties",
"dir_dialog",
".",
"add_buttons",
"(",
"'gtk-cancel'",
",",
"Gtk",
".",
"ResponseType",
".",
"CANCEL",
",",
"'gtk-open'",
",",
"Gtk",
".",
"ResponseType",
".",
"OK",
")",
"dir_dialog",
".",
"set_current_folder",
"(",
"dirname",
")",
"dir_dialog",
".",
"set_local_only",
"(",
"True",
")",
"dir_dialog",
".",
"set_select_multiple",
"(",
"False",
")",
"# Show dialog and update parameter on success",
"if",
"Gtk",
".",
"ResponseType",
".",
"OK",
"==",
"dir_dialog",
".",
"run",
"(",
")",
":",
"path",
"=",
"dir_dialog",
".",
"get_filename",
"(",
")",
"self",
".",
"_input",
".",
"set_text",
"(",
"path",
")",
"self",
".",
"_editing_callback",
"(",
")",
"self",
".",
"_apply_change",
"(",
")",
"# Cleanup dialog",
"dir_dialog",
".",
"destroy",
"(",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/ParamWidgets.py#L351-L386 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/python_setup.py | python | generate_distutils_setup | (package_xml_path=os.path.curdir, **kwargs) | return data | Extract the information relevant for distutils from the package
manifest. The following keys will be set:
The "name" and "version" are taken from the eponymous tags.
A single maintainer will set the keys "maintainer" and
"maintainer_email" while multiple maintainers are merged into the
"maintainer" fields (including their emails). Authors are handled
likewise.
The first URL of type "website" (or without a type) is used for
the "url" field.
The "description" is taken from the eponymous tag if it does not
exceed 200 characters. If it does "description" contains the
truncated text while "description_long" contains the complete.
All licenses are merged into the "license" field.
:param kwargs: All keyword arguments are passed through. The above
mentioned keys are verified to be identical if passed as a
keyword argument
:returns: return dict populated with parsed fields and passed
keyword arguments
:raises: :exc:`InvalidPackage`
:raises: :exc:`IOError` | Extract the information relevant for distutils from the package
manifest. The following keys will be set: | [
"Extract",
"the",
"information",
"relevant",
"for",
"distutils",
"from",
"the",
"package",
"manifest",
".",
"The",
"following",
"keys",
"will",
"be",
"set",
":"
] | def generate_distutils_setup(package_xml_path=os.path.curdir, **kwargs):
"""
Extract the information relevant for distutils from the package
manifest. The following keys will be set:
The "name" and "version" are taken from the eponymous tags.
A single maintainer will set the keys "maintainer" and
"maintainer_email" while multiple maintainers are merged into the
"maintainer" fields (including their emails). Authors are handled
likewise.
The first URL of type "website" (or without a type) is used for
the "url" field.
The "description" is taken from the eponymous tag if it does not
exceed 200 characters. If it does "description" contains the
truncated text while "description_long" contains the complete.
All licenses are merged into the "license" field.
:param kwargs: All keyword arguments are passed through. The above
mentioned keys are verified to be identical if passed as a
keyword argument
:returns: return dict populated with parsed fields and passed
keyword arguments
:raises: :exc:`InvalidPackage`
:raises: :exc:`IOError`
"""
package = parse_package(package_xml_path)
data = {}
data['name'] = package.name
data['version'] = package.version
# either set one author with one email or join all in a single field
if len(package.authors) == 1 and package.authors[0].email is not None:
data['author'] = package.authors[0].name
data['author_email'] = package.authors[0].email
else:
data['author'] = ', '.join([('%s <%s>' % (a.name, a.email) if a.email is not None else a.name) for a in package.authors])
# either set one maintainer with one email or join all in a single field
if len(package.maintainers) == 1:
data['maintainer'] = package.maintainers[0].name
data['maintainer_email'] = package.maintainers[0].email
else:
data['maintainer'] = ', '.join(['%s <%s>' % (m.name, m.email) for m in package.maintainers])
# either set the first URL with the type 'website' or the first URL of any type
websites = [url.url for url in package.urls if url.type == 'website']
if websites:
data['url'] = websites[0]
elif package.urls:
data['url'] = package.urls[0].url
if len(package.description) <= 200:
data['description'] = package.description
else:
data['description'] = package.description[:197] + '...'
data['long_description'] = package.description
data['license'] = ', '.join(package.licenses)
# pass keyword arguments and verify equality if generated and passed in
for k, v in kwargs.items():
if k in data:
if v != data[k]:
raise InvalidPackage('The keyword argument "%s" does not match the information from package.xml: "%s" != "%s"' % (k, v, data[k]))
else:
data[k] = v
return data | [
"def",
"generate_distutils_setup",
"(",
"package_xml_path",
"=",
"os",
".",
"path",
".",
"curdir",
",",
"*",
"*",
"kwargs",
")",
":",
"package",
"=",
"parse_package",
"(",
"package_xml_path",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'name'",
"]",
"=",
"package",
".",
"name",
"data",
"[",
"'version'",
"]",
"=",
"package",
".",
"version",
"# either set one author with one email or join all in a single field",
"if",
"len",
"(",
"package",
".",
"authors",
")",
"==",
"1",
"and",
"package",
".",
"authors",
"[",
"0",
"]",
".",
"email",
"is",
"not",
"None",
":",
"data",
"[",
"'author'",
"]",
"=",
"package",
".",
"authors",
"[",
"0",
"]",
".",
"name",
"data",
"[",
"'author_email'",
"]",
"=",
"package",
".",
"authors",
"[",
"0",
"]",
".",
"email",
"else",
":",
"data",
"[",
"'author'",
"]",
"=",
"', '",
".",
"join",
"(",
"[",
"(",
"'%s <%s>'",
"%",
"(",
"a",
".",
"name",
",",
"a",
".",
"email",
")",
"if",
"a",
".",
"email",
"is",
"not",
"None",
"else",
"a",
".",
"name",
")",
"for",
"a",
"in",
"package",
".",
"authors",
"]",
")",
"# either set one maintainer with one email or join all in a single field",
"if",
"len",
"(",
"package",
".",
"maintainers",
")",
"==",
"1",
":",
"data",
"[",
"'maintainer'",
"]",
"=",
"package",
".",
"maintainers",
"[",
"0",
"]",
".",
"name",
"data",
"[",
"'maintainer_email'",
"]",
"=",
"package",
".",
"maintainers",
"[",
"0",
"]",
".",
"email",
"else",
":",
"data",
"[",
"'maintainer'",
"]",
"=",
"', '",
".",
"join",
"(",
"[",
"'%s <%s>'",
"%",
"(",
"m",
".",
"name",
",",
"m",
".",
"email",
")",
"for",
"m",
"in",
"package",
".",
"maintainers",
"]",
")",
"# either set the first URL with the type 'website' or the first URL of any type",
"websites",
"=",
"[",
"url",
".",
"url",
"for",
"url",
"in",
"package",
".",
"urls",
"if",
"url",
".",
"type",
"==",
"'website'",
"]",
"if",
"websites",
":",
"data",
"[",
"'url'",
"]",
"=",
"websites",
"[",
"0",
"]",
"elif",
"package",
".",
"urls",
":",
"data",
"[",
"'url'",
"]",
"=",
"package",
".",
"urls",
"[",
"0",
"]",
".",
"url",
"if",
"len",
"(",
"package",
".",
"description",
")",
"<=",
"200",
":",
"data",
"[",
"'description'",
"]",
"=",
"package",
".",
"description",
"else",
":",
"data",
"[",
"'description'",
"]",
"=",
"package",
".",
"description",
"[",
":",
"197",
"]",
"+",
"'...'",
"data",
"[",
"'long_description'",
"]",
"=",
"package",
".",
"description",
"data",
"[",
"'license'",
"]",
"=",
"', '",
".",
"join",
"(",
"package",
".",
"licenses",
")",
"# pass keyword arguments and verify equality if generated and passed in",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"data",
":",
"if",
"v",
"!=",
"data",
"[",
"k",
"]",
":",
"raise",
"InvalidPackage",
"(",
"'The keyword argument \"%s\" does not match the information from package.xml: \"%s\" != \"%s\"'",
"%",
"(",
"k",
",",
"v",
",",
"data",
"[",
"k",
"]",
")",
")",
"else",
":",
"data",
"[",
"k",
"]",
"=",
"v",
"return",
"data"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/catkin_pkg/python_setup.py#L46-L119 | |
root-project/root | fcd3583bb14852bf2e8cd2415717cbaac0e75896 | interpreter/llvm/src/utils/sort_includes.py | python | sort_includes | (f) | Sort the #include lines of a specific file. | Sort the #include lines of a specific file. | [
"Sort",
"the",
"#include",
"lines",
"of",
"a",
"specific",
"file",
"."
] | def sort_includes(f):
"""Sort the #include lines of a specific file."""
# Skip files which are under INPUTS trees or test trees.
if 'INPUTS/' in f.name or 'test/' in f.name:
return
ext = os.path.splitext(f.name)[1]
if ext not in ['.cpp', '.c', '.h', '.inc', '.def']:
return
lines = f.readlines()
look_for_api_header = ext in ['.cpp', '.c']
found_headers = False
headers_begin = 0
headers_end = 0
api_headers = []
local_headers = []
subproject_headers = []
llvm_headers = []
system_headers = []
for (i, l) in enumerate(lines):
if l.strip() == '':
continue
if l.startswith('#include'):
if not found_headers:
headers_begin = i
found_headers = True
headers_end = i
header = l[len('#include'):].lstrip()
if look_for_api_header and header.startswith('"'):
api_headers.append(header)
look_for_api_header = False
continue
if (header.startswith('<') or header.startswith('"gtest/') or
header.startswith('"isl/') or header.startswith('"json/')):
system_headers.append(header)
continue
if (header.startswith('"clang/') or header.startswith('"clang-c/') or
header.startswith('"polly/')):
subproject_headers.append(header)
continue
if (header.startswith('"llvm/') or header.startswith('"llvm-c/')):
llvm_headers.append(header)
continue
local_headers.append(header)
continue
# Only allow comments and #defines prior to any includes. If either are
# mixed with includes, the order might be sensitive.
if found_headers:
break
if l.startswith('//') or l.startswith('#define') or l.startswith('#ifndef'):
continue
break
if not found_headers:
return
local_headers = sorted(set(local_headers))
subproject_headers = sorted(set(subproject_headers))
llvm_headers = sorted(set(llvm_headers))
system_headers = sorted(set(system_headers))
headers = api_headers + local_headers + subproject_headers + llvm_headers + system_headers
header_lines = ['#include ' + h for h in headers]
lines = lines[:headers_begin] + header_lines + lines[headers_end + 1:]
f.seek(0)
f.truncate()
f.writelines(lines) | [
"def",
"sort_includes",
"(",
"f",
")",
":",
"# Skip files which are under INPUTS trees or test trees.",
"if",
"'INPUTS/'",
"in",
"f",
".",
"name",
"or",
"'test/'",
"in",
"f",
".",
"name",
":",
"return",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"f",
".",
"name",
")",
"[",
"1",
"]",
"if",
"ext",
"not",
"in",
"[",
"'.cpp'",
",",
"'.c'",
",",
"'.h'",
",",
"'.inc'",
",",
"'.def'",
"]",
":",
"return",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"look_for_api_header",
"=",
"ext",
"in",
"[",
"'.cpp'",
",",
"'.c'",
"]",
"found_headers",
"=",
"False",
"headers_begin",
"=",
"0",
"headers_end",
"=",
"0",
"api_headers",
"=",
"[",
"]",
"local_headers",
"=",
"[",
"]",
"subproject_headers",
"=",
"[",
"]",
"llvm_headers",
"=",
"[",
"]",
"system_headers",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"l",
")",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"l",
".",
"strip",
"(",
")",
"==",
"''",
":",
"continue",
"if",
"l",
".",
"startswith",
"(",
"'#include'",
")",
":",
"if",
"not",
"found_headers",
":",
"headers_begin",
"=",
"i",
"found_headers",
"=",
"True",
"headers_end",
"=",
"i",
"header",
"=",
"l",
"[",
"len",
"(",
"'#include'",
")",
":",
"]",
".",
"lstrip",
"(",
")",
"if",
"look_for_api_header",
"and",
"header",
".",
"startswith",
"(",
"'\"'",
")",
":",
"api_headers",
".",
"append",
"(",
"header",
")",
"look_for_api_header",
"=",
"False",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'<'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"gtest/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"isl/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"json/'",
")",
")",
":",
"system_headers",
".",
"append",
"(",
"header",
")",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'\"clang/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"clang-c/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"polly/'",
")",
")",
":",
"subproject_headers",
".",
"append",
"(",
"header",
")",
"continue",
"if",
"(",
"header",
".",
"startswith",
"(",
"'\"llvm/'",
")",
"or",
"header",
".",
"startswith",
"(",
"'\"llvm-c/'",
")",
")",
":",
"llvm_headers",
".",
"append",
"(",
"header",
")",
"continue",
"local_headers",
".",
"append",
"(",
"header",
")",
"continue",
"# Only allow comments and #defines prior to any includes. If either are",
"# mixed with includes, the order might be sensitive.",
"if",
"found_headers",
":",
"break",
"if",
"l",
".",
"startswith",
"(",
"'//'",
")",
"or",
"l",
".",
"startswith",
"(",
"'#define'",
")",
"or",
"l",
".",
"startswith",
"(",
"'#ifndef'",
")",
":",
"continue",
"break",
"if",
"not",
"found_headers",
":",
"return",
"local_headers",
"=",
"sorted",
"(",
"set",
"(",
"local_headers",
")",
")",
"subproject_headers",
"=",
"sorted",
"(",
"set",
"(",
"subproject_headers",
")",
")",
"llvm_headers",
"=",
"sorted",
"(",
"set",
"(",
"llvm_headers",
")",
")",
"system_headers",
"=",
"sorted",
"(",
"set",
"(",
"system_headers",
")",
")",
"headers",
"=",
"api_headers",
"+",
"local_headers",
"+",
"subproject_headers",
"+",
"llvm_headers",
"+",
"system_headers",
"header_lines",
"=",
"[",
"'#include '",
"+",
"h",
"for",
"h",
"in",
"headers",
"]",
"lines",
"=",
"lines",
"[",
":",
"headers_begin",
"]",
"+",
"header_lines",
"+",
"lines",
"[",
"headers_end",
"+",
"1",
":",
"]",
"f",
".",
"seek",
"(",
"0",
")",
"f",
".",
"truncate",
"(",
")",
"f",
".",
"writelines",
"(",
"lines",
")"
] | https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/utils/sort_includes.py#L14-L82 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_windows.py | python | Dialog.CreateTextSizer | (*args, **kwargs) | return _windows_.Dialog_CreateTextSizer(*args, **kwargs) | CreateTextSizer(self, String message) -> Sizer | CreateTextSizer(self, String message) -> Sizer | [
"CreateTextSizer",
"(",
"self",
"String",
"message",
")",
"-",
">",
"Sizer"
] | def CreateTextSizer(*args, **kwargs):
"""CreateTextSizer(self, String message) -> Sizer"""
return _windows_.Dialog_CreateTextSizer(*args, **kwargs) | [
"def",
"CreateTextSizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"Dialog_CreateTextSizer",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L776-L778 | |
NASA-SW-VnV/ikos | 71325dfb94737332542caa708d7537752021522d | analyzer/python/ikos/report.py | python | generate_summary | (db) | return summary | Return the analysis summary: number of errors, warnings, ok and
unreachable per checked statements. | Return the analysis summary: number of errors, warnings, ok and
unreachable per checked statements. | [
"Return",
"the",
"analysis",
"summary",
":",
"number",
"of",
"errors",
"warnings",
"ok",
"and",
"unreachable",
"per",
"checked",
"statements",
"."
] | def generate_summary(db):
'''
Return the analysis summary: number of errors, warnings, ok and
unreachable per checked statements.
'''
summary = Summary(ok=0, error=0, warning=0, unreachable=0)
c = db.con.cursor()
order_by = 'statement_id, call_context_id'
c.execute('SELECT * FROM checks ORDER BY %s' % order_by)
stmt_id_key = operator.itemgetter(ChecksTable.STATEMENT_ID)
context_id_key = operator.itemgetter(ChecksTable.CALL_CONTEXT_ID)
for statement_id, statement_checks in itertools.groupby(c,
key=stmt_id_key):
# Iterate over the checks for statement = statement_id
statement_results = set()
statement_checkers = set()
statement_errors = set()
statement_warnings = set()
for context_id, checks in itertools.groupby(statement_checks,
key=context_id_key):
# Iterate over the checks for statement = statement_id
# and context = context_id
result, errors, warnings, _, checkers = \
generate_statement_result(checks,
keep_oks=False,
keep_checkers=True)
statement_results.add(result)
statement_checkers.update(checkers)
statement_errors.update(errors)
statement_warnings.update(warnings)
if statement_results == {Result.UNREACHABLE}:
# Statement is unreachable for all the calling contexts,
# check that it comes from dca
if CheckerName.DEAD_CODE in statement_checkers:
# Statement is never reachable
summary.unreachable += 1
else:
if Result.OK in statement_results:
# Some paths are safe
summary.ok += 1
summary.error += len(statement_errors)
summary.warning += len(statement_warnings)
c.close()
return summary | [
"def",
"generate_summary",
"(",
"db",
")",
":",
"summary",
"=",
"Summary",
"(",
"ok",
"=",
"0",
",",
"error",
"=",
"0",
",",
"warning",
"=",
"0",
",",
"unreachable",
"=",
"0",
")",
"c",
"=",
"db",
".",
"con",
".",
"cursor",
"(",
")",
"order_by",
"=",
"'statement_id, call_context_id'",
"c",
".",
"execute",
"(",
"'SELECT * FROM checks ORDER BY %s'",
"%",
"order_by",
")",
"stmt_id_key",
"=",
"operator",
".",
"itemgetter",
"(",
"ChecksTable",
".",
"STATEMENT_ID",
")",
"context_id_key",
"=",
"operator",
".",
"itemgetter",
"(",
"ChecksTable",
".",
"CALL_CONTEXT_ID",
")",
"for",
"statement_id",
",",
"statement_checks",
"in",
"itertools",
".",
"groupby",
"(",
"c",
",",
"key",
"=",
"stmt_id_key",
")",
":",
"# Iterate over the checks for statement = statement_id",
"statement_results",
"=",
"set",
"(",
")",
"statement_checkers",
"=",
"set",
"(",
")",
"statement_errors",
"=",
"set",
"(",
")",
"statement_warnings",
"=",
"set",
"(",
")",
"for",
"context_id",
",",
"checks",
"in",
"itertools",
".",
"groupby",
"(",
"statement_checks",
",",
"key",
"=",
"context_id_key",
")",
":",
"# Iterate over the checks for statement = statement_id",
"# and context = context_id",
"result",
",",
"errors",
",",
"warnings",
",",
"_",
",",
"checkers",
"=",
"generate_statement_result",
"(",
"checks",
",",
"keep_oks",
"=",
"False",
",",
"keep_checkers",
"=",
"True",
")",
"statement_results",
".",
"add",
"(",
"result",
")",
"statement_checkers",
".",
"update",
"(",
"checkers",
")",
"statement_errors",
".",
"update",
"(",
"errors",
")",
"statement_warnings",
".",
"update",
"(",
"warnings",
")",
"if",
"statement_results",
"==",
"{",
"Result",
".",
"UNREACHABLE",
"}",
":",
"# Statement is unreachable for all the calling contexts,",
"# check that it comes from dca",
"if",
"CheckerName",
".",
"DEAD_CODE",
"in",
"statement_checkers",
":",
"# Statement is never reachable",
"summary",
".",
"unreachable",
"+=",
"1",
"else",
":",
"if",
"Result",
".",
"OK",
"in",
"statement_results",
":",
"# Some paths are safe",
"summary",
".",
"ok",
"+=",
"1",
"summary",
".",
"error",
"+=",
"len",
"(",
"statement_errors",
")",
"summary",
".",
"warning",
"+=",
"len",
"(",
"statement_warnings",
")",
"c",
".",
"close",
"(",
")",
"return",
"summary"
] | https://github.com/NASA-SW-VnV/ikos/blob/71325dfb94737332542caa708d7537752021522d/analyzer/python/ikos/report.py#L181-L231 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/dom/expatbuilder.py | python | Namespaces.install | (self, parser) | Insert the namespace-handlers onto the parser. | Insert the namespace-handlers onto the parser. | [
"Insert",
"the",
"namespace",
"-",
"handlers",
"onto",
"the",
"parser",
"."
] | def install(self, parser):
"""Insert the namespace-handlers onto the parser."""
ExpatBuilder.install(self, parser)
if self._options.namespace_declarations:
parser.StartNamespaceDeclHandler = (
self.start_namespace_decl_handler) | [
"def",
"install",
"(",
"self",
",",
"parser",
")",
":",
"ExpatBuilder",
".",
"install",
"(",
"self",
",",
"parser",
")",
"if",
"self",
".",
"_options",
".",
"namespace_declarations",
":",
"parser",
".",
"StartNamespaceDeclHandler",
"=",
"(",
"self",
".",
"start_namespace_decl_handler",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/dom/expatbuilder.py#L732-L737 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py | python | NDFrame._validate_dtype | (self, dtype) | return dtype | validate the passed dtype | validate the passed dtype | [
"validate",
"the",
"passed",
"dtype"
] | def _validate_dtype(self, dtype):
""" validate the passed dtype """
if dtype is not None:
dtype = pandas_dtype(dtype)
# a compound dtype
if dtype.kind == "V":
raise NotImplementedError(
"compound dtypes are not implemented"
f" in the {type(self).__name__} constructor"
)
return dtype | [
"def",
"_validate_dtype",
"(",
"self",
",",
"dtype",
")",
":",
"if",
"dtype",
"is",
"not",
"None",
":",
"dtype",
"=",
"pandas_dtype",
"(",
"dtype",
")",
"# a compound dtype",
"if",
"dtype",
".",
"kind",
"==",
"\"V\"",
":",
"raise",
"NotImplementedError",
"(",
"\"compound dtypes are not implemented\"",
"f\" in the {type(self).__name__} constructor\"",
")",
"return",
"dtype"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/generic.py#L255-L268 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/lib2to3/fixer_util.py | python | Subscript | (index_node) | return Node(syms.trailer, [Leaf(token.LBRACE, "["),
index_node,
Leaf(token.RBRACE, "]")]) | A numeric or string subscript | A numeric or string subscript | [
"A",
"numeric",
"or",
"string",
"subscript"
] | def Subscript(index_node):
"""A numeric or string subscript"""
return Node(syms.trailer, [Leaf(token.LBRACE, "["),
index_node,
Leaf(token.RBRACE, "]")]) | [
"def",
"Subscript",
"(",
"index_node",
")",
":",
"return",
"Node",
"(",
"syms",
".",
"trailer",
",",
"[",
"Leaf",
"(",
"token",
".",
"LBRACE",
",",
"\"[\"",
")",
",",
"index_node",
",",
"Leaf",
"(",
"token",
".",
"RBRACE",
",",
"\"]\"",
")",
"]",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/lib2to3/fixer_util.py#L77-L81 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/pubsub.py | python | _TopicTreeNode.hasSubtopic | (self, subtopic) | return self.__subtopics.has_key(subtopic) | Return true only if topic string is one of subtopics of this node | Return true only if topic string is one of subtopics of this node | [
"Return",
"true",
"only",
"if",
"topic",
"string",
"is",
"one",
"of",
"subtopics",
"of",
"this",
"node"
] | def hasSubtopic(self, subtopic):
"""Return true only if topic string is one of subtopics of this node"""
return self.__subtopics.has_key(subtopic) | [
"def",
"hasSubtopic",
"(",
"self",
",",
"subtopic",
")",
":",
"return",
"self",
".",
"__subtopics",
".",
"has_key",
"(",
"subtopic",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/pubsub.py#L285-L287 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/math_ops.py | python | tensordot | (a, b, axes, name=None) | r"""Tensor contraction of a and b along specified axes and outer product.
Tensordot (also known as tensor contraction) sums the product of elements
from `a` and `b` over the indices specified by `axes`.
This operation corresponds to `numpy.tensordot(a, b, axes)`.
Example 1: When `a` and `b` are matrices (order 2), the case `axes=1`
is equivalent to matrix multiplication.
Example 2: When `a` and `b` are matrices (order 2), the case
`axes = [[1], [0]]` is equivalent to matrix multiplication.
Example 3: When `a` and `b` are matrices (order 2), the case `axes=0` gives
the outer product, a tensor of order 4.
Example 4: Suppose that \\(a_{ijk}\\) and \\(b_{lmn}\\) represent two
tensors of order 3. Then, `contract(a, b, [[0], [2]])` is the order 4 tensor
\\(c_{jklm}\\) whose entry
corresponding to the indices \\((j,k,l,m)\\) is given by:
\\( c_{jklm} = \sum_i a_{ijk} b_{lmi} \\).
In general, `order(c) = order(a) + order(b) - 2*len(axes[0])`.
Args:
a: `Tensor` of type `float32` or `float64`.
b: `Tensor` with the same type as `a`.
axes: Either a scalar `N`, or a list or an `int32` `Tensor` of shape [2, k].
If axes is a scalar, sum over the last N axes of a and the first N axes of
b in order. If axes is a list or `Tensor` the first and second row contain
the set of unique integers specifying axes along which the contraction is
computed, for `a` and `b`, respectively. The number of axes for `a` and
`b` must be equal. If `axes=0`, computes the outer product between `a` and
`b`.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `a`.
Raises:
ValueError: If the shapes of `a`, `b`, and `axes` are incompatible.
IndexError: If the values in axes exceed the rank of the corresponding
tensor. | r"""Tensor contraction of a and b along specified axes and outer product. | [
"r",
"Tensor",
"contraction",
"of",
"a",
"and",
"b",
"along",
"specified",
"axes",
"and",
"outer",
"product",
"."
] | def tensordot(a, b, axes, name=None):
r"""Tensor contraction of a and b along specified axes and outer product.
Tensordot (also known as tensor contraction) sums the product of elements
from `a` and `b` over the indices specified by `axes`.
This operation corresponds to `numpy.tensordot(a, b, axes)`.
Example 1: When `a` and `b` are matrices (order 2), the case `axes=1`
is equivalent to matrix multiplication.
Example 2: When `a` and `b` are matrices (order 2), the case
`axes = [[1], [0]]` is equivalent to matrix multiplication.
Example 3: When `a` and `b` are matrices (order 2), the case `axes=0` gives
the outer product, a tensor of order 4.
Example 4: Suppose that \\(a_{ijk}\\) and \\(b_{lmn}\\) represent two
tensors of order 3. Then, `contract(a, b, [[0], [2]])` is the order 4 tensor
\\(c_{jklm}\\) whose entry
corresponding to the indices \\((j,k,l,m)\\) is given by:
\\( c_{jklm} = \sum_i a_{ijk} b_{lmi} \\).
In general, `order(c) = order(a) + order(b) - 2*len(axes[0])`.
Args:
a: `Tensor` of type `float32` or `float64`.
b: `Tensor` with the same type as `a`.
axes: Either a scalar `N`, or a list or an `int32` `Tensor` of shape [2, k].
If axes is a scalar, sum over the last N axes of a and the first N axes of
b in order. If axes is a list or `Tensor` the first and second row contain
the set of unique integers specifying axes along which the contraction is
computed, for `a` and `b`, respectively. The number of axes for `a` and
`b` must be equal. If `axes=0`, computes the outer product between `a` and
`b`.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `a`.
Raises:
ValueError: If the shapes of `a`, `b`, and `axes` are incompatible.
IndexError: If the values in axes exceed the rank of the corresponding
tensor.
"""
def _tensordot_reshape(a, axes, flipped=False):
"""Helper method to perform transpose and reshape for contraction op.
This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul`
using `array_ops.transpose` and `array_ops.reshape`. The method takes a
tensor and performs the correct transpose and reshape operation for a given
set of indices. It returns the reshaped tensor as well as a list of indices
necessary to reshape the tensor again after matrix multiplication.
Args:
a: `Tensor`.
axes: List or `int32` `Tensor` of unique indices specifying valid axes of
`a`.
flipped: An optional `bool`. Defaults to `False`. If `True`, the method
assumes that `a` is the second argument in the contraction operation.
Returns:
A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is
the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is
either a list of integers or an `int32` `Tensor`, depending on whether
the shape of a is fully specified, and free_dims_static is either a list
of integers and None values, or None, representing the inferred
static shape of the free dimensions
"""
if a.get_shape().is_fully_defined() and isinstance(axes, (list, tuple)):
shape_a = a.get_shape().as_list()
axes = [i if i >= 0 else i + len(shape_a) for i in axes]
free = [i for i in builtins.range(len(shape_a)) if i not in axes]
free_dims = [shape_a[i] for i in free]
prod_free = int(np.prod([shape_a[i] for i in free]))
prod_axes = int(np.prod([shape_a[i] for i in axes]))
perm = list(axes) + free if flipped else free + list(axes)
new_shape = [prod_axes, prod_free] if flipped else [prod_free, prod_axes]
if (perm != np.arange(len(shape_a))).any():
a_trans = array_ops.transpose(a, perm)
else:
a_trans = a
if a_trans.get_shape().as_list() != new_shape:
reshaped_a = array_ops.reshape(a_trans, new_shape)
else:
reshaped_a = a_trans
return reshaped_a, free_dims, free_dims
else:
if a.get_shape().ndims is not None and isinstance(axes, (list, tuple)):
shape_a = a.get_shape().as_list()
axes = [i if i >= 0 else i + len(shape_a) for i in axes]
free = [i for i in builtins.range(len(shape_a)) if i not in axes]
axes_dims = [shape_a[i] for i in axes]
free_dims = [shape_a[i] for i in free]
free_dims_static = free_dims
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name="axes")
free = ops.convert_to_tensor(free, dtype=dtypes.int32, name="free")
shape_a = array_ops.shape(a)
else:
free_dims_static = None
shape_a = array_ops.shape(a)
rank_a = array_ops.rank(a)
axes = ops.convert_to_tensor(axes, dtype=dtypes.int32, name="axes")
axes = array_ops.where(axes >= 0, axes, axes + rank_a)
free, _ = gen_array_ops.list_diff(range(rank_a), axes, dtypes.int32)
free_dims = array_ops.gather(shape_a, free)
axes_dims = array_ops.gather(shape_a, axes)
prod_free_dims = reduce_prod(free_dims)
prod_axes_dims = reduce_prod(axes_dims)
if flipped:
perm = array_ops.concat([axes, free], 0)
new_shape = array_ops.stack([prod_axes_dims, prod_free_dims])
else:
perm = array_ops.concat([free, axes], 0)
new_shape = array_ops.stack([prod_free_dims, prod_axes_dims])
reshaped_a = array_ops.reshape(array_ops.transpose(a, perm), new_shape)
return reshaped_a, free_dims, free_dims_static
def _tensordot_axes(a, axes):
"""Generates two sets of contraction axes for the two tensor arguments."""
a_shape = a.get_shape()
if isinstance(axes, compat.integral_types):
if axes < 0:
raise ValueError(f"`axes` must be at least 0. Received: {axes}.")
if a_shape.ndims is not None:
if axes > a_shape.ndims:
raise ValueError(f"`axes` must not be larger than the number of "
f"dimensions of tensor {a}. Received {axes}, vs "
f"tensor dimensions {a_shape.ndims}.")
return (list(builtins.range(a_shape.ndims - axes,
a_shape.ndims)), list(builtins.range(axes)))
else:
rank = array_ops.rank(a)
return (range(rank - axes, rank,
dtype=dtypes.int32), range(axes, dtype=dtypes.int32))
elif isinstance(axes, (list, tuple)):
if len(axes) != 2:
raise ValueError(
f"`axes` must be an integer or have length 2. Received {axes}.")
a_axes = axes[0]
b_axes = axes[1]
if isinstance(a_axes, compat.integral_types) and \
isinstance(b_axes, compat.integral_types):
a_axes = [a_axes]
b_axes = [b_axes]
if len(a_axes) != len(b_axes):
raise ValueError(f"Different number of contraction axes `a` and `b`, "
f"{len(a_axes)} != {len(b_axes)}.")
return a_axes, b_axes
else:
axes = ops.convert_to_tensor(axes, name="axes", dtype=dtypes.int32)
return axes[0], axes[1]
with ops.name_scope(name, "Tensordot", [a, b, axes]) as name:
a = ops.convert_to_tensor(a, name="a")
b = ops.convert_to_tensor(b, name="b")
a_axes, b_axes = _tensordot_axes(a, axes)
a_reshape, a_free_dims, a_free_dims_static = _tensordot_reshape(a, a_axes)
b_reshape, b_free_dims, b_free_dims_static = _tensordot_reshape(
b, b_axes, True)
ab_matmul = matmul(a_reshape, b_reshape)
if isinstance(a_free_dims, list) and isinstance(b_free_dims, list):
if (ab_matmul.get_shape().is_fully_defined() and
ab_matmul.get_shape().as_list() == a_free_dims + b_free_dims):
return ab_matmul
else:
return array_ops.reshape(
ab_matmul, a_free_dims + b_free_dims, name=name)
else:
a_free_dims = ops.convert_to_tensor(a_free_dims, dtype=dtypes.int32)
b_free_dims = ops.convert_to_tensor(b_free_dims, dtype=dtypes.int32)
product = array_ops.reshape(
ab_matmul, array_ops.concat([a_free_dims, b_free_dims], 0), name=name)
if a_free_dims_static is not None and b_free_dims_static is not None:
product.set_shape(a_free_dims_static + b_free_dims_static)
return product | [
"def",
"tensordot",
"(",
"a",
",",
"b",
",",
"axes",
",",
"name",
"=",
"None",
")",
":",
"def",
"_tensordot_reshape",
"(",
"a",
",",
"axes",
",",
"flipped",
"=",
"False",
")",
":",
"\"\"\"Helper method to perform transpose and reshape for contraction op.\n\n This method is helpful in reducing `math_ops.tensordot` to `math_ops.matmul`\n using `array_ops.transpose` and `array_ops.reshape`. The method takes a\n tensor and performs the correct transpose and reshape operation for a given\n set of indices. It returns the reshaped tensor as well as a list of indices\n necessary to reshape the tensor again after matrix multiplication.\n\n Args:\n a: `Tensor`.\n axes: List or `int32` `Tensor` of unique indices specifying valid axes of\n `a`.\n flipped: An optional `bool`. Defaults to `False`. If `True`, the method\n assumes that `a` is the second argument in the contraction operation.\n\n Returns:\n A tuple `(reshaped_a, free_dims, free_dims_static)` where `reshaped_a` is\n the tensor `a` reshaped to allow contraction via `matmul`, `free_dims` is\n either a list of integers or an `int32` `Tensor`, depending on whether\n the shape of a is fully specified, and free_dims_static is either a list\n of integers and None values, or None, representing the inferred\n static shape of the free dimensions\n \"\"\"",
"if",
"a",
".",
"get_shape",
"(",
")",
".",
"is_fully_defined",
"(",
")",
"and",
"isinstance",
"(",
"axes",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"shape_a",
"=",
"a",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"axes",
"=",
"[",
"i",
"if",
"i",
">=",
"0",
"else",
"i",
"+",
"len",
"(",
"shape_a",
")",
"for",
"i",
"in",
"axes",
"]",
"free",
"=",
"[",
"i",
"for",
"i",
"in",
"builtins",
".",
"range",
"(",
"len",
"(",
"shape_a",
")",
")",
"if",
"i",
"not",
"in",
"axes",
"]",
"free_dims",
"=",
"[",
"shape_a",
"[",
"i",
"]",
"for",
"i",
"in",
"free",
"]",
"prod_free",
"=",
"int",
"(",
"np",
".",
"prod",
"(",
"[",
"shape_a",
"[",
"i",
"]",
"for",
"i",
"in",
"free",
"]",
")",
")",
"prod_axes",
"=",
"int",
"(",
"np",
".",
"prod",
"(",
"[",
"shape_a",
"[",
"i",
"]",
"for",
"i",
"in",
"axes",
"]",
")",
")",
"perm",
"=",
"list",
"(",
"axes",
")",
"+",
"free",
"if",
"flipped",
"else",
"free",
"+",
"list",
"(",
"axes",
")",
"new_shape",
"=",
"[",
"prod_axes",
",",
"prod_free",
"]",
"if",
"flipped",
"else",
"[",
"prod_free",
",",
"prod_axes",
"]",
"if",
"(",
"perm",
"!=",
"np",
".",
"arange",
"(",
"len",
"(",
"shape_a",
")",
")",
")",
".",
"any",
"(",
")",
":",
"a_trans",
"=",
"array_ops",
".",
"transpose",
"(",
"a",
",",
"perm",
")",
"else",
":",
"a_trans",
"=",
"a",
"if",
"a_trans",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"!=",
"new_shape",
":",
"reshaped_a",
"=",
"array_ops",
".",
"reshape",
"(",
"a_trans",
",",
"new_shape",
")",
"else",
":",
"reshaped_a",
"=",
"a_trans",
"return",
"reshaped_a",
",",
"free_dims",
",",
"free_dims",
"else",
":",
"if",
"a",
".",
"get_shape",
"(",
")",
".",
"ndims",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"axes",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"shape_a",
"=",
"a",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"axes",
"=",
"[",
"i",
"if",
"i",
">=",
"0",
"else",
"i",
"+",
"len",
"(",
"shape_a",
")",
"for",
"i",
"in",
"axes",
"]",
"free",
"=",
"[",
"i",
"for",
"i",
"in",
"builtins",
".",
"range",
"(",
"len",
"(",
"shape_a",
")",
")",
"if",
"i",
"not",
"in",
"axes",
"]",
"axes_dims",
"=",
"[",
"shape_a",
"[",
"i",
"]",
"for",
"i",
"in",
"axes",
"]",
"free_dims",
"=",
"[",
"shape_a",
"[",
"i",
"]",
"for",
"i",
"in",
"free",
"]",
"free_dims_static",
"=",
"free_dims",
"axes",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"axes",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"\"axes\"",
")",
"free",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"free",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"\"free\"",
")",
"shape_a",
"=",
"array_ops",
".",
"shape",
"(",
"a",
")",
"else",
":",
"free_dims_static",
"=",
"None",
"shape_a",
"=",
"array_ops",
".",
"shape",
"(",
"a",
")",
"rank_a",
"=",
"array_ops",
".",
"rank",
"(",
"a",
")",
"axes",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"axes",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
",",
"name",
"=",
"\"axes\"",
")",
"axes",
"=",
"array_ops",
".",
"where",
"(",
"axes",
">=",
"0",
",",
"axes",
",",
"axes",
"+",
"rank_a",
")",
"free",
",",
"_",
"=",
"gen_array_ops",
".",
"list_diff",
"(",
"range",
"(",
"rank_a",
")",
",",
"axes",
",",
"dtypes",
".",
"int32",
")",
"free_dims",
"=",
"array_ops",
".",
"gather",
"(",
"shape_a",
",",
"free",
")",
"axes_dims",
"=",
"array_ops",
".",
"gather",
"(",
"shape_a",
",",
"axes",
")",
"prod_free_dims",
"=",
"reduce_prod",
"(",
"free_dims",
")",
"prod_axes_dims",
"=",
"reduce_prod",
"(",
"axes_dims",
")",
"if",
"flipped",
":",
"perm",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"axes",
",",
"free",
"]",
",",
"0",
")",
"new_shape",
"=",
"array_ops",
".",
"stack",
"(",
"[",
"prod_axes_dims",
",",
"prod_free_dims",
"]",
")",
"else",
":",
"perm",
"=",
"array_ops",
".",
"concat",
"(",
"[",
"free",
",",
"axes",
"]",
",",
"0",
")",
"new_shape",
"=",
"array_ops",
".",
"stack",
"(",
"[",
"prod_free_dims",
",",
"prod_axes_dims",
"]",
")",
"reshaped_a",
"=",
"array_ops",
".",
"reshape",
"(",
"array_ops",
".",
"transpose",
"(",
"a",
",",
"perm",
")",
",",
"new_shape",
")",
"return",
"reshaped_a",
",",
"free_dims",
",",
"free_dims_static",
"def",
"_tensordot_axes",
"(",
"a",
",",
"axes",
")",
":",
"\"\"\"Generates two sets of contraction axes for the two tensor arguments.\"\"\"",
"a_shape",
"=",
"a",
".",
"get_shape",
"(",
")",
"if",
"isinstance",
"(",
"axes",
",",
"compat",
".",
"integral_types",
")",
":",
"if",
"axes",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"f\"`axes` must be at least 0. Received: {axes}.\"",
")",
"if",
"a_shape",
".",
"ndims",
"is",
"not",
"None",
":",
"if",
"axes",
">",
"a_shape",
".",
"ndims",
":",
"raise",
"ValueError",
"(",
"f\"`axes` must not be larger than the number of \"",
"f\"dimensions of tensor {a}. Received {axes}, vs \"",
"f\"tensor dimensions {a_shape.ndims}.\"",
")",
"return",
"(",
"list",
"(",
"builtins",
".",
"range",
"(",
"a_shape",
".",
"ndims",
"-",
"axes",
",",
"a_shape",
".",
"ndims",
")",
")",
",",
"list",
"(",
"builtins",
".",
"range",
"(",
"axes",
")",
")",
")",
"else",
":",
"rank",
"=",
"array_ops",
".",
"rank",
"(",
"a",
")",
"return",
"(",
"range",
"(",
"rank",
"-",
"axes",
",",
"rank",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
",",
"range",
"(",
"axes",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
")",
"elif",
"isinstance",
"(",
"axes",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"len",
"(",
"axes",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"f\"`axes` must be an integer or have length 2. Received {axes}.\"",
")",
"a_axes",
"=",
"axes",
"[",
"0",
"]",
"b_axes",
"=",
"axes",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"a_axes",
",",
"compat",
".",
"integral_types",
")",
"and",
"isinstance",
"(",
"b_axes",
",",
"compat",
".",
"integral_types",
")",
":",
"a_axes",
"=",
"[",
"a_axes",
"]",
"b_axes",
"=",
"[",
"b_axes",
"]",
"if",
"len",
"(",
"a_axes",
")",
"!=",
"len",
"(",
"b_axes",
")",
":",
"raise",
"ValueError",
"(",
"f\"Different number of contraction axes `a` and `b`, \"",
"f\"{len(a_axes)} != {len(b_axes)}.\"",
")",
"return",
"a_axes",
",",
"b_axes",
"else",
":",
"axes",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"axes",
",",
"name",
"=",
"\"axes\"",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"return",
"axes",
"[",
"0",
"]",
",",
"axes",
"[",
"1",
"]",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"\"Tensordot\"",
",",
"[",
"a",
",",
"b",
",",
"axes",
"]",
")",
"as",
"name",
":",
"a",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"a",
",",
"name",
"=",
"\"a\"",
")",
"b",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"b",
",",
"name",
"=",
"\"b\"",
")",
"a_axes",
",",
"b_axes",
"=",
"_tensordot_axes",
"(",
"a",
",",
"axes",
")",
"a_reshape",
",",
"a_free_dims",
",",
"a_free_dims_static",
"=",
"_tensordot_reshape",
"(",
"a",
",",
"a_axes",
")",
"b_reshape",
",",
"b_free_dims",
",",
"b_free_dims_static",
"=",
"_tensordot_reshape",
"(",
"b",
",",
"b_axes",
",",
"True",
")",
"ab_matmul",
"=",
"matmul",
"(",
"a_reshape",
",",
"b_reshape",
")",
"if",
"isinstance",
"(",
"a_free_dims",
",",
"list",
")",
"and",
"isinstance",
"(",
"b_free_dims",
",",
"list",
")",
":",
"if",
"(",
"ab_matmul",
".",
"get_shape",
"(",
")",
".",
"is_fully_defined",
"(",
")",
"and",
"ab_matmul",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"==",
"a_free_dims",
"+",
"b_free_dims",
")",
":",
"return",
"ab_matmul",
"else",
":",
"return",
"array_ops",
".",
"reshape",
"(",
"ab_matmul",
",",
"a_free_dims",
"+",
"b_free_dims",
",",
"name",
"=",
"name",
")",
"else",
":",
"a_free_dims",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"a_free_dims",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"b_free_dims",
"=",
"ops",
".",
"convert_to_tensor",
"(",
"b_free_dims",
",",
"dtype",
"=",
"dtypes",
".",
"int32",
")",
"product",
"=",
"array_ops",
".",
"reshape",
"(",
"ab_matmul",
",",
"array_ops",
".",
"concat",
"(",
"[",
"a_free_dims",
",",
"b_free_dims",
"]",
",",
"0",
")",
",",
"name",
"=",
"name",
")",
"if",
"a_free_dims_static",
"is",
"not",
"None",
"and",
"b_free_dims_static",
"is",
"not",
"None",
":",
"product",
".",
"set_shape",
"(",
"a_free_dims_static",
"+",
"b_free_dims_static",
")",
"return",
"product"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_ops.py#L4962-L5139 | ||
gamedev-net/nehe-opengl | 9f073e5b092ad8dbcb21393871a2855fe86a65c6 | python/lesson44/ztv121/glCamera.py | python | glCamera.PointInFrustum | (self, x,y,z) | return(True) | // This member fuction checks to see if a point is in
// the viewing volume. | // This member fuction checks to see if a point is in
// the viewing volume. | [
"//",
"This",
"member",
"fuction",
"checks",
"to",
"see",
"if",
"a",
"point",
"is",
"in",
"//",
"the",
"viewing",
"volume",
"."
] | def PointInFrustum(self, x,y,z):
""" // This member fuction checks to see if a point is in
// the viewing volume. """
# // The idea behind this algorithum is that if the point
# // is inside all 6 clipping planes then it is inside our
# // viewing volume so we can return true.
Frustum = self.m_Frustum
# // Loop through all our clipping planes
for i in xrange (6):
# // If the point is outside of the plane then its not in the viewing volume.
if(Frustum[i][0] * x + Frustum[i][1] * y + Frustum[i][2] * z + Frustum[i][3] <= 0):
return(False);
return(True); | [
"def",
"PointInFrustum",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"# // The idea behind this algorithum is that if the point",
"# // is inside all 6 clipping planes then it is inside our",
"# // viewing volume so we can return true.",
"Frustum",
"=",
"self",
".",
"m_Frustum",
"# // Loop through all our clipping planes",
"for",
"i",
"in",
"xrange",
"(",
"6",
")",
":",
"# // If the point is outside of the plane then its not in the viewing volume.",
"if",
"(",
"Frustum",
"[",
"i",
"]",
"[",
"0",
"]",
"*",
"x",
"+",
"Frustum",
"[",
"i",
"]",
"[",
"1",
"]",
"*",
"y",
"+",
"Frustum",
"[",
"i",
"]",
"[",
"2",
"]",
"*",
"z",
"+",
"Frustum",
"[",
"i",
"]",
"[",
"3",
"]",
"<=",
"0",
")",
":",
"return",
"(",
"False",
")",
"return",
"(",
"True",
")"
] | https://github.com/gamedev-net/nehe-opengl/blob/9f073e5b092ad8dbcb21393871a2855fe86a65c6/python/lesson44/ztv121/glCamera.py#L452-L467 | |
microsoft/DirectXShaderCompiler | 8348ff8d9e0287610ba05d3a828e10af981a1c05 | utils/hct/hctdb.py | python | db_dxil.add_enum_type | (self, name, doc, valNameDocTuples) | Adds a new enumeration type with name/value/doc tuples | Adds a new enumeration type with name/value/doc tuples | [
"Adds",
"a",
"new",
"enumeration",
"type",
"with",
"name",
"/",
"value",
"/",
"doc",
"tuples"
] | def add_enum_type(self, name, doc, valNameDocTuples):
"Adds a new enumeration type with name/value/doc tuples"
self.enums.append(db_dxil_enum(name, doc, valNameDocTuples)) | [
"def",
"add_enum_type",
"(",
"self",
",",
"name",
",",
"doc",
",",
"valNameDocTuples",
")",
":",
"self",
".",
"enums",
".",
"append",
"(",
"db_dxil_enum",
"(",
"name",
",",
"doc",
",",
"valNameDocTuples",
")",
")"
] | https://github.com/microsoft/DirectXShaderCompiler/blob/8348ff8d9e0287610ba05d3a828e10af981a1c05/utils/hct/hctdb.py#L199-L201 | ||
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py | python | TokenKind.from_value | (value) | return result | Obtain a registered TokenKind instance from its value. | Obtain a registered TokenKind instance from its value. | [
"Obtain",
"a",
"registered",
"TokenKind",
"instance",
"from",
"its",
"value",
"."
] | def from_value(value):
"""Obtain a registered TokenKind instance from its value."""
result = TokenKind._value_map.get(value, None)
if result is None:
raise ValueError('Unknown TokenKind: %d' % value)
return result | [
"def",
"from_value",
"(",
"value",
")",
":",
"result",
"=",
"TokenKind",
".",
"_value_map",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"result",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown TokenKind: %d'",
"%",
"value",
")",
"return",
"result"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L517-L524 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/vecutil.py | python | matadd | (matrix1, matrix2, fac1=1.0, fac2=1.0) | return new_matrix | Matrix addition | Matrix addition | [
"Matrix",
"addition"
] | def matadd(matrix1, matrix2, fac1=1.0, fac2=1.0):
"""Matrix addition"""
if (len(matrix1[0]) != len(matrix2[0])) or (len(matrix1) != len(matrix2)):
raise ValidationError('Matrices must be same dimension to add.')
new_matrix = zero(len(matrix1), len(matrix1[0]))
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
new_matrix[i][j] = fac1 * matrix1[i][j] + fac2 * matrix2[i][j]
return new_matrix | [
"def",
"matadd",
"(",
"matrix1",
",",
"matrix2",
",",
"fac1",
"=",
"1.0",
",",
"fac2",
"=",
"1.0",
")",
":",
"if",
"(",
"len",
"(",
"matrix1",
"[",
"0",
"]",
")",
"!=",
"len",
"(",
"matrix2",
"[",
"0",
"]",
")",
")",
"or",
"(",
"len",
"(",
"matrix1",
")",
"!=",
"len",
"(",
"matrix2",
")",
")",
":",
"raise",
"ValidationError",
"(",
"'Matrices must be same dimension to add.'",
")",
"new_matrix",
"=",
"zero",
"(",
"len",
"(",
"matrix1",
")",
",",
"len",
"(",
"matrix1",
"[",
"0",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"matrix1",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"matrix1",
"[",
"0",
"]",
")",
")",
":",
"new_matrix",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"fac1",
"*",
"matrix1",
"[",
"i",
"]",
"[",
"j",
"]",
"+",
"fac2",
"*",
"matrix2",
"[",
"i",
"]",
"[",
"j",
"]",
"return",
"new_matrix"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/vecutil.py#L339-L347 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/_tf_utils.py | python | convert_shared_float_array_to_numpy | (array) | return np.array(array, copy=False, dtype=np.float32) | The initialization from C++ implementation is mapped to SharedFloatArray
in Python through Pybind. It must be converted to numpy arrays to be used
in TensorFlow.
Parameters
----------
array: SharedFloatArray
Returns
-------
return: Numpy Array
SharedFloatArray casted as Numpy Array | The initialization from C++ implementation is mapped to SharedFloatArray
in Python through Pybind. It must be converted to numpy arrays to be used
in TensorFlow. | [
"The",
"initialization",
"from",
"C",
"++",
"implementation",
"is",
"mapped",
"to",
"SharedFloatArray",
"in",
"Python",
"through",
"Pybind",
".",
"It",
"must",
"be",
"converted",
"to",
"numpy",
"arrays",
"to",
"be",
"used",
"in",
"TensorFlow",
"."
] | def convert_shared_float_array_to_numpy(array):
"""
The initialization from C++ implementation is mapped to SharedFloatArray
in Python through Pybind. It must be converted to numpy arrays to be used
in TensorFlow.
Parameters
----------
array: SharedFloatArray
Returns
-------
return: Numpy Array
SharedFloatArray casted as Numpy Array
"""
return np.array(array, copy=False, dtype=np.float32) | [
"def",
"convert_shared_float_array_to_numpy",
"(",
"array",
")",
":",
"return",
"np",
".",
"array",
"(",
"array",
",",
"copy",
"=",
"False",
",",
"dtype",
"=",
"np",
".",
"float32",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/_tf_utils.py#L79-L95 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/traitlets/py2/traitlets/traitlets.py | python | UseEnum.select_by_name | (self, value, default=Undefined) | return self.enum_class.__members__.get(value, default) | Selects enum-value by using its name or scoped-name. | Selects enum-value by using its name or scoped-name. | [
"Selects",
"enum",
"-",
"value",
"by",
"using",
"its",
"name",
"or",
"scoped",
"-",
"name",
"."
] | def select_by_name(self, value, default=Undefined):
"""Selects enum-value by using its name or scoped-name."""
assert isinstance(value, six.string_types)
if value.startswith(self.name_prefix):
# -- SUPPORT SCOPED-NAMES, like: "Color.red" => "red"
value = value.replace(self.name_prefix, "", 1)
return self.enum_class.__members__.get(value, default) | [
"def",
"select_by_name",
"(",
"self",
",",
"value",
",",
"default",
"=",
"Undefined",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
"if",
"value",
".",
"startswith",
"(",
"self",
".",
"name_prefix",
")",
":",
"# -- SUPPORT SCOPED-NAMES, like: \"Color.red\" => \"red\"",
"value",
"=",
"value",
".",
"replace",
"(",
"self",
".",
"name_prefix",
",",
"\"\"",
",",
"1",
")",
"return",
"self",
".",
"enum_class",
".",
"__members__",
".",
"get",
"(",
"value",
",",
"default",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/traitlets.py#L2657-L2663 | |
BDLDev/bdlauncher | d10fb098852ebcf9fb71afb23052a463ee7b5d0a | scripts/cppheaderparser.py | python | CppUnion.__str__ | (self) | return rtn | Convert class to a string | Convert class to a string | [
"Convert",
"class",
"to",
"a",
"string"
] | def __str__(self):
"""Convert class to a string"""
namespace_prefix = ""
if self["namespace"]: namespace_prefix = self["namespace"] + "::"
rtn = "%s %s"%(self["declaration_method"], namespace_prefix + self["name"])
if self['abstract']: rtn += ' (abstract)\n'
else: rtn += '\n'
if 'doxygen' in list(self.keys()): rtn += self["doxygen"] + '\n'
if 'parent' in list(self.keys()) and self['parent']: rtn += 'parent class: ' + self['parent'] + '\n'
rtn += "{\n"
for member in self["members"]:
rtn += " %s\n"%(repr(member))
rtn += "}\n"
return rtn | [
"def",
"__str__",
"(",
"self",
")",
":",
"namespace_prefix",
"=",
"\"\"",
"if",
"self",
"[",
"\"namespace\"",
"]",
":",
"namespace_prefix",
"=",
"self",
"[",
"\"namespace\"",
"]",
"+",
"\"::\"",
"rtn",
"=",
"\"%s %s\"",
"%",
"(",
"self",
"[",
"\"declaration_method\"",
"]",
",",
"namespace_prefix",
"+",
"self",
"[",
"\"name\"",
"]",
")",
"if",
"self",
"[",
"'abstract'",
"]",
":",
"rtn",
"+=",
"' (abstract)\\n'",
"else",
":",
"rtn",
"+=",
"'\\n'",
"if",
"'doxygen'",
"in",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
":",
"rtn",
"+=",
"self",
"[",
"\"doxygen\"",
"]",
"+",
"'\\n'",
"if",
"'parent'",
"in",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
"and",
"self",
"[",
"'parent'",
"]",
":",
"rtn",
"+=",
"'parent class: '",
"+",
"self",
"[",
"'parent'",
"]",
"+",
"'\\n'",
"rtn",
"+=",
"\"{\\n\"",
"for",
"member",
"in",
"self",
"[",
"\"members\"",
"]",
":",
"rtn",
"+=",
"\" %s\\n\"",
"%",
"(",
"repr",
"(",
"member",
")",
")",
"rtn",
"+=",
"\"}\\n\"",
"return",
"rtn"
] | https://github.com/BDLDev/bdlauncher/blob/d10fb098852ebcf9fb71afb23052a463ee7b5d0a/scripts/cppheaderparser.py#L694-L709 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/exceptions.py | python | RequestException.__init__ | (self, *args, **kwargs) | Initialize RequestException with `request` and `response` objects. | Initialize RequestException with `request` and `response` objects. | [
"Initialize",
"RequestException",
"with",
"request",
"and",
"response",
"objects",
"."
] | def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(RequestException, self).__init__(*args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"kwargs",
".",
"pop",
"(",
"'response'",
",",
"None",
")",
"self",
".",
"response",
"=",
"response",
"self",
".",
"request",
"=",
"kwargs",
".",
"pop",
"(",
"'request'",
",",
"None",
")",
"if",
"(",
"response",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"request",
"and",
"hasattr",
"(",
"response",
",",
"'request'",
")",
")",
":",
"self",
".",
"request",
"=",
"self",
".",
"response",
".",
"request",
"super",
"(",
"RequestException",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/exceptions.py#L17-L25 | ||
xiaolonw/caffe-video_triplet | c39ea1ad6e937ccf7deba4510b7e555165abf05f | 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/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/scripts/cpp_lint.py#L3405-L3434 | ||
strukturag/libheif | 0082fea96ee70a20c8906a0373bedec0c01777bc | scripts/cpplint.py | python | FileInfo.Extension | (self) | return self.Split()[2] | File extension - text following the final period. | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period",
"."
] | def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2] | [
"def",
"Extension",
"(",
"self",
")",
":",
"return",
"self",
".",
"Split",
"(",
")",
"[",
"2",
"]"
] | https://github.com/strukturag/libheif/blob/0082fea96ee70a20c8906a0373bedec0c01777bc/scripts/cpplint.py#L1128-L1130 | |
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/largest-rectangle-in-histogram.py | python | Solution.largestRectangleArea | (self, heights) | return result | :type heights: List[int]
:rtype: int | :type heights: List[int]
:rtype: int | [
":",
"type",
"heights",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
stk, result = [-1], 0
for i in xrange(len(heights)+1):
while stk[-1] != -1 and (i == len(heights) or heights[stk[-1]] >= heights[i]):
result = max(result, heights[stk.pop()]*((i-1)-stk[-1]))
stk.append(i)
return result | [
"def",
"largestRectangleArea",
"(",
"self",
",",
"heights",
")",
":",
"stk",
",",
"result",
"=",
"[",
"-",
"1",
"]",
",",
"0",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"heights",
")",
"+",
"1",
")",
":",
"while",
"stk",
"[",
"-",
"1",
"]",
"!=",
"-",
"1",
"and",
"(",
"i",
"==",
"len",
"(",
"heights",
")",
"or",
"heights",
"[",
"stk",
"[",
"-",
"1",
"]",
"]",
">=",
"heights",
"[",
"i",
"]",
")",
":",
"result",
"=",
"max",
"(",
"result",
",",
"heights",
"[",
"stk",
".",
"pop",
"(",
")",
"]",
"*",
"(",
"(",
"i",
"-",
"1",
")",
"-",
"stk",
"[",
"-",
"1",
"]",
")",
")",
"stk",
".",
"append",
"(",
"i",
")",
"return",
"result"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/largest-rectangle-in-histogram.py#L5-L15 | |
bumptop/BumpTop | 466d23597a07ae738f4265262fa01087fc6e257c | trunk/mac/Build/cpplint.py | python | CheckLanguage | (filename, clean_lines, linenum, file_extension, include_state,
error) | Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Checks rules from the 'C++ language rules' section of cppguide.html. | [
"Checks",
"rules",
"from",
"the",
"C",
"++",
"language",
"rules",
"section",
"of",
"cppguide",
".",
"html",
"."
] | def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
# get rid of comments
comment_elided_line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
if _RE_PATTERN_INCLUDE_NEW_STYLE.search(comment_elided_line):
error(filename, linenum, 'build/include', 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(comment_elided_line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
if include in include_state:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, include_state[include]))
else:
include_state[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()))
# If the line is empty or consists of entirely a comment, no need to
# check it.
line = clean_lines.elided[linenum]
if not line:
return
# Create an extended_line, which is the concatenation of the current and
# next lines, for more effective checking of code that may span more than one
# line.
if linenum + 1 < clean_lines.NumLines():
extended_line = line + clean_lines.elided[linenum + 1]
else:
extended_line = line
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
# TODO(unknown): figure out if they're using default arguments in fn proto.
# Look for any of the stream classes that are part of standard C++.
match = _RE_PATTERN_INCLUDE.match(line)
if match:
include = match.group(2)
if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
# Many unit tests use cout, so we exempt them.
if not _IsTestFilename(filename):
error(filename, linenum, 'readability/streams', 3,
'Streams are highly discouraged.')
# Check for non-const references in functions. This is tricky because &
# is also used to take the address of something. We allow <> for templates,
# (ignoring whatever is between the braces) and : for classes.
# These are complicated re's. They try to capture the following:
# paren (for fn-prototype start), typename, &, varname. For the const
# version, we're willing for const to be before typename or after
# Don't check the implemention on same line.
fnline = line.split('{', 1)[0]
if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) +
len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+',
fnline))):
# We allow non-const references in a few standard places, like functions
# called "swap()" or iostream operators like "<<" or ">>".
if not Search(
r'(swap|Swap|operator[<>][<>])\s*\(\s*(?:[\w:]|<.*>)+\s*&',
fnline):
error(filename, linenum, 'runtime/references', 2,
'Is this a non-const reference? '
'If so, make const or use a pointer.')
# Check to see if they're using an conversion function cast.
# I just try to capture the most common basic types, though there are more.
# Parameterless conversion functions, such as bool(), are allowed as they are
# probably a member operator declaration or default constructor.
match = Search(
r'\b(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
if match:
# gMock methods are defined using some variant of MOCK_METHODx(name, type)
# where type may be float(), int(string), etc. Without context they are
# virtually indistinguishable from int(x) casts.
if not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line):
error(filename, linenum, 'readability/casting', 4,
'Using deprecated casting style. '
'Use static_cast<%s>(...) instead' %
match.group(1))
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'static_cast',
r'\((int|float|double|bool|char|u?int(16|32|64))\)',
error)
# This doesn't catch all cases. Consider (const char * const)"hello".
CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
# point where you think.
if Search(
r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
error(filename, linenum, 'runtime/casting', 4,
('Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'))
# Check for people declaring static/global STL strings at the top level.
# This is dangerous because the C++ language does not guarantee that
# globals with constructors are initialized before the first access.
match = Match(
r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
line)
# Make sure it's not a function.
# Function template specialization looks like: "string foo<Type>(...".
# Class template definitions look like: "string Foo<Type>::Method(...".
if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
match.group(3)):
error(filename, linenum, 'runtime/string', 4,
'For a static/global string constant, use a C style string instead: '
'"%schar %s[]".' %
(match.group(1), match.group(2)))
# Check that we're not using RTTI outside of testing code.
if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename):
error(filename, linenum, 'runtime/rtti', 5,
'Do not use dynamic_cast<>. If you need to cast within a class '
"hierarchy, use static_cast<> to upcast. Google doesn't support "
'RTTI.')
if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
error(filename, linenum, 'runtime/init', 4,
'You seem to be initializing a member variable with itself.')
if file_extension == 'h':
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
# (level 1 error)
pass
# Check if people are using the verboten C basic types. The only exception
# we regularly allow is "unsigned short port" for port.
if Search(r'\bshort port\b', line):
if not Search(r'\bunsigned short port\b', line):
error(filename, linenum, 'runtime/int', 4,
'Use "unsigned short" for ports, not "short"')
else:
match = Search(r'\b(short|long(?! +double)|long long)\b', line)
if match:
error(filename, linenum, 'runtime/int', 4,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
# When snprintf is used, the second argument shouldn't be a literal.
match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
if match:
error(filename, linenum, 'runtime/printf', 3,
'If you can, use sizeof(%s) instead of %s as the 2nd arg '
'to snprintf.' % (match.group(1), match.group(2)))
# Check if some verboten C functions are being used.
if Search(r'\bsprintf\b', line):
error(filename, linenum, 'runtime/printf', 5,
'Never use sprintf. Use snprintf instead.')
match = Search(r'\b(strcpy|strcat)\b', line)
if match:
error(filename, linenum, 'runtime/printf', 4,
'Almost always, snprintf is better than %s' % match.group(1))
if Search(r'\bsscanf\b', line):
error(filename, linenum, 'runtime/printf', 1,
'sscanf can be ok, but is slow and can overflow buffers.')
# Check for suspicious usage of "if" like
# } if (a == b) {
if Search(r'\}\s*if\s*\(', line):
error(filename, linenum, 'readability/braces', 4,
'Did you mean "else if"? If not, start a new line for "if".')
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
match = re.search(r'\b((?:string)?printf)\s*\(([\w.\->()]+)\)', line, re.I)
if match:
error(filename, linenum, 'runtime/printf', 4,
'Potential format string bug. Do %s("%%s", %s) instead.'
% (match.group(1), match.group(2)))
# Check for potential memset bugs like memset(buf, sizeof(buf), 0).
match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
error(filename, linenum, 'runtime/memset', 4,
'Did you mean "memset(%s, 0, %s)"?'
% (match.group(1), match.group(2)))
if Search(r'\busing namespace\b', line):
error(filename, linenum, 'build/namespaces', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
# Detect variable-length arrays.
match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
match.group(3).find(']') == -1):
# Split the size using space and arithmetic operators as delimiters.
# If any of the resulting tokens are not compile time constants then
# report the error.
tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
is_const = True
skip_next = False
for tok in tokens:
if skip_next:
skip_next = False
continue
if Search(r'sizeof\(.+\)', tok): continue
if Search(r'arraysize\(\w+\)', tok): continue
tok = tok.lstrip('(')
tok = tok.rstrip(')')
if not tok: continue
if Match(r'\d+', tok): continue
if Match(r'0[xX][0-9a-fA-F]+', tok): continue
if Match(r'k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
# A catch all for tricky sizeof cases, including 'sizeof expression',
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
# requires skipping the next token becasue we split on ' ' and '*'.
if tok.startswith('sizeof'):
skip_next = True
continue
is_const = False
break
if not is_const:
error(filename, linenum, 'runtime/arrays', 1,
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
# in the class declaration.
match = Match(
(r'\s*'
r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
r'\(.*\);$'),
line)
if match and linenum + 1 < clean_lines.NumLines():
next_line = clean_lines.elided[linenum + 1]
if not Search(r'^\s*};', next_line):
error(filename, linenum, 'readability/constructors', 3,
match.group(1) + ' should be the last thing in the class')
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
if (file_extension == 'h'
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.') | [
"def",
"CheckLanguage",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"# get rid of comments",
"comment_elided_line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"",
"if",
"_RE_PATTERN_INCLUDE_NEW_STYLE",
".",
"search",
"(",
"comment_elided_line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"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",
"(",
"comment_elided_line",
")",
"if",
"match",
":",
"include",
"=",
"match",
".",
"group",
"(",
"2",
")",
"is_system",
"=",
"(",
"match",
".",
"group",
"(",
"1",
")",
"==",
"'<'",
")",
"if",
"include",
"in",
"include_state",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'\"%s\" already included at %s:%s'",
"%",
"(",
"include",
",",
"filename",
",",
"include_state",
"[",
"include",
"]",
")",
")",
"else",
":",
"include_state",
"[",
"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",
"(",
")",
")",
")",
"# If the line is empty or consists of entirely a comment, no need to",
"# check it.",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"if",
"not",
"line",
":",
"return",
"# Create an extended_line, which is the concatenation of the current and",
"# next lines, for more effective checking of code that may span more than one",
"# line.",
"if",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"extended_line",
"=",
"line",
"+",
"clean_lines",
".",
"elided",
"[",
"linenum",
"+",
"1",
"]",
"else",
":",
"extended_line",
"=",
"line",
"# Make Windows paths like Unix.",
"fullname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"# TODO(unknown): figure out if they're using default arguments in fn proto.",
"# Look for any of the stream classes that are part of standard C++.",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"include",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"Match",
"(",
"r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$'",
",",
"include",
")",
":",
"# Many unit tests use cout, so we exempt them.",
"if",
"not",
"_IsTestFilename",
"(",
"filename",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/streams'",
",",
"3",
",",
"'Streams are highly discouraged.'",
")",
"# Check for non-const references in functions. This is tricky because &",
"# is also used to take the address of something. We allow <> for templates,",
"# (ignoring whatever is between the braces) and : for classes.",
"# These are complicated re's. They try to capture the following:",
"# paren (for fn-prototype start), typename, &, varname. For the const",
"# version, we're willing for const to be before typename or after",
"# Don't check the implemention on same line.",
"fnline",
"=",
"line",
".",
"split",
"(",
"'{'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"(",
"len",
"(",
"re",
".",
"findall",
"(",
"r'\\([^()]*\\b(?:[\\w:]|<[^()]*>)+(\\s?&|&\\s?)\\w+'",
",",
"fnline",
")",
")",
">",
"len",
"(",
"re",
".",
"findall",
"(",
"r'\\([^()]*\\bconst\\s+(?:typename\\s+)?(?:struct\\s+)?'",
"r'(?:[\\w:]|<[^()]*>)+(\\s?&|&\\s?)\\w+'",
",",
"fnline",
")",
")",
"+",
"len",
"(",
"re",
".",
"findall",
"(",
"r'\\([^()]*\\b(?:[\\w:]|<[^()]*>)+\\s+const(\\s?&|&\\s?)[\\w]+'",
",",
"fnline",
")",
")",
")",
":",
"# We allow non-const references in a few standard places, like functions",
"# called \"swap()\" or iostream operators like \"<<\" or \">>\".",
"if",
"not",
"Search",
"(",
"r'(swap|Swap|operator[<>][<>])\\s*\\(\\s*(?:[\\w:]|<.*>)+\\s*&'",
",",
"fnline",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/references'",
",",
"2",
",",
"'Is this a non-const reference? '",
"'If so, make const or use a pointer.'",
")",
"# Check to see if they're using an conversion function cast.",
"# I just try to capture the most common basic types, though there are more.",
"# Parameterless conversion functions, such as bool(), are allowed as they are",
"# probably a member operator declaration or default constructor.",
"match",
"=",
"Search",
"(",
"r'\\b(int|float|double|bool|char|int32|uint32|int64|uint64)\\([^)]'",
",",
"line",
")",
"if",
"match",
":",
"# gMock methods are defined using some variant of MOCK_METHODx(name, type)",
"# where type may be float(), int(string), etc. Without context they are",
"# virtually indistinguishable from int(x) casts.",
"if",
"not",
"Match",
"(",
"r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/casting'",
",",
"4",
",",
"'Using deprecated casting style. '",
"'Use static_cast<%s>(...) instead'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'static_cast'",
",",
"r'\\((int|float|double|bool|char|u?int(16|32|64))\\)'",
",",
"error",
")",
"# This doesn't catch all cases. Consider (const char * const)\"hello\".",
"CheckCStyleCast",
"(",
"filename",
",",
"linenum",
",",
"line",
",",
"clean_lines",
".",
"raw_lines",
"[",
"linenum",
"]",
",",
"'reinterpret_cast'",
",",
"r'\\((\\w+\\s?\\*+\\s?)\\)'",
",",
"error",
")",
"# In addition, we look for people taking the address of a cast. This",
"# is dangerous -- casts can assign to temporaries, so the pointer doesn't",
"# point where you think.",
"if",
"Search",
"(",
"r'(&\\([^)]+\\)[\\w(])|(&(static|dynamic|reinterpret)_cast\\b)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/casting'",
",",
"4",
",",
"(",
"'Are you taking an address of a cast? '",
"'This is dangerous: could be a temp var. '",
"'Take the address before doing the cast, rather than after'",
")",
")",
"# Check for people declaring static/global STL strings at the top level.",
"# This is dangerous because the C++ language does not guarantee that",
"# globals with constructors are initialized before the first access.",
"match",
"=",
"Match",
"(",
"r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\\b(.*)'",
",",
"line",
")",
"# Make sure it's not a function.",
"# Function template specialization looks like: \"string foo<Type>(...\".",
"# Class template definitions look like: \"string Foo<Type>::Method(...\".",
"if",
"match",
"and",
"not",
"Match",
"(",
"r'\\s*(<.*>)?(::[a-zA-Z0-9_]+)?\\s*\\(([^\"]|$)'",
",",
"match",
".",
"group",
"(",
"3",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/string'",
",",
"4",
",",
"'For a static/global string constant, use a C style string instead: '",
"'\"%schar %s[]\".'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"# Check that we're not using RTTI outside of testing code.",
"if",
"Search",
"(",
"r'\\bdynamic_cast<'",
",",
"line",
")",
"and",
"not",
"_IsTestFilename",
"(",
"filename",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/rtti'",
",",
"5",
",",
"'Do not use dynamic_cast<>. If you need to cast within a class '",
"\"hierarchy, use static_cast<> to upcast. Google doesn't support \"",
"'RTTI.'",
")",
"if",
"Search",
"(",
"r'\\b([A-Za-z0-9_]*_)\\(\\1\\)'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/init'",
",",
"4",
",",
"'You seem to be initializing a member variable with itself.'",
")",
"if",
"file_extension",
"==",
"'h'",
":",
"# TODO(unknown): check that 1-arg constructors are explicit.",
"# How to tell it's a constructor?",
"# (handled in CheckForNonStandardConstructs for now)",
"# TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS",
"# (level 1 error)",
"pass",
"# Check if people are using the verboten C basic types. The only exception",
"# we regularly allow is \"unsigned short port\" for port.",
"if",
"Search",
"(",
"r'\\bshort port\\b'",
",",
"line",
")",
":",
"if",
"not",
"Search",
"(",
"r'\\bunsigned short port\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/int'",
",",
"4",
",",
"'Use \"unsigned short\" for ports, not \"short\"'",
")",
"else",
":",
"match",
"=",
"Search",
"(",
"r'\\b(short|long(?! +double)|long long)\\b'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/int'",
",",
"4",
",",
"'Use int16/int64/etc, rather than the C type %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"# When snprintf is used, the second argument shouldn't be a literal.",
"match",
"=",
"Search",
"(",
"r'snprintf\\s*\\(([^,]*),\\s*([0-9]*)\\s*,'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"3",
",",
"'If you can, use sizeof(%s) instead of %s as the 2nd arg '",
"'to snprintf.'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"# Check if some verboten C functions are being used.",
"if",
"Search",
"(",
"r'\\bsprintf\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"5",
",",
"'Never use sprintf. Use snprintf instead.'",
")",
"match",
"=",
"Search",
"(",
"r'\\b(strcpy|strcat)\\b'",
",",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"4",
",",
"'Almost always, snprintf is better than %s'",
"%",
"match",
".",
"group",
"(",
"1",
")",
")",
"if",
"Search",
"(",
"r'\\bsscanf\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"1",
",",
"'sscanf can be ok, but is slow and can overflow buffers.'",
")",
"# Check for suspicious usage of \"if\" like",
"# } if (a == b) {",
"if",
"Search",
"(",
"r'\\}\\s*if\\s*\\('",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/braces'",
",",
"4",
",",
"'Did you mean \"else if\"? If not, start a new line for \"if\".'",
")",
"# Check for potential format string bugs like printf(foo).",
"# We constrain the pattern not to pick things like DocidForPrintf(foo).",
"# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())",
"match",
"=",
"re",
".",
"search",
"(",
"r'\\b((?:string)?printf)\\s*\\(([\\w.\\->()]+)\\)'",
",",
"line",
",",
"re",
".",
"I",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/printf'",
",",
"4",
",",
"'Potential format string bug. Do %s(\"%%s\", %s) instead.'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"# Check for potential memset bugs like memset(buf, sizeof(buf), 0).",
"match",
"=",
"Search",
"(",
"r'memset\\s*\\(([^,]*),\\s*([^,]*),\\s*0\\s*\\)'",
",",
"line",
")",
"if",
"match",
"and",
"not",
"Match",
"(",
"r\"^''|-?[0-9]+|0x[0-9A-Fa-f]$\"",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/memset'",
",",
"4",
",",
"'Did you mean \"memset(%s, 0, %s)\"?'",
"%",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"if",
"Search",
"(",
"r'\\busing namespace\\b'",
",",
"line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces'",
",",
"5",
",",
"'Do not use namespace using-directives. '",
"'Use using-declarations instead.'",
")",
"# Detect variable-length arrays.",
"match",
"=",
"Match",
"(",
"r'\\s*(.+::)?(\\w+) [a-z]\\w*\\[(.+)];'",
",",
"line",
")",
"if",
"(",
"match",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'return'",
"and",
"match",
".",
"group",
"(",
"2",
")",
"!=",
"'delete'",
"and",
"match",
".",
"group",
"(",
"3",
")",
".",
"find",
"(",
"']'",
")",
"==",
"-",
"1",
")",
":",
"# Split the size using space and arithmetic operators as delimiters.",
"# If any of the resulting tokens are not compile time constants then",
"# report the error.",
"tokens",
"=",
"re",
".",
"split",
"(",
"r'\\s|\\+|\\-|\\*|\\/|<<|>>]'",
",",
"match",
".",
"group",
"(",
"3",
")",
")",
"is_const",
"=",
"True",
"skip_next",
"=",
"False",
"for",
"tok",
"in",
"tokens",
":",
"if",
"skip_next",
":",
"skip_next",
"=",
"False",
"continue",
"if",
"Search",
"(",
"r'sizeof\\(.+\\)'",
",",
"tok",
")",
":",
"continue",
"if",
"Search",
"(",
"r'arraysize\\(\\w+\\)'",
",",
"tok",
")",
":",
"continue",
"tok",
"=",
"tok",
".",
"lstrip",
"(",
"'('",
")",
"tok",
"=",
"tok",
".",
"rstrip",
"(",
"')'",
")",
"if",
"not",
"tok",
":",
"continue",
"if",
"Match",
"(",
"r'\\d+'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'0[xX][0-9a-fA-F]+'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'k[A-Z0-9]\\w*'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'(.+::)?k[A-Z0-9]\\w*'",
",",
"tok",
")",
":",
"continue",
"if",
"Match",
"(",
"r'(.+::)?[A-Z][A-Z0-9_]*'",
",",
"tok",
")",
":",
"continue",
"# A catch all for tricky sizeof cases, including 'sizeof expression',",
"# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'",
"# requires skipping the next token becasue we split on ' ' and '*'.",
"if",
"tok",
".",
"startswith",
"(",
"'sizeof'",
")",
":",
"skip_next",
"=",
"True",
"continue",
"is_const",
"=",
"False",
"break",
"if",
"not",
"is_const",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'runtime/arrays'",
",",
"1",
",",
"'Do not use variable-length arrays. Use an appropriately named '",
"\"('k' followed by CamelCase) compile-time constant for the size.\"",
")",
"# If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or",
"# DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing",
"# in the class declaration.",
"match",
"=",
"Match",
"(",
"(",
"r'\\s*'",
"r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'",
"r'\\(.*\\);$'",
")",
",",
"line",
")",
"if",
"match",
"and",
"linenum",
"+",
"1",
"<",
"clean_lines",
".",
"NumLines",
"(",
")",
":",
"next_line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"+",
"1",
"]",
"if",
"not",
"Search",
"(",
"r'^\\s*};'",
",",
"next_line",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'readability/constructors'",
",",
"3",
",",
"match",
".",
"group",
"(",
"1",
")",
"+",
"' should be the last thing in the class'",
")",
"# Check for use of unnamed namespaces in header files. Registration",
"# macros are typically OK, so we allow use of \"namespace {\" on lines",
"# that end with backslashes.",
"if",
"(",
"file_extension",
"==",
"'h'",
"and",
"Search",
"(",
"r'\\bnamespace\\s*{'",
",",
"line",
")",
"and",
"line",
"[",
"-",
"1",
"]",
"!=",
"'\\\\'",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/namespaces'",
",",
"4",
",",
"'Do not use unnamed namespaces in header files. See '",
"'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'",
"' for more information.'",
")"
] | https://github.com/bumptop/BumpTop/blob/466d23597a07ae738f4265262fa01087fc6e257c/trunk/mac/Build/cpplint.py#L2063-L2362 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typeconv/typeconv.py | python | TypeCastingRules.promote | (self, a, b) | Set `a` can promote to `b` | Set `a` can promote to `b` | [
"Set",
"a",
"can",
"promote",
"to",
"b"
] | def promote(self, a, b):
"""
Set `a` can promote to `b`
"""
self._tg.promote(a, b) | [
"def",
"promote",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"self",
".",
"_tg",
".",
"promote",
"(",
"a",
",",
"b",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/typeconv/typeconv.py#L83-L87 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/idlelib/TreeWidget.py | python | TreeItem.GetSelectedIconName | (self) | Return name of icon to be displayed when selected. | Return name of icon to be displayed when selected. | [
"Return",
"name",
"of",
"icon",
"to",
"be",
"displayed",
"when",
"selected",
"."
] | def GetSelectedIconName(self):
"""Return name of icon to be displayed when selected.""" | [
"def",
"GetSelectedIconName",
"(",
"self",
")",
":"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/idlelib/TreeWidget.py#L353-L354 | ||
wallix/redemption | fb4ceefb39e11e1ae250bce17e878e1dc7d195d2 | tools/conf_migration_tool/conf_migrate.py | python | ConfigurationFile.__is_variable_exist | (self, section_name:Optional[str], variable_name:str) | return False | Retourne False si la variable n'existe pas dans la section, ou si la
section n'existe pas. Sinon retourne True. | Retourne False si la variable n'existe pas dans la section, ou si la
section n'existe pas. Sinon retourne True. | [
"Retourne",
"False",
"si",
"la",
"variable",
"n",
"existe",
"pas",
"dans",
"la",
"section",
"ou",
"si",
"la",
"section",
"n",
"existe",
"pas",
".",
"Sinon",
"retourne",
"True",
"."
] | def __is_variable_exist(self, section_name:Optional[str], variable_name:str) -> bool:
"""
Retourne False si la variable n'existe pas dans la section, ou si la
section n'existe pas. Sinon retourne True.
"""
current_section_name = None
for line in self._content:
if line.is_section_declaration():
current_section_name = line.get_name()
elif line.is_variable_declaration():
assert current_section_name, \
f'Not in a section: "{configuration_file_line}"'
if current_section_name == section_name and \
line.get_name() == variable_name:
return True
return False | [
"def",
"__is_variable_exist",
"(",
"self",
",",
"section_name",
":",
"Optional",
"[",
"str",
"]",
",",
"variable_name",
":",
"str",
")",
"->",
"bool",
":",
"current_section_name",
"=",
"None",
"for",
"line",
"in",
"self",
".",
"_content",
":",
"if",
"line",
".",
"is_section_declaration",
"(",
")",
":",
"current_section_name",
"=",
"line",
".",
"get_name",
"(",
")",
"elif",
"line",
".",
"is_variable_declaration",
"(",
")",
":",
"assert",
"current_section_name",
",",
"f'Not in a section: \"{configuration_file_line}\"'",
"if",
"current_section_name",
"==",
"section_name",
"and",
"line",
".",
"get_name",
"(",
")",
"==",
"variable_name",
":",
"return",
"True",
"return",
"False"
] | https://github.com/wallix/redemption/blob/fb4ceefb39e11e1ae250bce17e878e1dc7d195d2/tools/conf_migration_tool/conf_migrate.py#L348-L366 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/resource_group.py | python | ResourceGroup.create_file | (self, relative_destination_path, initial_content, force=False) | return file_util.create_ignore_filter_function(self.__context, destination_path, initial_content) | Creates a file in a resource group.
Args:
relative_destination_path: the path and name of the file relative to
the resource group directory.
initial_content: The file's initial content.
force (named): Overwrite existing files. Default is False.
Returns:
True if the file was created. | Creates a file in a resource group. | [
"Creates",
"a",
"file",
"in",
"a",
"resource",
"group",
"."
] | def create_file(self, relative_destination_path, initial_content, force=False):
"""Creates a file in a resource group.
Args:
relative_destination_path: the path and name of the file relative to
the resource group directory.
initial_content: The file's initial content.
force (named): Overwrite existing files. Default is False.
Returns:
True if the file was created.
"""
destination_path = os.path.join(self.directory_path, relative_destination_path)
return file_util.create_ignore_filter_function(self.__context, destination_path, initial_content) | [
"def",
"create_file",
"(",
"self",
",",
"relative_destination_path",
",",
"initial_content",
",",
"force",
"=",
"False",
")",
":",
"destination_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"directory_path",
",",
"relative_destination_path",
")",
"return",
"file_util",
".",
"create_ignore_filter_function",
"(",
"self",
".",
"__context",
",",
"destination_path",
",",
"initial_content",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/resource_group.py#L532-L551 | |
crosslife/OpenBird | 9e0198a1a2295f03fa1e8676e216e22c9c7d380b | cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py | python | register_functions | (lib, ignore_errors) | Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library. | Register function prototypes with a libclang library instance. | [
"Register",
"function",
"prototypes",
"with",
"a",
"libclang",
"library",
"instance",
"."
] | def register_functions(lib, ignore_errors):
"""Register function prototypes with a libclang library instance.
This must be called as part of library instantiation so Python knows how
to call out to the shared library.
"""
def register(item):
return register_function(lib, item, ignore_errors)
map(register, functionList) | [
"def",
"register_functions",
"(",
"lib",
",",
"ignore_errors",
")",
":",
"def",
"register",
"(",
"item",
")",
":",
"return",
"register_function",
"(",
"lib",
",",
"item",
",",
"ignore_errors",
")",
"map",
"(",
"register",
",",
"functionList",
")"
] | https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L3121-L3131 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/memory_inspector/memory_inspector/__init__.py | python | _IncludeDeps | () | Imports all the project dependencies. | Imports all the project dependencies. | [
"Imports",
"all",
"the",
"project",
"dependencies",
"."
] | def _IncludeDeps():
"""Imports all the project dependencies."""
chromium_dir = os.path.abspath(os.path.join(ROOT_DIR, os.pardir, os.pardir))
sys.path += [
ROOT_DIR,
# Include all dependencies.
os.path.join(chromium_dir, 'build', 'android'), # For pylib.
] | [
"def",
"_IncludeDeps",
"(",
")",
":",
"chromium_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"ROOT_DIR",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
")",
")",
"sys",
".",
"path",
"+=",
"[",
"ROOT_DIR",
",",
"# Include all dependencies.",
"os",
".",
"path",
".",
"join",
"(",
"chromium_dir",
",",
"'build'",
",",
"'android'",
")",
",",
"# For pylib.",
"]"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/memory_inspector/memory_inspector/__init__.py#L19-L28 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py | python | TarFile.utime | (self, tarinfo, targetpath) | Set modification time of targetpath according to tarinfo. | Set modification time of targetpath according to tarinfo. | [
"Set",
"modification",
"time",
"of",
"targetpath",
"according",
"to",
"tarinfo",
"."
] | def utime(self, tarinfo, targetpath):
"""Set modification time of targetpath according to tarinfo.
"""
if not hasattr(os, 'utime'):
return
try:
os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
except EnvironmentError as e:
raise ExtractError("could not change modification time") | [
"def",
"utime",
"(",
"self",
",",
"tarinfo",
",",
"targetpath",
")",
":",
"if",
"not",
"hasattr",
"(",
"os",
",",
"'utime'",
")",
":",
"return",
"try",
":",
"os",
".",
"utime",
"(",
"targetpath",
",",
"(",
"tarinfo",
".",
"mtime",
",",
"tarinfo",
".",
"mtime",
")",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"raise",
"ExtractError",
"(",
"\"could not change modification time\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2403-L2411 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Rect.GetY | (*args, **kwargs) | return _core_.Rect_GetY(*args, **kwargs) | GetY(self) -> int | GetY(self) -> int | [
"GetY",
"(",
"self",
")",
"-",
">",
"int"
] | def GetY(*args, **kwargs):
"""GetY(self) -> int"""
return _core_.Rect_GetY(*args, **kwargs) | [
"def",
"GetY",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect_GetY",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1277-L1279 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/contrib/tensor_forest/data/data_ops.py | python | ParseDataTensorOrDict | (data) | Return a tensor to use for input data.
The incoming features can be a dict where keys are the string names of the
columns, which we turn into a single 2-D tensor.
Args:
data: `Tensor` or `dict` of `Tensor` objects.
Returns:
A 2-D tensor for input to tensor_forest, a keys tensor for the
tf.Examples if they exist, and a list of the type of each column
(e.g. continuous float, categorical). | Return a tensor to use for input data. | [
"Return",
"a",
"tensor",
"to",
"use",
"for",
"input",
"data",
"."
] | def ParseDataTensorOrDict(data):
"""Return a tensor to use for input data.
The incoming features can be a dict where keys are the string names of the
columns, which we turn into a single 2-D tensor.
Args:
data: `Tensor` or `dict` of `Tensor` objects.
Returns:
A 2-D tensor for input to tensor_forest, a keys tensor for the
tf.Examples if they exist, and a list of the type of each column
(e.g. continuous float, categorical).
"""
if isinstance(data, dict):
# If there's at least one sparse tensor, everything has to be sparse.
is_sparse = False
for v in data.values():
if isinstance(v, ops.SparseTensor):
is_sparse = True
break
if is_sparse:
return _ParseSparse(data)
else:
return _ParseDense(data)
else:
return (data, None, None,
[constants.DATA_FLOAT] * data.get_shape().as_list()[1]) | [
"def",
"ParseDataTensorOrDict",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"# If there's at least one sparse tensor, everything has to be sparse.",
"is_sparse",
"=",
"False",
"for",
"v",
"in",
"data",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"ops",
".",
"SparseTensor",
")",
":",
"is_sparse",
"=",
"True",
"break",
"if",
"is_sparse",
":",
"return",
"_ParseSparse",
"(",
"data",
")",
"else",
":",
"return",
"_ParseDense",
"(",
"data",
")",
"else",
":",
"return",
"(",
"data",
",",
"None",
",",
"None",
",",
"[",
"constants",
".",
"DATA_FLOAT",
"]",
"*",
"data",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
"]",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/tensor_forest/data/data_ops.py#L164-L191 | ||
openvinotoolkit/openvino | dedcbeafa8b84cccdc55ca64b8da516682b381c7 | src/bindings/python/src/openvino/runtime/opset3/ops.py | python | non_max_suppression | (
boxes: NodeInput,
scores: NodeInput,
max_output_boxes_per_class: Optional[NodeInput] = None,
iou_threshold: Optional[NodeInput] = None,
score_threshold: Optional[NodeInput] = None,
box_encoding: str = "corner",
sort_result_descending: bool = True,
output_type: str = "i64",
name: Optional[str] = None,
) | return _get_node_factory_opset3().create("NonMaxSuppression", inputs, attributes) | Return a node which performs NonMaxSuppression.
@param boxes: Tensor with box coordinates.
@param scores: Tensor with box scores.
@param max_output_boxes_per_class: Tensor Specifying maximum number of boxes
to be selected per class.
@param iou_threshold: Tensor specifying intersection over union threshold
@param score_threshold: Tensor specifying minimum score to consider box for the processing.
@param box_encoding: Format of boxes data encoding.
@param sort_result_descending: Flag that specifies whenever it is necessary to sort selected
boxes across batches or not.
@param output_type: Output element type.
@return The new node which performs NonMaxSuppression | Return a node which performs NonMaxSuppression. | [
"Return",
"a",
"node",
"which",
"performs",
"NonMaxSuppression",
"."
] | def non_max_suppression(
boxes: NodeInput,
scores: NodeInput,
max_output_boxes_per_class: Optional[NodeInput] = None,
iou_threshold: Optional[NodeInput] = None,
score_threshold: Optional[NodeInput] = None,
box_encoding: str = "corner",
sort_result_descending: bool = True,
output_type: str = "i64",
name: Optional[str] = None,
) -> Node:
"""Return a node which performs NonMaxSuppression.
@param boxes: Tensor with box coordinates.
@param scores: Tensor with box scores.
@param max_output_boxes_per_class: Tensor Specifying maximum number of boxes
to be selected per class.
@param iou_threshold: Tensor specifying intersection over union threshold
@param score_threshold: Tensor specifying minimum score to consider box for the processing.
@param box_encoding: Format of boxes data encoding.
@param sort_result_descending: Flag that specifies whenever it is necessary to sort selected
boxes across batches or not.
@param output_type: Output element type.
@return The new node which performs NonMaxSuppression
"""
if max_output_boxes_per_class is None:
max_output_boxes_per_class = make_constant_node(0, np.int64)
if iou_threshold is None:
iou_threshold = make_constant_node(0, np.float32)
if score_threshold is None:
score_threshold = make_constant_node(0, np.float32)
inputs = as_nodes(boxes, scores, max_output_boxes_per_class, iou_threshold, score_threshold)
attributes = {
"box_encoding": box_encoding,
"sort_result_descending": sort_result_descending,
"output_type": output_type,
}
return _get_node_factory_opset3().create("NonMaxSuppression", inputs, attributes) | [
"def",
"non_max_suppression",
"(",
"boxes",
":",
"NodeInput",
",",
"scores",
":",
"NodeInput",
",",
"max_output_boxes_per_class",
":",
"Optional",
"[",
"NodeInput",
"]",
"=",
"None",
",",
"iou_threshold",
":",
"Optional",
"[",
"NodeInput",
"]",
"=",
"None",
",",
"score_threshold",
":",
"Optional",
"[",
"NodeInput",
"]",
"=",
"None",
",",
"box_encoding",
":",
"str",
"=",
"\"corner\"",
",",
"sort_result_descending",
":",
"bool",
"=",
"True",
",",
"output_type",
":",
"str",
"=",
"\"i64\"",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Node",
":",
"if",
"max_output_boxes_per_class",
"is",
"None",
":",
"max_output_boxes_per_class",
"=",
"make_constant_node",
"(",
"0",
",",
"np",
".",
"int64",
")",
"if",
"iou_threshold",
"is",
"None",
":",
"iou_threshold",
"=",
"make_constant_node",
"(",
"0",
",",
"np",
".",
"float32",
")",
"if",
"score_threshold",
"is",
"None",
":",
"score_threshold",
"=",
"make_constant_node",
"(",
"0",
",",
"np",
".",
"float32",
")",
"inputs",
"=",
"as_nodes",
"(",
"boxes",
",",
"scores",
",",
"max_output_boxes_per_class",
",",
"iou_threshold",
",",
"score_threshold",
")",
"attributes",
"=",
"{",
"\"box_encoding\"",
":",
"box_encoding",
",",
"\"sort_result_descending\"",
":",
"sort_result_descending",
",",
"\"output_type\"",
":",
"output_type",
",",
"}",
"return",
"_get_node_factory_opset3",
"(",
")",
".",
"create",
"(",
"\"NonMaxSuppression\"",
",",
"inputs",
",",
"attributes",
")"
] | https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset3/ops.py#L313-L352 | |
gzc/CLRS | b7d3df5ba834b2a15007d0f0fc320f1dfc9f4041 | C33-Computational-Geometry/Graham_Scan.py | python | Point.polar_sort | (cls, p0, *P) | return sorted(point_and_angle, key = lambda p_tuple: p_tuple[1]) | Sort a sequence <p1, p2, ..., pN> of n points according to their polar
angles w.r.t a given original point p0. Time Complexity: O(n log(n))
:param p0: The reference point.
:param P: A sorted sequence of tuple of Point object and its angle.
Sorting is done by angle. | Sort a sequence <p1, p2, ..., pN> of n points according to their polar
angles w.r.t a given original point p0. Time Complexity: O(n log(n))
:param p0: The reference point.
:param P: A sorted sequence of tuple of Point object and its angle.
Sorting is done by angle. | [
"Sort",
"a",
"sequence",
"<p1",
"p2",
"...",
"pN",
">",
"of",
"n",
"points",
"according",
"to",
"their",
"polar",
"angles",
"w",
".",
"r",
".",
"t",
"a",
"given",
"original",
"point",
"p0",
".",
"Time",
"Complexity",
":",
"O",
"(",
"n",
"log",
"(",
"n",
"))",
":",
"param",
"p0",
":",
"The",
"reference",
"point",
".",
":",
"param",
"P",
":",
"A",
"sorted",
"sequence",
"of",
"tuple",
"of",
"Point",
"object",
"and",
"its",
"angle",
".",
"Sorting",
"is",
"done",
"by",
"angle",
"."
] | def polar_sort(cls, p0, *P):
"""
Sort a sequence <p1, p2, ..., pN> of n points according to their polar
angles w.r.t a given original point p0. Time Complexity: O(n log(n))
:param p0: The reference point.
:param P: A sorted sequence of tuple of Point object and its angle.
Sorting is done by angle.
"""
point_and_angle = map(lambda p: (p, cls.angle(p, p0)), P)
return sorted(point_and_angle, key = lambda p_tuple: p_tuple[1]) | [
"def",
"polar_sort",
"(",
"cls",
",",
"p0",
",",
"*",
"P",
")",
":",
"point_and_angle",
"=",
"map",
"(",
"lambda",
"p",
":",
"(",
"p",
",",
"cls",
".",
"angle",
"(",
"p",
",",
"p0",
")",
")",
",",
"P",
")",
"return",
"sorted",
"(",
"point_and_angle",
",",
"key",
"=",
"lambda",
"p_tuple",
":",
"p_tuple",
"[",
"1",
"]",
")"
] | https://github.com/gzc/CLRS/blob/b7d3df5ba834b2a15007d0f0fc320f1dfc9f4041/C33-Computational-Geometry/Graham_Scan.py#L81-L90 | |
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/nyan/nyan_structs.py | python | NyanMember.get_name | (self) | return self.name | Returns the name of the member. | Returns the name of the member. | [
"Returns",
"the",
"name",
"of",
"the",
"member",
"."
] | def get_name(self):
"""
Returns the name of the member.
"""
return self.name | [
"def",
"get_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"name"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/nyan/nyan_structs.py#L882-L886 | |
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/loader/file_image.py | python | FileImageLoaderBase.get_image_data | (self, key) | Loads data from image and normalizes it.
Returns:
:class:`numpy.ndarrayarray`: if there was one image in the file.
tuple: `(data, labels)` if there were many images in the file | Loads data from image and normalizes it. | [
"Loads",
"data",
"from",
"image",
"and",
"normalizes",
"it",
"."
] | def get_image_data(self, key):
"""
Loads data from image and normalizes it.
Returns:
:class:`numpy.ndarrayarray`: if there was one image in the file.
tuple: `(data, labels)` if there were many images in the file
"""
try:
with open(key, "rb") as fin:
img = Image.open(fin)
if img.mode in ("P", "CMYK"):
return numpy.array(img.convert("RGB"),
dtype=self.source_dtype)
else:
return numpy.array(img, dtype=self.source_dtype)
except (TypeError, KeyboardInterrupt) as e:
raise from_none(e)
except Exception as e:
self.warning("Failed to read %s with PIL: %s", key, e)
img = cv2.imread(key)
if img is None:
raise error.BadFormatError("Unable to read %s" % key)
return img.astype(self.source_dtype) | [
"def",
"get_image_data",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"with",
"open",
"(",
"key",
",",
"\"rb\"",
")",
"as",
"fin",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"fin",
")",
"if",
"img",
".",
"mode",
"in",
"(",
"\"P\"",
",",
"\"CMYK\"",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"img",
".",
"convert",
"(",
"\"RGB\"",
")",
",",
"dtype",
"=",
"self",
".",
"source_dtype",
")",
"else",
":",
"return",
"numpy",
".",
"array",
"(",
"img",
",",
"dtype",
"=",
"self",
".",
"source_dtype",
")",
"except",
"(",
"TypeError",
",",
"KeyboardInterrupt",
")",
"as",
"e",
":",
"raise",
"from_none",
"(",
"e",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"warning",
"(",
"\"Failed to read %s with PIL: %s\"",
",",
"key",
",",
"e",
")",
"img",
"=",
"cv2",
".",
"imread",
"(",
"key",
")",
"if",
"img",
"is",
"None",
":",
"raise",
"error",
".",
"BadFormatError",
"(",
"\"Unable to read %s\"",
"%",
"key",
")",
"return",
"img",
".",
"astype",
"(",
"self",
".",
"source_dtype",
")"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/loader/file_image.py#L82-L105 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py | python | Differ._fancy_replace | (self, a, alo, ahi, b, blo, bhi) | r"""
When replacing one block of lines with another, search the blocks
for *similar* lines; the best-matching pair (if any) is used as a
synch point, and intraline difference marking is done on the
similar pair. Lots of work, but often worth it.
Example:
>>> d = Differ()
>>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
... ['abcdefGhijkl\n'], 0, 1)
>>> print(''.join(results), end="")
- abcDefghiJkl
? ^ ^ ^
+ abcdefGhijkl
? ^ ^ ^ | r"""
When replacing one block of lines with another, search the blocks
for *similar* lines; the best-matching pair (if any) is used as a
synch point, and intraline difference marking is done on the
similar pair. Lots of work, but often worth it. | [
"r",
"When",
"replacing",
"one",
"block",
"of",
"lines",
"with",
"another",
"search",
"the",
"blocks",
"for",
"*",
"similar",
"*",
"lines",
";",
"the",
"best",
"-",
"matching",
"pair",
"(",
"if",
"any",
")",
"is",
"used",
"as",
"a",
"synch",
"point",
"and",
"intraline",
"difference",
"marking",
"is",
"done",
"on",
"the",
"similar",
"pair",
".",
"Lots",
"of",
"work",
"but",
"often",
"worth",
"it",
"."
] | def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
r"""
When replacing one block of lines with another, search the blocks
for *similar* lines; the best-matching pair (if any) is used as a
synch point, and intraline difference marking is done on the
similar pair. Lots of work, but often worth it.
Example:
>>> d = Differ()
>>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
... ['abcdefGhijkl\n'], 0, 1)
>>> print(''.join(results), end="")
- abcDefghiJkl
? ^ ^ ^
+ abcdefGhijkl
? ^ ^ ^
"""
# don't synch up unless the lines have a similarity score of at
# least cutoff; best_ratio tracks the best score seen so far
best_ratio, cutoff = 0.74, 0.75
cruncher = SequenceMatcher(self.charjunk)
eqi, eqj = None, None # 1st indices of equal lines (if any)
# search for the pair that matches best without being identical
# (identical lines must be junk lines, & we don't want to synch up
# on junk -- unless we have to)
for j in range(blo, bhi):
bj = b[j]
cruncher.set_seq2(bj)
for i in range(alo, ahi):
ai = a[i]
if ai == bj:
if eqi is None:
eqi, eqj = i, j
continue
cruncher.set_seq1(ai)
# computing similarity is expensive, so use the quick
# upper bounds first -- have seen this speed up messy
# compares by a factor of 3.
# note that ratio() is only expensive to compute the first
# time it's called on a sequence pair; the expensive part
# of the computation is cached by cruncher
if cruncher.real_quick_ratio() > best_ratio and \
cruncher.quick_ratio() > best_ratio and \
cruncher.ratio() > best_ratio:
best_ratio, best_i, best_j = cruncher.ratio(), i, j
if best_ratio < cutoff:
# no non-identical "pretty close" pair
if eqi is None:
# no identical pair either -- treat it as a straight replace
yield from self._plain_replace(a, alo, ahi, b, blo, bhi)
return
# no close pair, but an identical pair -- synch up on that
best_i, best_j, best_ratio = eqi, eqj, 1.0
else:
# there's a close pair, so forget the identical pair (if any)
eqi = None
# a[best_i] very similar to b[best_j]; eqi is None iff they're not
# identical
# pump out diffs from before the synch point
yield from self._fancy_helper(a, alo, best_i, b, blo, best_j)
# do intraline marking on the synch pair
aelt, belt = a[best_i], b[best_j]
if eqi is None:
# pump out a '-', '?', '+', '?' quad for the synched lines
atags = btags = ""
cruncher.set_seqs(aelt, belt)
for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
la, lb = ai2 - ai1, bj2 - bj1
if tag == 'replace':
atags += '^' * la
btags += '^' * lb
elif tag == 'delete':
atags += '-' * la
elif tag == 'insert':
btags += '+' * lb
elif tag == 'equal':
atags += ' ' * la
btags += ' ' * lb
else:
raise ValueError('unknown tag %r' % (tag,))
yield from self._qformat(aelt, belt, atags, btags)
else:
# the synch pair is identical
yield ' ' + aelt
# pump out diffs from after the synch point
yield from self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi) | [
"def",
"_fancy_replace",
"(",
"self",
",",
"a",
",",
"alo",
",",
"ahi",
",",
"b",
",",
"blo",
",",
"bhi",
")",
":",
"# don't synch up unless the lines have a similarity score of at",
"# least cutoff; best_ratio tracks the best score seen so far",
"best_ratio",
",",
"cutoff",
"=",
"0.74",
",",
"0.75",
"cruncher",
"=",
"SequenceMatcher",
"(",
"self",
".",
"charjunk",
")",
"eqi",
",",
"eqj",
"=",
"None",
",",
"None",
"# 1st indices of equal lines (if any)",
"# search for the pair that matches best without being identical",
"# (identical lines must be junk lines, & we don't want to synch up",
"# on junk -- unless we have to)",
"for",
"j",
"in",
"range",
"(",
"blo",
",",
"bhi",
")",
":",
"bj",
"=",
"b",
"[",
"j",
"]",
"cruncher",
".",
"set_seq2",
"(",
"bj",
")",
"for",
"i",
"in",
"range",
"(",
"alo",
",",
"ahi",
")",
":",
"ai",
"=",
"a",
"[",
"i",
"]",
"if",
"ai",
"==",
"bj",
":",
"if",
"eqi",
"is",
"None",
":",
"eqi",
",",
"eqj",
"=",
"i",
",",
"j",
"continue",
"cruncher",
".",
"set_seq1",
"(",
"ai",
")",
"# computing similarity is expensive, so use the quick",
"# upper bounds first -- have seen this speed up messy",
"# compares by a factor of 3.",
"# note that ratio() is only expensive to compute the first",
"# time it's called on a sequence pair; the expensive part",
"# of the computation is cached by cruncher",
"if",
"cruncher",
".",
"real_quick_ratio",
"(",
")",
">",
"best_ratio",
"and",
"cruncher",
".",
"quick_ratio",
"(",
")",
">",
"best_ratio",
"and",
"cruncher",
".",
"ratio",
"(",
")",
">",
"best_ratio",
":",
"best_ratio",
",",
"best_i",
",",
"best_j",
"=",
"cruncher",
".",
"ratio",
"(",
")",
",",
"i",
",",
"j",
"if",
"best_ratio",
"<",
"cutoff",
":",
"# no non-identical \"pretty close\" pair",
"if",
"eqi",
"is",
"None",
":",
"# no identical pair either -- treat it as a straight replace",
"yield",
"from",
"self",
".",
"_plain_replace",
"(",
"a",
",",
"alo",
",",
"ahi",
",",
"b",
",",
"blo",
",",
"bhi",
")",
"return",
"# no close pair, but an identical pair -- synch up on that",
"best_i",
",",
"best_j",
",",
"best_ratio",
"=",
"eqi",
",",
"eqj",
",",
"1.0",
"else",
":",
"# there's a close pair, so forget the identical pair (if any)",
"eqi",
"=",
"None",
"# a[best_i] very similar to b[best_j]; eqi is None iff they're not",
"# identical",
"# pump out diffs from before the synch point",
"yield",
"from",
"self",
".",
"_fancy_helper",
"(",
"a",
",",
"alo",
",",
"best_i",
",",
"b",
",",
"blo",
",",
"best_j",
")",
"# do intraline marking on the synch pair",
"aelt",
",",
"belt",
"=",
"a",
"[",
"best_i",
"]",
",",
"b",
"[",
"best_j",
"]",
"if",
"eqi",
"is",
"None",
":",
"# pump out a '-', '?', '+', '?' quad for the synched lines",
"atags",
"=",
"btags",
"=",
"\"\"",
"cruncher",
".",
"set_seqs",
"(",
"aelt",
",",
"belt",
")",
"for",
"tag",
",",
"ai1",
",",
"ai2",
",",
"bj1",
",",
"bj2",
"in",
"cruncher",
".",
"get_opcodes",
"(",
")",
":",
"la",
",",
"lb",
"=",
"ai2",
"-",
"ai1",
",",
"bj2",
"-",
"bj1",
"if",
"tag",
"==",
"'replace'",
":",
"atags",
"+=",
"'^'",
"*",
"la",
"btags",
"+=",
"'^'",
"*",
"lb",
"elif",
"tag",
"==",
"'delete'",
":",
"atags",
"+=",
"'-'",
"*",
"la",
"elif",
"tag",
"==",
"'insert'",
":",
"btags",
"+=",
"'+'",
"*",
"lb",
"elif",
"tag",
"==",
"'equal'",
":",
"atags",
"+=",
"' '",
"*",
"la",
"btags",
"+=",
"' '",
"*",
"lb",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown tag %r'",
"%",
"(",
"tag",
",",
")",
")",
"yield",
"from",
"self",
".",
"_qformat",
"(",
"aelt",
",",
"belt",
",",
"atags",
",",
"btags",
")",
"else",
":",
"# the synch pair is identical",
"yield",
"' '",
"+",
"aelt",
"# pump out diffs from after the synch point",
"yield",
"from",
"self",
".",
"_fancy_helper",
"(",
"a",
",",
"best_i",
"+",
"1",
",",
"ahi",
",",
"b",
",",
"best_j",
"+",
"1",
",",
"bhi",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py#L928-L1020 | ||
kamyu104/LeetCode-Solutions | 77605708a927ea3b85aee5a479db733938c7c211 | Python/longest-substring-with-at-most-k-distinct-characters.py | python | Solution.lengthOfLongestSubstringKDistinct | (self, s, k) | return longest | :type s: str
:type k: int
:rtype: int | :type s: str
:type k: int
:rtype: int | [
":",
"type",
"s",
":",
"str",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"int"
] | def lengthOfLongestSubstringKDistinct(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
longest, start, distinct_count, visited = 0, 0, 0, [0 for _ in xrange(256)]
for i, char in enumerate(s):
if visited[ord(char)] == 0:
distinct_count += 1
visited[ord(char)] += 1
while distinct_count > k:
visited[ord(s[start])] -= 1
if visited[ord(s[start])] == 0:
distinct_count -= 1
start += 1
longest = max(longest, i - start + 1)
return longest | [
"def",
"lengthOfLongestSubstringKDistinct",
"(",
"self",
",",
"s",
",",
"k",
")",
":",
"longest",
",",
"start",
",",
"distinct_count",
",",
"visited",
"=",
"0",
",",
"0",
",",
"0",
",",
"[",
"0",
"for",
"_",
"in",
"xrange",
"(",
"256",
")",
"]",
"for",
"i",
",",
"char",
"in",
"enumerate",
"(",
"s",
")",
":",
"if",
"visited",
"[",
"ord",
"(",
"char",
")",
"]",
"==",
"0",
":",
"distinct_count",
"+=",
"1",
"visited",
"[",
"ord",
"(",
"char",
")",
"]",
"+=",
"1",
"while",
"distinct_count",
">",
"k",
":",
"visited",
"[",
"ord",
"(",
"s",
"[",
"start",
"]",
")",
"]",
"-=",
"1",
"if",
"visited",
"[",
"ord",
"(",
"s",
"[",
"start",
"]",
")",
"]",
"==",
"0",
":",
"distinct_count",
"-=",
"1",
"start",
"+=",
"1",
"longest",
"=",
"max",
"(",
"longest",
",",
"i",
"-",
"start",
"+",
"1",
")",
"return",
"longest"
] | https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/longest-substring-with-at-most-k-distinct-characters.py#L5-L22 | |
baidu/bigflow | 449245016c0df7d1252e85581e588bfc60cefad3 | bigflow_python/python/bigflow/pcollection.py | python | PCollection.cogroup | (self, other, *others) | return transforms.cogroup(self, other, *others) | 等同于
:func:`bigflow.transforms.cogroup(self, other, *others)
<bigflow.transforms.cogroup>`,
Args:
other (PCollection): 用于协同分组的PCollection
*others: 更多的PCollection
Returns:
PTable: 分组结果 | 等同于
:func:`bigflow.transforms.cogroup(self, other, *others)
<bigflow.transforms.cogroup>`, | [
"等同于",
":",
"func",
":",
"bigflow",
".",
"transforms",
".",
"cogroup",
"(",
"self",
"other",
"*",
"others",
")",
"<bigflow",
".",
"transforms",
".",
"cogroup",
">"
] | def cogroup(self, other, *others):
"""
等同于
:func:`bigflow.transforms.cogroup(self, other, *others)
<bigflow.transforms.cogroup>`,
Args:
other (PCollection): 用于协同分组的PCollection
*others: 更多的PCollection
Returns:
PTable: 分组结果
"""
return transforms.cogroup(self, other, *others) | [
"def",
"cogroup",
"(",
"self",
",",
"other",
",",
"*",
"others",
")",
":",
"return",
"transforms",
".",
"cogroup",
"(",
"self",
",",
"other",
",",
"*",
"others",
")"
] | https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/pcollection.py#L97-L110 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | ScrollHelper.SetScale | (*args, **kwargs) | return _windows_.ScrollHelper_SetScale(*args, **kwargs) | SetScale(self, double xs, double ys) | SetScale(self, double xs, double ys) | [
"SetScale",
"(",
"self",
"double",
"xs",
"double",
"ys",
")"
] | def SetScale(*args, **kwargs):
"""SetScale(self, double xs, double ys)"""
return _windows_.ScrollHelper_SetScale(*args, **kwargs) | [
"def",
"SetScale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"ScrollHelper_SetScale",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L203-L205 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/portable_globe.py | python | Globe._GetData | (self) | return content | Returns package or file content currently pointed to by unpacker. | Returns package or file content currently pointed to by unpacker. | [
"Returns",
"package",
"or",
"file",
"content",
"currently",
"pointed",
"to",
"by",
"unpacker",
"."
] | def _GetData(self):
"""Returns package or file content currently pointed to by unpacker."""
assert self.unpacker_
offset = 0L + (self.file_loc_.HighOffset() & 0xffffffff) << 32
offset += (self.file_loc_.LowOffset() & 0xffffffff)
fp = open(self.GlobePath(), "rb")
fp.seek(offset)
# We should never be requesting files whose size doesn't fit in the
# lower 32 bits.
content = fp.read(self.file_loc_.LowSize())
fp.close()
return content | [
"def",
"_GetData",
"(",
"self",
")",
":",
"assert",
"self",
".",
"unpacker_",
"offset",
"=",
"0L",
"+",
"(",
"self",
".",
"file_loc_",
".",
"HighOffset",
"(",
")",
"&",
"0xffffffff",
")",
"<<",
"32",
"offset",
"+=",
"(",
"self",
".",
"file_loc_",
".",
"LowOffset",
"(",
")",
"&",
"0xffffffff",
")",
"fp",
"=",
"open",
"(",
"self",
".",
"GlobePath",
"(",
")",
",",
"\"rb\"",
")",
"fp",
".",
"seek",
"(",
"offset",
")",
"# We should never be requesting files whose size doesn't fit in the",
"# lower 32 bits.",
"content",
"=",
"fp",
".",
"read",
"(",
"self",
".",
"file_loc_",
".",
"LowSize",
"(",
")",
")",
"fp",
".",
"close",
"(",
")",
"return",
"content"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/common/portable_globe.py#L116-L127 | |
PaddlePaddle/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | tools/external_converter_v2/parser/proto/helper.py | python | reverse_cache_data | (data) | tensor_pb2.CacheDate => 1.0 / tensor_pb2.CacheDate | tensor_pb2.CacheDate => 1.0 / tensor_pb2.CacheDate | [
"tensor_pb2",
".",
"CacheDate",
"=",
">",
"1",
".",
"0",
"/",
"tensor_pb2",
".",
"CacheDate"
] | def reverse_cache_data(data): # type: tensor_pb2.CacheDate -> None
"""tensor_pb2.CacheDate => 1.0 / tensor_pb2.CacheDate
"""
if data.type is tensor_pb2.INT8:
data.c[:] = map(lambda x: 1.0 / x, data.c)
elif data.type is tensor_pb2.INT32:
data.i[:] = map(lambda x: 1.0 / x, data.i)
elif data.type in [tensor_pb2.FLOAT, tensor_pb2.FLOAT16, tensor_pb2.DOUBLE]:
data.f[:] = map(lambda x: 1.0 / x, data.f)
elif data.type is tensor_pb2.CACHE_LIST:
for x in data.l:
reverse_cache_data(x)
else:
raise Exception('unsupported data.type={}'.format(data.type)) | [
"def",
"reverse_cache_data",
"(",
"data",
")",
":",
"# type: tensor_pb2.CacheDate -> None",
"if",
"data",
".",
"type",
"is",
"tensor_pb2",
".",
"INT8",
":",
"data",
".",
"c",
"[",
":",
"]",
"=",
"map",
"(",
"lambda",
"x",
":",
"1.0",
"/",
"x",
",",
"data",
".",
"c",
")",
"elif",
"data",
".",
"type",
"is",
"tensor_pb2",
".",
"INT32",
":",
"data",
".",
"i",
"[",
":",
"]",
"=",
"map",
"(",
"lambda",
"x",
":",
"1.0",
"/",
"x",
",",
"data",
".",
"i",
")",
"elif",
"data",
".",
"type",
"in",
"[",
"tensor_pb2",
".",
"FLOAT",
",",
"tensor_pb2",
".",
"FLOAT16",
",",
"tensor_pb2",
".",
"DOUBLE",
"]",
":",
"data",
".",
"f",
"[",
":",
"]",
"=",
"map",
"(",
"lambda",
"x",
":",
"1.0",
"/",
"x",
",",
"data",
".",
"f",
")",
"elif",
"data",
".",
"type",
"is",
"tensor_pb2",
".",
"CACHE_LIST",
":",
"for",
"x",
"in",
"data",
".",
"l",
":",
"reverse_cache_data",
"(",
"x",
")",
"else",
":",
"raise",
"Exception",
"(",
"'unsupported data.type={}'",
".",
"format",
"(",
"data",
".",
"type",
")",
")"
] | https://github.com/PaddlePaddle/Anakin/blob/5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730/tools/external_converter_v2/parser/proto/helper.py#L71-L84 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py | python | ParserElement.addCondition | (self, *fns, **kwargs) | return self | Add a boolean predicate function to expression's list of parse actions. See
L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
functions passed to C{addCondition} need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) | Add a boolean predicate function to expression's list of parse actions. See
L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
functions passed to C{addCondition} need to return boolean success/fail of the condition. | [
"Add",
"a",
"boolean",
"predicate",
"function",
"to",
"expression",
"s",
"list",
"of",
"parse",
"actions",
".",
"See",
"L",
"{",
"I",
"{",
"setParseAction",
"}",
"<setParseAction",
">",
"}",
"for",
"function",
"call",
"signatures",
".",
"Unlike",
"C",
"{",
"setParseAction",
"}",
"functions",
"passed",
"to",
"C",
"{",
"addCondition",
"}",
"need",
"to",
"return",
"boolean",
"success",
"/",
"fail",
"of",
"the",
"condition",
"."
] | def addCondition(self, *fns, **kwargs):
"""Add a boolean predicate function to expression's list of parse actions. See
L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
functions passed to C{addCondition} need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
"""
msg = kwargs.get("message", "failed user-defined condition")
exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException
for fn in fns:
def pa(s,l,t):
if not bool(_trim_arity(fn)(s,l,t)):
raise exc_type(s,l,msg)
self.parseAction.append(pa)
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
return self | [
"def",
"addCondition",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"kwargs",
".",
"get",
"(",
"\"message\"",
",",
"\"failed user-defined condition\"",
")",
"exc_type",
"=",
"ParseFatalException",
"if",
"kwargs",
".",
"get",
"(",
"\"fatal\"",
",",
"False",
")",
"else",
"ParseException",
"for",
"fn",
"in",
"fns",
":",
"def",
"pa",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"if",
"not",
"bool",
"(",
"_trim_arity",
"(",
"fn",
")",
"(",
"s",
",",
"l",
",",
"t",
")",
")",
":",
"raise",
"exc_type",
"(",
"s",
",",
"l",
",",
"msg",
")",
"self",
".",
"parseAction",
".",
"append",
"(",
"pa",
")",
"self",
".",
"callDuringTry",
"=",
"self",
".",
"callDuringTry",
"or",
"kwargs",
".",
"get",
"(",
"\"callDuringTry\"",
",",
"False",
")",
"return",
"self"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L1299-L1324 | |
thalium/icebox | 99d147d5b9269222225443ce171b4fd46d8985d4 | third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py | python | parserCtxt.htmlFreeParserCtxt | (self) | Free all the memory used by a parser context. However the
parsed document in ctxt->myDoc is not freed. | Free all the memory used by a parser context. However the
parsed document in ctxt->myDoc is not freed. | [
"Free",
"all",
"the",
"memory",
"used",
"by",
"a",
"parser",
"context",
".",
"However",
"the",
"parsed",
"document",
"in",
"ctxt",
"-",
">",
"myDoc",
"is",
"not",
"freed",
"."
] | def htmlFreeParserCtxt(self):
"""Free all the memory used by a parser context. However the
parsed document in ctxt->myDoc is not freed. """
libxml2mod.htmlFreeParserCtxt(self._o) | [
"def",
"htmlFreeParserCtxt",
"(",
"self",
")",
":",
"libxml2mod",
".",
"htmlFreeParserCtxt",
"(",
"self",
".",
"_o",
")"
] | https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L4210-L4213 | ||
epiqc/ScaffCC | 66a79944ee4cd116b27bc1a69137276885461db8 | llvm/utils/benchmark/tools/gbench/util.py | python | check_input_file | (filename) | return ftype | Classify the file named by 'filename' and return the classification.
If the file is classified as 'IT_Invalid' print an error message and exit
the program. | Classify the file named by 'filename' and return the classification.
If the file is classified as 'IT_Invalid' print an error message and exit
the program. | [
"Classify",
"the",
"file",
"named",
"by",
"filename",
"and",
"return",
"the",
"classification",
".",
"If",
"the",
"file",
"is",
"classified",
"as",
"IT_Invalid",
"print",
"an",
"error",
"message",
"and",
"exit",
"the",
"program",
"."
] | def check_input_file(filename):
"""
Classify the file named by 'filename' and return the classification.
If the file is classified as 'IT_Invalid' print an error message and exit
the program.
"""
ftype, msg = classify_input_file(filename)
if ftype == IT_Invalid:
print("Invalid input file: %s" % msg)
sys.exit(1)
return ftype | [
"def",
"check_input_file",
"(",
"filename",
")",
":",
"ftype",
",",
"msg",
"=",
"classify_input_file",
"(",
"filename",
")",
"if",
"ftype",
"==",
"IT_Invalid",
":",
"print",
"(",
"\"Invalid input file: %s\"",
"%",
"msg",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"ftype"
] | https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/utils/benchmark/tools/gbench/util.py#L75-L85 | |
y123456yz/reading-and-annotate-mongodb-3.6 | 93280293672ca7586dc24af18132aa61e4ed7fcf | mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Variables/__init__.py | python | Variables.Save | (self, filename, env) | Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file.
filename - Name of the file to save into
env - the environment get the option values from | Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file. | [
"Saves",
"all",
"the",
"options",
"in",
"the",
"given",
"file",
".",
"This",
"file",
"can",
"then",
"be",
"used",
"to",
"load",
"the",
"options",
"next",
"run",
".",
"This",
"can",
"be",
"used",
"to",
"create",
"an",
"option",
"cache",
"file",
"."
] | def Save(self, filename, env):
"""
Saves all the options in the given file. This file can
then be used to load the options next run. This can be used
to create an option cache file.
filename - Name of the file to save into
env - the environment get the option values from
"""
# Create the file and write out the header
try:
fh = open(filename, 'w')
try:
# Make an assignment in the file for each option
# within the environment that was assigned a value
# other than the default.
for option in self.options:
try:
value = env[option.key]
try:
prepare = value.prepare_to_store
except AttributeError:
try:
eval(repr(value))
except KeyboardInterrupt:
raise
except:
# Convert stuff that has a repr() that
# cannot be evaluated into a string
value = SCons.Util.to_String(value)
else:
value = prepare()
defaultVal = env.subst(SCons.Util.to_String(option.default))
if option.converter:
defaultVal = option.converter(defaultVal)
if str(env.subst('${%s}' % option.key)) != str(defaultVal):
fh.write('%s = %s\n' % (option.key, repr(value)))
except KeyError:
pass
finally:
fh.close()
except IOError, x:
raise SCons.Errors.UserError('Error writing options to file: %s\n%s' % (filename, x)) | [
"def",
"Save",
"(",
"self",
",",
"filename",
",",
"env",
")",
":",
"# Create the file and write out the header",
"try",
":",
"fh",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"try",
":",
"# Make an assignment in the file for each option",
"# within the environment that was assigned a value",
"# other than the default.",
"for",
"option",
"in",
"self",
".",
"options",
":",
"try",
":",
"value",
"=",
"env",
"[",
"option",
".",
"key",
"]",
"try",
":",
"prepare",
"=",
"value",
".",
"prepare_to_store",
"except",
"AttributeError",
":",
"try",
":",
"eval",
"(",
"repr",
"(",
"value",
")",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"except",
":",
"# Convert stuff that has a repr() that",
"# cannot be evaluated into a string",
"value",
"=",
"SCons",
".",
"Util",
".",
"to_String",
"(",
"value",
")",
"else",
":",
"value",
"=",
"prepare",
"(",
")",
"defaultVal",
"=",
"env",
".",
"subst",
"(",
"SCons",
".",
"Util",
".",
"to_String",
"(",
"option",
".",
"default",
")",
")",
"if",
"option",
".",
"converter",
":",
"defaultVal",
"=",
"option",
".",
"converter",
"(",
"defaultVal",
")",
"if",
"str",
"(",
"env",
".",
"subst",
"(",
"'${%s}'",
"%",
"option",
".",
"key",
")",
")",
"!=",
"str",
"(",
"defaultVal",
")",
":",
"fh",
".",
"write",
"(",
"'%s = %s\\n'",
"%",
"(",
"option",
".",
"key",
",",
"repr",
"(",
"value",
")",
")",
")",
"except",
"KeyError",
":",
"pass",
"finally",
":",
"fh",
".",
"close",
"(",
")",
"except",
"IOError",
",",
"x",
":",
"raise",
"SCons",
".",
"Errors",
".",
"UserError",
"(",
"'Error writing options to file: %s\\n%s'",
"%",
"(",
"filename",
",",
"x",
")",
")"
] | https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Variables/__init__.py#L230-L277 | ||
chanyn/3Dpose_ssl | 585696676279683a279b1ecca136c0e0d02aef2a | caffe-3dssl/scripts/cpp_lint.py | python | ReplaceAll | (pattern, rep, s) | return _regexp_compile_cache[pattern].sub(rep, s) | Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements) | Replaces instances of pattern in a string with a replacement. | [
"Replaces",
"instances",
"of",
"pattern",
"in",
"a",
"string",
"with",
"a",
"replacement",
"."
] | def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s) | [
"def",
"ReplaceAll",
"(",
"pattern",
",",
"rep",
",",
"s",
")",
":",
"if",
"pattern",
"not",
"in",
"_regexp_compile_cache",
":",
"_regexp_compile_cache",
"[",
"pattern",
"]",
"=",
"sre_compile",
".",
"compile",
"(",
"pattern",
")",
"return",
"_regexp_compile_cache",
"[",
"pattern",
"]",
".",
"sub",
"(",
"rep",
",",
"s",
")"
] | https://github.com/chanyn/3Dpose_ssl/blob/585696676279683a279b1ecca136c0e0d02aef2a/caffe-3dssl/scripts/cpp_lint.py#L525-L540 | |
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsCJKCompatibilityForms | (code) | return ret | Check whether the character is part of
CJKCompatibilityForms UCS Block | Check whether the character is part of
CJKCompatibilityForms UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"CJKCompatibilityForms",
"UCS",
"Block"
] | def uCSIsCJKCompatibilityForms(code):
"""Check whether the character is part of
CJKCompatibilityForms UCS Block """
ret = libxml2mod.xmlUCSIsCJKCompatibilityForms(code)
return ret | [
"def",
"uCSIsCJKCompatibilityForms",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCJKCompatibilityForms",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1405-L1409 | |
lammps/lammps | b75c3065430a75b1b5543a10e10f46d9b4c91913 | tools/i-pi/ipi/engine/forces.py | python | FFSocket.copy | (self) | return type(self)(self.pars, self.socket) | Creates a deep copy without the bound objects.
Used in ForceBeads to create a FFSocket for each replica of the system.
Returns:
A FFSocket object without atoms or cell attributes. | Creates a deep copy without the bound objects. | [
"Creates",
"a",
"deep",
"copy",
"without",
"the",
"bound",
"objects",
"."
] | def copy(self):
"""Creates a deep copy without the bound objects.
Used in ForceBeads to create a FFSocket for each replica of the system.
Returns:
A FFSocket object without atoms or cell attributes.
"""
# does not copy the bound objects
# (i.e., the returned forcefield must be bound before use)
return type(self)(self.pars, self.socket) | [
"def",
"copy",
"(",
"self",
")",
":",
"# does not copy the bound objects",
"# (i.e., the returned forcefield must be bound before use)",
"return",
"type",
"(",
"self",
")",
"(",
"self",
".",
"pars",
",",
"self",
".",
"socket",
")"
] | https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/forces.py#L252-L263 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Editor/Python/windows/Lib/site-packages/setuptools/wheel.py | python | Wheel.is_compatible | (self) | return next((True for t in self.tags() if t in supported_tags), False) | Is the wheel is compatible with the current platform? | Is the wheel is compatible with the current platform? | [
"Is",
"the",
"wheel",
"is",
"compatible",
"with",
"the",
"current",
"platform?"
] | def is_compatible(self):
'''Is the wheel is compatible with the current platform?'''
supported_tags = pep425tags.get_supported()
return next((True for t in self.tags() if t in supported_tags), False) | [
"def",
"is_compatible",
"(",
"self",
")",
":",
"supported_tags",
"=",
"pep425tags",
".",
"get_supported",
"(",
")",
"return",
"next",
"(",
"(",
"True",
"for",
"t",
"in",
"self",
".",
"tags",
"(",
")",
"if",
"t",
"in",
"supported_tags",
")",
",",
"False",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/wheel.py#L77-L80 | |
brave/brave-core | ceaa3de4735789d355b6fa80c21d4709e2c1d0e8 | script/lib/changelog.py | python | reconstruct_brave_changelog_list | (li) | return changes | li is a list | li is a list | [
"li",
"is",
"a",
"list"
] | def reconstruct_brave_changelog_list(li):
"""
li is a list
"""
changes = []
for item in li['children']:
# For special markdown characters such as *EMPHASIS* or `inline code
# blocks`, mistletoe's AST provides us with a nested list. We need
# to traverse the list elements and append them to a single string.
# During this process we also remove the special characters.
appended_entry = str()
for item2 in item['children'][0]['children']:
if 'RawText' in item2['type']:
appended_entry = appended_entry + '{}'.format(item2['content'])
elif 'Link' in item2['type']:
appended_entry = appended_entry + \
'[{}]({})'.format(item2['children']
[0]['content'], item2['target'])
elif 'InlineCode' in item2['type']:
appended_entry = appended_entry + \
'{}'.format(item2['children'][0]['content'])
else:
# Try to catch all other markdown types in this general case
#
# Mistletoe types defined here:
# https://github.com/miyuchina/mistletoe/blob/master/mistletoe/base_renderer.py#L47-L71
appended_entry = appended_entry + \
'{}'.format(item2['children'][0]['content'])
changes.append(" {} {}".format(' -', appended_entry))
return changes | [
"def",
"reconstruct_brave_changelog_list",
"(",
"li",
")",
":",
"changes",
"=",
"[",
"]",
"for",
"item",
"in",
"li",
"[",
"'children'",
"]",
":",
"# For special markdown characters such as *EMPHASIS* or `inline code",
"# blocks`, mistletoe's AST provides us with a nested list. We need",
"# to traverse the list elements and append them to a single string.",
"# During this process we also remove the special characters.",
"appended_entry",
"=",
"str",
"(",
")",
"for",
"item2",
"in",
"item",
"[",
"'children'",
"]",
"[",
"0",
"]",
"[",
"'children'",
"]",
":",
"if",
"'RawText'",
"in",
"item2",
"[",
"'type'",
"]",
":",
"appended_entry",
"=",
"appended_entry",
"+",
"'{}'",
".",
"format",
"(",
"item2",
"[",
"'content'",
"]",
")",
"elif",
"'Link'",
"in",
"item2",
"[",
"'type'",
"]",
":",
"appended_entry",
"=",
"appended_entry",
"+",
"'[{}]({})'",
".",
"format",
"(",
"item2",
"[",
"'children'",
"]",
"[",
"0",
"]",
"[",
"'content'",
"]",
",",
"item2",
"[",
"'target'",
"]",
")",
"elif",
"'InlineCode'",
"in",
"item2",
"[",
"'type'",
"]",
":",
"appended_entry",
"=",
"appended_entry",
"+",
"'{}'",
".",
"format",
"(",
"item2",
"[",
"'children'",
"]",
"[",
"0",
"]",
"[",
"'content'",
"]",
")",
"else",
":",
"# Try to catch all other markdown types in this general case",
"#",
"# Mistletoe types defined here:",
"# https://github.com/miyuchina/mistletoe/blob/master/mistletoe/base_renderer.py#L47-L71",
"appended_entry",
"=",
"appended_entry",
"+",
"'{}'",
".",
"format",
"(",
"item2",
"[",
"'children'",
"]",
"[",
"0",
"]",
"[",
"'content'",
"]",
")",
"changes",
".",
"append",
"(",
"\" {} {}\"",
".",
"format",
"(",
"' -'",
",",
"appended_entry",
")",
")",
"return",
"changes"
] | https://github.com/brave/brave-core/blob/ceaa3de4735789d355b6fa80c21d4709e2c1d0e8/script/lib/changelog.py#L55-L87 | |
apiaryio/snowcrash | b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3 | tools/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.ComputeMacBundleOutput | (self, spec) | return os.path.join(path, self.xcode_settings.GetWrapperName()) | Return the 'output' (full output path) to a bundle output directory. | Return the 'output' (full output path) to a bundle output directory. | [
"Return",
"the",
"output",
"(",
"full",
"output",
"path",
")",
"to",
"a",
"bundle",
"output",
"directory",
"."
] | def ComputeMacBundleOutput(self, spec):
"""Return the 'output' (full output path) to a bundle output directory."""
assert self.is_mac_bundle
path = generator_default_variables['PRODUCT_DIR']
return os.path.join(path, self.xcode_settings.GetWrapperName()) | [
"def",
"ComputeMacBundleOutput",
"(",
"self",
",",
"spec",
")",
":",
"assert",
"self",
".",
"is_mac_bundle",
"path",
"=",
"generator_default_variables",
"[",
"'PRODUCT_DIR'",
"]",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"self",
".",
"xcode_settings",
".",
"GetWrapperName",
"(",
")",
")"
] | https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/make.py#L1386-L1390 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/nanfunctions.py | python | nancumprod | (a, axis=None, dtype=None, out=None) | return np.cumprod(a, axis=axis, dtype=dtype, out=out) | Return the cumulative product of array elements over a given axis treating Not a
Numbers (NaNs) as one. The cumulative product does not change when NaNs are
encountered and leading NaNs are replaced by ones.
Ones are returned for slices that are all-NaN or empty.
.. versionadded:: 1.12.0
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative product is computed. By default
the input is flattened.
dtype : dtype, optional
Type of the returned array, as well as of the accumulator in which
the elements are multiplied. If *dtype* is not specified, it
defaults to the dtype of `a`, unless `a` has an integer dtype with
a precision less than that of the default platform integer. In
that case, the default platform integer is used instead.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type of the resulting values will be cast if necessary.
Returns
-------
nancumprod : ndarray
A new array holding the result is returned unless `out` is
specified, in which case it is returned.
See Also
--------
numpy.cumprod : Cumulative product across array propagating NaNs.
isnan : Show which elements are NaN.
Examples
--------
>>> np.nancumprod(1)
array([1])
>>> np.nancumprod([1])
array([1])
>>> np.nancumprod([1, np.nan])
array([1., 1.])
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nancumprod(a)
array([1., 2., 6., 6.])
>>> np.nancumprod(a, axis=0)
array([[1., 2.],
[3., 2.]])
>>> np.nancumprod(a, axis=1)
array([[1., 2.],
[3., 3.]]) | Return the cumulative product of array elements over a given axis treating Not a
Numbers (NaNs) as one. The cumulative product does not change when NaNs are
encountered and leading NaNs are replaced by ones. | [
"Return",
"the",
"cumulative",
"product",
"of",
"array",
"elements",
"over",
"a",
"given",
"axis",
"treating",
"Not",
"a",
"Numbers",
"(",
"NaNs",
")",
"as",
"one",
".",
"The",
"cumulative",
"product",
"does",
"not",
"change",
"when",
"NaNs",
"are",
"encountered",
"and",
"leading",
"NaNs",
"are",
"replaced",
"by",
"ones",
"."
] | def nancumprod(a, axis=None, dtype=None, out=None):
"""
Return the cumulative product of array elements over a given axis treating Not a
Numbers (NaNs) as one. The cumulative product does not change when NaNs are
encountered and leading NaNs are replaced by ones.
Ones are returned for slices that are all-NaN or empty.
.. versionadded:: 1.12.0
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative product is computed. By default
the input is flattened.
dtype : dtype, optional
Type of the returned array, as well as of the accumulator in which
the elements are multiplied. If *dtype* is not specified, it
defaults to the dtype of `a`, unless `a` has an integer dtype with
a precision less than that of the default platform integer. In
that case, the default platform integer is used instead.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type of the resulting values will be cast if necessary.
Returns
-------
nancumprod : ndarray
A new array holding the result is returned unless `out` is
specified, in which case it is returned.
See Also
--------
numpy.cumprod : Cumulative product across array propagating NaNs.
isnan : Show which elements are NaN.
Examples
--------
>>> np.nancumprod(1)
array([1])
>>> np.nancumprod([1])
array([1])
>>> np.nancumprod([1, np.nan])
array([1., 1.])
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nancumprod(a)
array([1., 2., 6., 6.])
>>> np.nancumprod(a, axis=0)
array([[1., 2.],
[3., 2.]])
>>> np.nancumprod(a, axis=1)
array([[1., 2.],
[3., 3.]])
"""
a, mask = _replace_nan(a, 1)
return np.cumprod(a, axis=axis, dtype=dtype, out=out) | [
"def",
"nancumprod",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"a",
",",
"mask",
"=",
"_replace_nan",
"(",
"a",
",",
"1",
")",
"return",
"np",
".",
"cumprod",
"(",
"a",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/nanfunctions.py#L796-L855 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | native_client_sdk/src/build_tools/update_nacl_manifest.py | python | Updater._GetPlatformArchiveBundle | (self, archive) | return bundle | Downloads the manifest "snippet" for an archive, and reads it as a
Bundle.
Args:
archive: A full URL of a platform-specific archive, using the gs schema.
Returns:
An object of type manifest_util.Bundle, read from a JSON file storing
metadata for this archive. | Downloads the manifest "snippet" for an archive, and reads it as a
Bundle. | [
"Downloads",
"the",
"manifest",
"snippet",
"for",
"an",
"archive",
"and",
"reads",
"it",
"as",
"a",
"Bundle",
"."
] | def _GetPlatformArchiveBundle(self, archive):
"""Downloads the manifest "snippet" for an archive, and reads it as a
Bundle.
Args:
archive: A full URL of a platform-specific archive, using the gs schema.
Returns:
An object of type manifest_util.Bundle, read from a JSON file storing
metadata for this archive.
"""
stdout = self.delegate.GsUtil_cat(archive + '.json')
bundle = manifest_util.Bundle('')
bundle.LoadDataFromString(stdout)
# Some snippets were uploaded with revisions and versions as strings. Fix
# those here.
bundle.revision = int(bundle.revision)
bundle.version = int(bundle.version)
# HACK. The naclports archive specifies host_os as linux. Change it to all.
for archive in bundle.GetArchives():
if NACLPORTS_ARCHIVE_NAME in archive.url:
archive.host_os = 'all'
return bundle | [
"def",
"_GetPlatformArchiveBundle",
"(",
"self",
",",
"archive",
")",
":",
"stdout",
"=",
"self",
".",
"delegate",
".",
"GsUtil_cat",
"(",
"archive",
"+",
"'.json'",
")",
"bundle",
"=",
"manifest_util",
".",
"Bundle",
"(",
"''",
")",
"bundle",
".",
"LoadDataFromString",
"(",
"stdout",
")",
"# Some snippets were uploaded with revisions and versions as strings. Fix",
"# those here.",
"bundle",
".",
"revision",
"=",
"int",
"(",
"bundle",
".",
"revision",
")",
"bundle",
".",
"version",
"=",
"int",
"(",
"bundle",
".",
"version",
")",
"# HACK. The naclports archive specifies host_os as linux. Change it to all.",
"for",
"archive",
"in",
"bundle",
".",
"GetArchives",
"(",
")",
":",
"if",
"NACLPORTS_ARCHIVE_NAME",
"in",
"archive",
".",
"url",
":",
"archive",
".",
"host_os",
"=",
"'all'",
"return",
"bundle"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/build_tools/update_nacl_manifest.py#L710-L732 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/tarfile.py | python | TarFile.__init__ | (self, name=None, mode="r", fileobj=None, format=None,
tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
errors="surrogateescape", pax_headers=None, debug=None,
errorlevel=None, copybufsize=None) | Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
read from an existing archive, 'a' to append data to an existing
file or 'w' to create a new file overwriting an existing one. `mode'
defaults to 'r'.
If `fileobj' is given, it is used for reading or writing data. If it
can be determined, `mode' is overridden by `fileobj's mode.
`fileobj' is not closed, when TarFile is closed. | Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
read from an existing archive, 'a' to append data to an existing
file or 'w' to create a new file overwriting an existing one. `mode'
defaults to 'r'.
If `fileobj' is given, it is used for reading or writing data. If it
can be determined, `mode' is overridden by `fileobj's mode.
`fileobj' is not closed, when TarFile is closed. | [
"Open",
"an",
"(",
"uncompressed",
")",
"tar",
"archive",
"name",
".",
"mode",
"is",
"either",
"r",
"to",
"read",
"from",
"an",
"existing",
"archive",
"a",
"to",
"append",
"data",
"to",
"an",
"existing",
"file",
"or",
"w",
"to",
"create",
"a",
"new",
"file",
"overwriting",
"an",
"existing",
"one",
".",
"mode",
"defaults",
"to",
"r",
".",
"If",
"fileobj",
"is",
"given",
"it",
"is",
"used",
"for",
"reading",
"or",
"writing",
"data",
".",
"If",
"it",
"can",
"be",
"determined",
"mode",
"is",
"overridden",
"by",
"fileobj",
"s",
"mode",
".",
"fileobj",
"is",
"not",
"closed",
"when",
"TarFile",
"is",
"closed",
"."
] | def __init__(self, name=None, mode="r", fileobj=None, format=None,
tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
errors="surrogateescape", pax_headers=None, debug=None,
errorlevel=None, copybufsize=None):
"""Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
read from an existing archive, 'a' to append data to an existing
file or 'w' to create a new file overwriting an existing one. `mode'
defaults to 'r'.
If `fileobj' is given, it is used for reading or writing data. If it
can be determined, `mode' is overridden by `fileobj's mode.
`fileobj' is not closed, when TarFile is closed.
"""
modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
if mode not in modes:
raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
self.mode = mode
self._mode = modes[mode]
if not fileobj:
if self.mode == "a" and not os.path.exists(name):
# Create nonexistent files in append mode.
self.mode = "w"
self._mode = "wb"
fileobj = bltn_open(name, self._mode)
self._extfileobj = False
else:
if (name is None and hasattr(fileobj, "name") and
isinstance(fileobj.name, (str, bytes))):
name = fileobj.name
if hasattr(fileobj, "mode"):
self._mode = fileobj.mode
self._extfileobj = True
self.name = os.path.abspath(name) if name else None
self.fileobj = fileobj
# Init attributes.
if format is not None:
self.format = format
if tarinfo is not None:
self.tarinfo = tarinfo
if dereference is not None:
self.dereference = dereference
if ignore_zeros is not None:
self.ignore_zeros = ignore_zeros
if encoding is not None:
self.encoding = encoding
self.errors = errors
if pax_headers is not None and self.format == PAX_FORMAT:
self.pax_headers = pax_headers
else:
self.pax_headers = {}
if debug is not None:
self.debug = debug
if errorlevel is not None:
self.errorlevel = errorlevel
# Init datastructures.
self.copybufsize = copybufsize
self.closed = False
self.members = [] # list of members as TarInfo objects
self._loaded = False # flag if all members have been read
self.offset = self.fileobj.tell()
# current position in the archive file
self.inodes = {} # dictionary caching the inodes of
# archive members already added
try:
if self.mode == "r":
self.firstmember = None
self.firstmember = self.next()
if self.mode == "a":
# Move to the end of the archive,
# before the first empty block.
while True:
self.fileobj.seek(self.offset)
try:
tarinfo = self.tarinfo.fromtarfile(self)
self.members.append(tarinfo)
except EOFHeaderError:
self.fileobj.seek(self.offset)
break
except HeaderError as e:
raise ReadError(str(e))
if self.mode in ("a", "w", "x"):
self._loaded = True
if self.pax_headers:
buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
self.fileobj.write(buf)
self.offset += len(buf)
except:
if not self._extfileobj:
self.fileobj.close()
self.closed = True
raise | [
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"None",
",",
"mode",
"=",
"\"r\"",
",",
"fileobj",
"=",
"None",
",",
"format",
"=",
"None",
",",
"tarinfo",
"=",
"None",
",",
"dereference",
"=",
"None",
",",
"ignore_zeros",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"\"surrogateescape\"",
",",
"pax_headers",
"=",
"None",
",",
"debug",
"=",
"None",
",",
"errorlevel",
"=",
"None",
",",
"copybufsize",
"=",
"None",
")",
":",
"modes",
"=",
"{",
"\"r\"",
":",
"\"rb\"",
",",
"\"a\"",
":",
"\"r+b\"",
",",
"\"w\"",
":",
"\"wb\"",
",",
"\"x\"",
":",
"\"xb\"",
"}",
"if",
"mode",
"not",
"in",
"modes",
":",
"raise",
"ValueError",
"(",
"\"mode must be 'r', 'a', 'w' or 'x'\"",
")",
"self",
".",
"mode",
"=",
"mode",
"self",
".",
"_mode",
"=",
"modes",
"[",
"mode",
"]",
"if",
"not",
"fileobj",
":",
"if",
"self",
".",
"mode",
"==",
"\"a\"",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
":",
"# Create nonexistent files in append mode.",
"self",
".",
"mode",
"=",
"\"w\"",
"self",
".",
"_mode",
"=",
"\"wb\"",
"fileobj",
"=",
"bltn_open",
"(",
"name",
",",
"self",
".",
"_mode",
")",
"self",
".",
"_extfileobj",
"=",
"False",
"else",
":",
"if",
"(",
"name",
"is",
"None",
"and",
"hasattr",
"(",
"fileobj",
",",
"\"name\"",
")",
"and",
"isinstance",
"(",
"fileobj",
".",
"name",
",",
"(",
"str",
",",
"bytes",
")",
")",
")",
":",
"name",
"=",
"fileobj",
".",
"name",
"if",
"hasattr",
"(",
"fileobj",
",",
"\"mode\"",
")",
":",
"self",
".",
"_mode",
"=",
"fileobj",
".",
"mode",
"self",
".",
"_extfileobj",
"=",
"True",
"self",
".",
"name",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"name",
")",
"if",
"name",
"else",
"None",
"self",
".",
"fileobj",
"=",
"fileobj",
"# Init attributes.",
"if",
"format",
"is",
"not",
"None",
":",
"self",
".",
"format",
"=",
"format",
"if",
"tarinfo",
"is",
"not",
"None",
":",
"self",
".",
"tarinfo",
"=",
"tarinfo",
"if",
"dereference",
"is",
"not",
"None",
":",
"self",
".",
"dereference",
"=",
"dereference",
"if",
"ignore_zeros",
"is",
"not",
"None",
":",
"self",
".",
"ignore_zeros",
"=",
"ignore_zeros",
"if",
"encoding",
"is",
"not",
"None",
":",
"self",
".",
"encoding",
"=",
"encoding",
"self",
".",
"errors",
"=",
"errors",
"if",
"pax_headers",
"is",
"not",
"None",
"and",
"self",
".",
"format",
"==",
"PAX_FORMAT",
":",
"self",
".",
"pax_headers",
"=",
"pax_headers",
"else",
":",
"self",
".",
"pax_headers",
"=",
"{",
"}",
"if",
"debug",
"is",
"not",
"None",
":",
"self",
".",
"debug",
"=",
"debug",
"if",
"errorlevel",
"is",
"not",
"None",
":",
"self",
".",
"errorlevel",
"=",
"errorlevel",
"# Init datastructures.",
"self",
".",
"copybufsize",
"=",
"copybufsize",
"self",
".",
"closed",
"=",
"False",
"self",
".",
"members",
"=",
"[",
"]",
"# list of members as TarInfo objects",
"self",
".",
"_loaded",
"=",
"False",
"# flag if all members have been read",
"self",
".",
"offset",
"=",
"self",
".",
"fileobj",
".",
"tell",
"(",
")",
"# current position in the archive file",
"self",
".",
"inodes",
"=",
"{",
"}",
"# dictionary caching the inodes of",
"# archive members already added",
"try",
":",
"if",
"self",
".",
"mode",
"==",
"\"r\"",
":",
"self",
".",
"firstmember",
"=",
"None",
"self",
".",
"firstmember",
"=",
"self",
".",
"next",
"(",
")",
"if",
"self",
".",
"mode",
"==",
"\"a\"",
":",
"# Move to the end of the archive,",
"# before the first empty block.",
"while",
"True",
":",
"self",
".",
"fileobj",
".",
"seek",
"(",
"self",
".",
"offset",
")",
"try",
":",
"tarinfo",
"=",
"self",
".",
"tarinfo",
".",
"fromtarfile",
"(",
"self",
")",
"self",
".",
"members",
".",
"append",
"(",
"tarinfo",
")",
"except",
"EOFHeaderError",
":",
"self",
".",
"fileobj",
".",
"seek",
"(",
"self",
".",
"offset",
")",
"break",
"except",
"HeaderError",
"as",
"e",
":",
"raise",
"ReadError",
"(",
"str",
"(",
"e",
")",
")",
"if",
"self",
".",
"mode",
"in",
"(",
"\"a\"",
",",
"\"w\"",
",",
"\"x\"",
")",
":",
"self",
".",
"_loaded",
"=",
"True",
"if",
"self",
".",
"pax_headers",
":",
"buf",
"=",
"self",
".",
"tarinfo",
".",
"create_pax_global_header",
"(",
"self",
".",
"pax_headers",
".",
"copy",
"(",
")",
")",
"self",
".",
"fileobj",
".",
"write",
"(",
"buf",
")",
"self",
".",
"offset",
"+=",
"len",
"(",
"buf",
")",
"except",
":",
"if",
"not",
"self",
".",
"_extfileobj",
":",
"self",
".",
"fileobj",
".",
"close",
"(",
")",
"self",
".",
"closed",
"=",
"True",
"raise"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/tarfile.py#L1451-L1549 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/cython/Cython/Compiler/Code.py | python | GlobalState.use_utility_code | (self, utility_code) | Adds code to the C file. utility_code should
a) implement __eq__/__hash__ for the purpose of knowing whether the same
code has already been included
b) implement put_code, which takes a globalstate instance
See UtilityCode. | Adds code to the C file. utility_code should
a) implement __eq__/__hash__ for the purpose of knowing whether the same
code has already been included
b) implement put_code, which takes a globalstate instance | [
"Adds",
"code",
"to",
"the",
"C",
"file",
".",
"utility_code",
"should",
"a",
")",
"implement",
"__eq__",
"/",
"__hash__",
"for",
"the",
"purpose",
"of",
"knowing",
"whether",
"the",
"same",
"code",
"has",
"already",
"been",
"included",
"b",
")",
"implement",
"put_code",
"which",
"takes",
"a",
"globalstate",
"instance"
] | def use_utility_code(self, utility_code):
"""
Adds code to the C file. utility_code should
a) implement __eq__/__hash__ for the purpose of knowing whether the same
code has already been included
b) implement put_code, which takes a globalstate instance
See UtilityCode.
"""
if utility_code and utility_code not in self.utility_codes:
self.utility_codes.add(utility_code)
utility_code.put_code(self) | [
"def",
"use_utility_code",
"(",
"self",
",",
"utility_code",
")",
":",
"if",
"utility_code",
"and",
"utility_code",
"not",
"in",
"self",
".",
"utility_codes",
":",
"self",
".",
"utility_codes",
".",
"add",
"(",
"utility_code",
")",
"utility_code",
".",
"put_code",
"(",
"self",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Compiler/Code.py#L1643-L1654 | ||
NicknineTheEagle/TF2-Base | 20459c5a7fbc995b6bf54fa85c2f62a101e9fb64 | src/thirdparty/protobuf-2.3.0/python/mox.py | python | MockObject.__getitem__ | (self, key) | return self._CreateMockMethod('__getitem__')(key) | Provide custom logic for mocking classes that are subscriptable.
Args:
key: Key to return the value for.
Returns:
Expected return value in replay mode. A MockMethod object for the
__getitem__ method that has already been called if not in replay mode.
Raises:
TypeError if the underlying class is not subscriptable.
UnexpectedMethodCallError if the object does not expect the call to
__setitem__. | Provide custom logic for mocking classes that are subscriptable. | [
"Provide",
"custom",
"logic",
"for",
"mocking",
"classes",
"that",
"are",
"subscriptable",
"."
] | def __getitem__(self, key):
"""Provide custom logic for mocking classes that are subscriptable.
Args:
key: Key to return the value for.
Returns:
Expected return value in replay mode. A MockMethod object for the
__getitem__ method that has already been called if not in replay mode.
Raises:
TypeError if the underlying class is not subscriptable.
UnexpectedMethodCallError if the object does not expect the call to
__setitem__.
"""
getitem = self._class_to_mock.__dict__.get('__getitem__', None)
# Verify the class supports item assignment.
if getitem is None:
raise TypeError('unsubscriptable object')
# If we are in replay mode then simply call the mock __getitem__ method.
if self._replay_mode:
return MockMethod('__getitem__', self._expected_calls_queue,
self._replay_mode)(key)
# Otherwise, create a mock method __getitem__.
return self._CreateMockMethod('__getitem__')(key) | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"getitem",
"=",
"self",
".",
"_class_to_mock",
".",
"__dict__",
".",
"get",
"(",
"'__getitem__'",
",",
"None",
")",
"# Verify the class supports item assignment.",
"if",
"getitem",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'unsubscriptable object'",
")",
"# If we are in replay mode then simply call the mock __getitem__ method.",
"if",
"self",
".",
"_replay_mode",
":",
"return",
"MockMethod",
"(",
"'__getitem__'",
",",
"self",
".",
"_expected_calls_queue",
",",
"self",
".",
"_replay_mode",
")",
"(",
"key",
")",
"# Otherwise, create a mock method __getitem__.",
"return",
"self",
".",
"_CreateMockMethod",
"(",
"'__getitem__'",
")",
"(",
"key",
")"
] | https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/mox.py#L459-L488 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/sparse/base.py | python | spmatrix.transpose | (self, axes=None, copy=False) | return self.tocsr(copy=copy).transpose(axes=axes, copy=False) | Reverses the dimensions of the sparse matrix.
Parameters
----------
axes : None, optional
This argument is in the signature *solely* for NumPy
compatibility reasons. Do not pass in anything except
for the default value.
copy : bool, optional
Indicates whether or not attributes of `self` should be
copied whenever possible. The degree to which attributes
are copied varies depending on the type of sparse matrix
being used.
Returns
-------
p : `self` with the dimensions reversed.
See Also
--------
np.matrix.transpose : NumPy's implementation of 'transpose'
for matrices | Reverses the dimensions of the sparse matrix. | [
"Reverses",
"the",
"dimensions",
"of",
"the",
"sparse",
"matrix",
"."
] | def transpose(self, axes=None, copy=False):
"""
Reverses the dimensions of the sparse matrix.
Parameters
----------
axes : None, optional
This argument is in the signature *solely* for NumPy
compatibility reasons. Do not pass in anything except
for the default value.
copy : bool, optional
Indicates whether or not attributes of `self` should be
copied whenever possible. The degree to which attributes
are copied varies depending on the type of sparse matrix
being used.
Returns
-------
p : `self` with the dimensions reversed.
See Also
--------
np.matrix.transpose : NumPy's implementation of 'transpose'
for matrices
"""
return self.tocsr(copy=copy).transpose(axes=axes, copy=False) | [
"def",
"transpose",
"(",
"self",
",",
"axes",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"return",
"self",
".",
"tocsr",
"(",
"copy",
"=",
"copy",
")",
".",
"transpose",
"(",
"axes",
"=",
"axes",
",",
"copy",
"=",
"False",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/sparse/base.py#L689-L714 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/copy_reg.py | python | add_extension | (module, name, code) | Register an extension code. | Register an extension code. | [
"Register",
"an",
"extension",
"code",
"."
] | def add_extension(module, name, code):
"""Register an extension code."""
code = int(code)
if not 1 <= code <= 0x7fffffff:
raise ValueError, "code out of range"
key = (module, name)
if (_extension_registry.get(key) == code and
_inverted_registry.get(code) == key):
return # Redundant registrations are benign
if key in _extension_registry:
raise ValueError("key %s is already registered with code %s" %
(key, _extension_registry[key]))
if code in _inverted_registry:
raise ValueError("code %s is already in use for key %s" %
(code, _inverted_registry[code]))
_extension_registry[key] = code
_inverted_registry[code] = key | [
"def",
"add_extension",
"(",
"module",
",",
"name",
",",
"code",
")",
":",
"code",
"=",
"int",
"(",
"code",
")",
"if",
"not",
"1",
"<=",
"code",
"<=",
"0x7fffffff",
":",
"raise",
"ValueError",
",",
"\"code out of range\"",
"key",
"=",
"(",
"module",
",",
"name",
")",
"if",
"(",
"_extension_registry",
".",
"get",
"(",
"key",
")",
"==",
"code",
"and",
"_inverted_registry",
".",
"get",
"(",
"code",
")",
"==",
"key",
")",
":",
"return",
"# Redundant registrations are benign",
"if",
"key",
"in",
"_extension_registry",
":",
"raise",
"ValueError",
"(",
"\"key %s is already registered with code %s\"",
"%",
"(",
"key",
",",
"_extension_registry",
"[",
"key",
"]",
")",
")",
"if",
"code",
"in",
"_inverted_registry",
":",
"raise",
"ValueError",
"(",
"\"code %s is already in use for key %s\"",
"%",
"(",
"code",
",",
"_inverted_registry",
"[",
"code",
"]",
")",
")",
"_extension_registry",
"[",
"key",
"]",
"=",
"code",
"_inverted_registry",
"[",
"code",
"]",
"=",
"key"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/copy_reg.py#L161-L177 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/guiutility.py | python | GetValueDialog.__init__ | (self, parent=None, label_name='') | return | :param parent:
:param label_name | :param parent:
:param label_name | [
":",
"param",
"parent",
":",
":",
"param",
"label_name"
] | def __init__(self, parent=None, label_name=''):
"""
:param parent:
:param label_name
"""
super(GetValueDialog, self).__init__(parent)
layout = QVBoxLayout(self)
# details information
self.info_line = QPlainTextEdit(self)
self.info_line.setEnabled(False)
layout.addWidget(self.info_line)
# input
self.label = QLabel(self)
self.value_edit = QLineEdit(self)
layout.addWidget(self.label)
layout.addWidget(self.value_edit)
# END-IF-ELSE
# nice widget for editing the date
# self.datetime = QDateTimeEdit(self)
# self.datetime.setCalendarPopup(True)
# self.datetime.setDateTime(QDateTime.currentDateTime())
# layout.addWidget(self.datetime)
# OK and Cancel buttons
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
QtCore.Qt.Horizontal, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
# set some values
self.setWindowTitle('Get user input')
self.label.setText(label_name)
return | [
"def",
"__init__",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"label_name",
"=",
"''",
")",
":",
"super",
"(",
"GetValueDialog",
",",
"self",
")",
".",
"__init__",
"(",
"parent",
")",
"layout",
"=",
"QVBoxLayout",
"(",
"self",
")",
"# details information",
"self",
".",
"info_line",
"=",
"QPlainTextEdit",
"(",
"self",
")",
"self",
".",
"info_line",
".",
"setEnabled",
"(",
"False",
")",
"layout",
".",
"addWidget",
"(",
"self",
".",
"info_line",
")",
"# input",
"self",
".",
"label",
"=",
"QLabel",
"(",
"self",
")",
"self",
".",
"value_edit",
"=",
"QLineEdit",
"(",
"self",
")",
"layout",
".",
"addWidget",
"(",
"self",
".",
"label",
")",
"layout",
".",
"addWidget",
"(",
"self",
".",
"value_edit",
")",
"# END-IF-ELSE",
"# nice widget for editing the date",
"# self.datetime = QDateTimeEdit(self)",
"# self.datetime.setCalendarPopup(True)",
"# self.datetime.setDateTime(QDateTime.currentDateTime())",
"# layout.addWidget(self.datetime)",
"# OK and Cancel buttons",
"buttons",
"=",
"QDialogButtonBox",
"(",
"QDialogButtonBox",
".",
"Ok",
"|",
"QDialogButtonBox",
".",
"Cancel",
",",
"QtCore",
".",
"Qt",
".",
"Horizontal",
",",
"self",
")",
"buttons",
".",
"accepted",
".",
"connect",
"(",
"self",
".",
"accept",
")",
"buttons",
".",
"rejected",
".",
"connect",
"(",
"self",
".",
"reject",
")",
"layout",
".",
"addWidget",
"(",
"buttons",
")",
"# set some values",
"self",
".",
"setWindowTitle",
"(",
"'Get user input'",
")",
"self",
".",
"label",
".",
"setText",
"(",
"label_name",
")",
"return"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/guiutility.py#L379-L418 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/dataview.py | python | DataViewModel.BeforeReset | (*args, **kwargs) | return _dataview.DataViewModel_BeforeReset(*args, **kwargs) | BeforeReset(self) -> bool | BeforeReset(self) -> bool | [
"BeforeReset",
"(",
"self",
")",
"-",
">",
"bool"
] | def BeforeReset(*args, **kwargs):
"""BeforeReset(self) -> bool"""
return _dataview.DataViewModel_BeforeReset(*args, **kwargs) | [
"def",
"BeforeReset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewModel_BeforeReset",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L628-L630 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/contrib/factorization/python/ops/clustering_ops.py | python | KMeans._full_batch_training_op | (self, inputs, cluster_idx_list, cluster_centers) | return tf.assign(cluster_centers, new_clusters_centers) | Creates an op for training for full batch case.
Args:
inputs: list of input Tensors.
cluster_idx_list: A vector (or list of vectors). Each element in the
vector corresponds to an input row in 'inp' and specifies the cluster id
corresponding to the input.
cluster_centers: Tensor Ref of cluster centers.
Returns:
An op for doing an update of mini-batch k-means. | Creates an op for training for full batch case. | [
"Creates",
"an",
"op",
"for",
"training",
"for",
"full",
"batch",
"case",
"."
] | def _full_batch_training_op(self, inputs, cluster_idx_list, cluster_centers):
"""Creates an op for training for full batch case.
Args:
inputs: list of input Tensors.
cluster_idx_list: A vector (or list of vectors). Each element in the
vector corresponds to an input row in 'inp' and specifies the cluster id
corresponding to the input.
cluster_centers: Tensor Ref of cluster centers.
Returns:
An op for doing an update of mini-batch k-means.
"""
cluster_sums = []
cluster_counts = []
epsilon = tf.constant(1e-6, dtype=inputs[0].dtype)
for inp, cluster_idx in zip(inputs, cluster_idx_list):
with ops.colocate_with(inp):
cluster_sums.append(tf.unsorted_segment_sum(inp,
cluster_idx,
self._num_clusters))
cluster_counts.append(tf.unsorted_segment_sum(
tf.reshape(tf.ones(tf.reshape(tf.shape(inp)[0], [-1])), [-1, 1]),
cluster_idx,
self._num_clusters))
with ops.colocate_with(cluster_centers):
new_clusters_centers = tf.add_n(cluster_sums) / (
tf.cast(tf.add_n(cluster_counts), cluster_sums[0].dtype) + epsilon)
if self._clusters_l2_normalized():
new_clusters_centers = tf.nn.l2_normalize(new_clusters_centers, dim=1)
return tf.assign(cluster_centers, new_clusters_centers) | [
"def",
"_full_batch_training_op",
"(",
"self",
",",
"inputs",
",",
"cluster_idx_list",
",",
"cluster_centers",
")",
":",
"cluster_sums",
"=",
"[",
"]",
"cluster_counts",
"=",
"[",
"]",
"epsilon",
"=",
"tf",
".",
"constant",
"(",
"1e-6",
",",
"dtype",
"=",
"inputs",
"[",
"0",
"]",
".",
"dtype",
")",
"for",
"inp",
",",
"cluster_idx",
"in",
"zip",
"(",
"inputs",
",",
"cluster_idx_list",
")",
":",
"with",
"ops",
".",
"colocate_with",
"(",
"inp",
")",
":",
"cluster_sums",
".",
"append",
"(",
"tf",
".",
"unsorted_segment_sum",
"(",
"inp",
",",
"cluster_idx",
",",
"self",
".",
"_num_clusters",
")",
")",
"cluster_counts",
".",
"append",
"(",
"tf",
".",
"unsorted_segment_sum",
"(",
"tf",
".",
"reshape",
"(",
"tf",
".",
"ones",
"(",
"tf",
".",
"reshape",
"(",
"tf",
".",
"shape",
"(",
"inp",
")",
"[",
"0",
"]",
",",
"[",
"-",
"1",
"]",
")",
")",
",",
"[",
"-",
"1",
",",
"1",
"]",
")",
",",
"cluster_idx",
",",
"self",
".",
"_num_clusters",
")",
")",
"with",
"ops",
".",
"colocate_with",
"(",
"cluster_centers",
")",
":",
"new_clusters_centers",
"=",
"tf",
".",
"add_n",
"(",
"cluster_sums",
")",
"/",
"(",
"tf",
".",
"cast",
"(",
"tf",
".",
"add_n",
"(",
"cluster_counts",
")",
",",
"cluster_sums",
"[",
"0",
"]",
".",
"dtype",
")",
"+",
"epsilon",
")",
"if",
"self",
".",
"_clusters_l2_normalized",
"(",
")",
":",
"new_clusters_centers",
"=",
"tf",
".",
"nn",
".",
"l2_normalize",
"(",
"new_clusters_centers",
",",
"dim",
"=",
"1",
")",
"return",
"tf",
".",
"assign",
"(",
"cluster_centers",
",",
"new_clusters_centers",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/factorization/python/ops/clustering_ops.py#L378-L408 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/distributions/student_t.py | python | StudentT.__init__ | (self,
df,
loc,
scale,
validate_args=False,
allow_nan_stats=True,
name="StudentT") | Construct Student's t distributions.
The distributions have degree of freedom `df`, mean `loc`, and scale
`scale`.
The parameters `df`, `loc`, and `scale` must be shaped in a way that
supports broadcasting (e.g. `df + loc + scale` is a valid operation).
Args:
df: Floating-point `Tensor`. The degrees of freedom of the
distribution(s). `df` must contain only positive values.
loc: Floating-point `Tensor`. The mean(s) of the distribution(s).
scale: Floating-point `Tensor`. The scaling factor(s) for the
distribution(s). Note that `scale` is not technically the standard
deviation of this distribution but has semantics more similar to
standard deviation than variance.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`,
statistics (e.g., mean, mode, variance) use the value "`NaN`" to
indicate the result is undefined. When `False`, an exception is raised
if one or more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
Raises:
TypeError: if loc and scale are different dtypes. | Construct Student's t distributions. | [
"Construct",
"Student",
"s",
"t",
"distributions",
"."
] | def __init__(self,
df,
loc,
scale,
validate_args=False,
allow_nan_stats=True,
name="StudentT"):
"""Construct Student's t distributions.
The distributions have degree of freedom `df`, mean `loc`, and scale
`scale`.
The parameters `df`, `loc`, and `scale` must be shaped in a way that
supports broadcasting (e.g. `df + loc + scale` is a valid operation).
Args:
df: Floating-point `Tensor`. The degrees of freedom of the
distribution(s). `df` must contain only positive values.
loc: Floating-point `Tensor`. The mean(s) of the distribution(s).
scale: Floating-point `Tensor`. The scaling factor(s) for the
distribution(s). Note that `scale` is not technically the standard
deviation of this distribution but has semantics more similar to
standard deviation than variance.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
allow_nan_stats: Python `bool`, default `True`. When `True`,
statistics (e.g., mean, mode, variance) use the value "`NaN`" to
indicate the result is undefined. When `False`, an exception is raised
if one or more of the statistic's batch members are undefined.
name: Python `str` name prefixed to Ops created by this class.
Raises:
TypeError: if loc and scale are different dtypes.
"""
parameters = locals()
with ops.name_scope(name, values=[df, loc, scale]):
with ops.control_dependencies([check_ops.assert_positive(df)]
if validate_args else []):
self._df = array_ops.identity(df, name="df")
self._loc = array_ops.identity(loc, name="loc")
self._scale = array_ops.identity(scale, name="scale")
check_ops.assert_same_float_dtype(
(self._df, self._loc, self._scale))
super(StudentT, self).__init__(
dtype=self._scale.dtype,
reparameterization_type=distribution.NOT_REPARAMETERIZED,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
parameters=parameters,
graph_parents=[self._df, self._loc, self._scale],
name=name) | [
"def",
"__init__",
"(",
"self",
",",
"df",
",",
"loc",
",",
"scale",
",",
"validate_args",
"=",
"False",
",",
"allow_nan_stats",
"=",
"True",
",",
"name",
"=",
"\"StudentT\"",
")",
":",
"parameters",
"=",
"locals",
"(",
")",
"with",
"ops",
".",
"name_scope",
"(",
"name",
",",
"values",
"=",
"[",
"df",
",",
"loc",
",",
"scale",
"]",
")",
":",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"check_ops",
".",
"assert_positive",
"(",
"df",
")",
"]",
"if",
"validate_args",
"else",
"[",
"]",
")",
":",
"self",
".",
"_df",
"=",
"array_ops",
".",
"identity",
"(",
"df",
",",
"name",
"=",
"\"df\"",
")",
"self",
".",
"_loc",
"=",
"array_ops",
".",
"identity",
"(",
"loc",
",",
"name",
"=",
"\"loc\"",
")",
"self",
".",
"_scale",
"=",
"array_ops",
".",
"identity",
"(",
"scale",
",",
"name",
"=",
"\"scale\"",
")",
"check_ops",
".",
"assert_same_float_dtype",
"(",
"(",
"self",
".",
"_df",
",",
"self",
".",
"_loc",
",",
"self",
".",
"_scale",
")",
")",
"super",
"(",
"StudentT",
",",
"self",
")",
".",
"__init__",
"(",
"dtype",
"=",
"self",
".",
"_scale",
".",
"dtype",
",",
"reparameterization_type",
"=",
"distribution",
".",
"NOT_REPARAMETERIZED",
",",
"validate_args",
"=",
"validate_args",
",",
"allow_nan_stats",
"=",
"allow_nan_stats",
",",
"parameters",
"=",
"parameters",
",",
"graph_parents",
"=",
"[",
"self",
".",
"_df",
",",
"self",
".",
"_loc",
",",
"self",
".",
"_scale",
"]",
",",
"name",
"=",
"name",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/student_t.py#L122-L174 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/extern/stcspellcheck.py | python | STCSpellCheck.reloadEnchant | (cls, libpath=u'') | Try (re)loading the enchant module. Use to dynamically try to
import enchant incase it could be loaded at the time of the import of
this module.
@keyword libpath: optionally specify path to libenchant
@return: bool | Try (re)loading the enchant module. Use to dynamically try to
import enchant incase it could be loaded at the time of the import of
this module.
@keyword libpath: optionally specify path to libenchant
@return: bool | [
"Try",
"(",
"re",
")",
"loading",
"the",
"enchant",
"module",
".",
"Use",
"to",
"dynamically",
"try",
"to",
"import",
"enchant",
"incase",
"it",
"could",
"be",
"loaded",
"at",
"the",
"time",
"of",
"the",
"import",
"of",
"this",
"module",
".",
"@keyword",
"libpath",
":",
"optionally",
"specify",
"path",
"to",
"libenchant",
"@return",
":",
"bool"
] | def reloadEnchant(cls, libpath=u''):
"""Try (re)loading the enchant module. Use to dynamically try to
import enchant incase it could be loaded at the time of the import of
this module.
@keyword libpath: optionally specify path to libenchant
@return: bool
"""
try:
if libpath and os.path.exists(libpath):
os.environ['PYENCHANT_LIBRARY_PATH'] = libpath
if cls.isEnchantOk():
reload(enchant)
else:
mod = __import__('enchant', globals(), locals())
globals()['enchant'] = mod
except ImportError:
return False
else:
return True | [
"def",
"reloadEnchant",
"(",
"cls",
",",
"libpath",
"=",
"u''",
")",
":",
"try",
":",
"if",
"libpath",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"libpath",
")",
":",
"os",
".",
"environ",
"[",
"'PYENCHANT_LIBRARY_PATH'",
"]",
"=",
"libpath",
"if",
"cls",
".",
"isEnchantOk",
"(",
")",
":",
"reload",
"(",
"enchant",
")",
"else",
":",
"mod",
"=",
"__import__",
"(",
"'enchant'",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
")",
"globals",
"(",
")",
"[",
"'enchant'",
"]",
"=",
"mod",
"except",
"ImportError",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/stcspellcheck.py#L260-L280 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | deps/src/libxml2-2.9.1/python/libxml2class.py | python | uCSIsCJKSymbolsandPunctuation | (code) | return ret | Check whether the character is part of
CJKSymbolsandPunctuation UCS Block | Check whether the character is part of
CJKSymbolsandPunctuation UCS Block | [
"Check",
"whether",
"the",
"character",
"is",
"part",
"of",
"CJKSymbolsandPunctuation",
"UCS",
"Block"
] | def uCSIsCJKSymbolsandPunctuation(code):
"""Check whether the character is part of
CJKSymbolsandPunctuation UCS Block """
ret = libxml2mod.xmlUCSIsCJKSymbolsandPunctuation(code)
return ret | [
"def",
"uCSIsCJKSymbolsandPunctuation",
"(",
"code",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlUCSIsCJKSymbolsandPunctuation",
"(",
"code",
")",
"return",
"ret"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1429-L1433 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/cfg.py | python | GraphBuilder._add_new_node | (self, ast_node) | return node | Grows the graph by adding a CFG node following the current leaves. | Grows the graph by adding a CFG node following the current leaves. | [
"Grows",
"the",
"graph",
"by",
"adding",
"a",
"CFG",
"node",
"following",
"the",
"current",
"leaves",
"."
] | def _add_new_node(self, ast_node):
"""Grows the graph by adding a CFG node following the current leaves."""
if ast_node is self.node_index:
raise ValueError('%s added twice' % ast_node)
# Assumption: All CFG nodes have identical life spans, because the graph
# owns them. Nodes should never be used outside the context of an existing
# graph.
node = Node(next_=set(), prev=weakref.WeakSet(), ast_node=ast_node)
self.node_index[ast_node] = node
self.owners[node] = frozenset(self.active_stmts)
if self.head is None:
self.head = node
for leaf in self.leaves:
self._connect_nodes(leaf, node)
# If any finally section awaits its first node, populate it.
for section_id in self.pending_finally_sections:
self.finally_section_subgraphs[section_id][0] = node
self.pending_finally_sections = set()
return node | [
"def",
"_add_new_node",
"(",
"self",
",",
"ast_node",
")",
":",
"if",
"ast_node",
"is",
"self",
".",
"node_index",
":",
"raise",
"ValueError",
"(",
"'%s added twice'",
"%",
"ast_node",
")",
"# Assumption: All CFG nodes have identical life spans, because the graph",
"# owns them. Nodes should never be used outside the context of an existing",
"# graph.",
"node",
"=",
"Node",
"(",
"next_",
"=",
"set",
"(",
")",
",",
"prev",
"=",
"weakref",
".",
"WeakSet",
"(",
")",
",",
"ast_node",
"=",
"ast_node",
")",
"self",
".",
"node_index",
"[",
"ast_node",
"]",
"=",
"node",
"self",
".",
"owners",
"[",
"node",
"]",
"=",
"frozenset",
"(",
"self",
".",
"active_stmts",
")",
"if",
"self",
".",
"head",
"is",
"None",
":",
"self",
".",
"head",
"=",
"node",
"for",
"leaf",
"in",
"self",
".",
"leaves",
":",
"self",
".",
"_connect_nodes",
"(",
"leaf",
",",
"node",
")",
"# If any finally section awaits its first node, populate it.",
"for",
"section_id",
"in",
"self",
".",
"pending_finally_sections",
":",
"self",
".",
"finally_section_subgraphs",
"[",
"section_id",
"]",
"[",
"0",
"]",
"=",
"node",
"self",
".",
"pending_finally_sections",
"=",
"set",
"(",
")",
"return",
"node"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/cfg.py#L324-L346 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/distro.py | python | _distro_version | (version_val) | return version_val | Parse distro version value, converting SVN revision to version value if necessary | Parse distro version value, converting SVN revision to version value if necessary | [
"Parse",
"distro",
"version",
"value",
"converting",
"SVN",
"revision",
"to",
"version",
"value",
"if",
"necessary"
] | def _distro_version(version_val):
"""
Parse distro version value, converting SVN revision to version value if necessary
"""
version_val = str(version_val)
# check for no keyword sub
if version_val == '$Revision$':
return 0
m = re.search('\$Revision:\s*([0-9]*)\s*\$', version_val)
if m is not None:
version_val = 'r'+m.group(1)
# Check that is a valid version string
valid = string.ascii_letters + string.digits + '.+~'
if False in (c in valid for c in version_val):
raise InvalidDistro("Version string %s not valid"%version_val)
return version_val | [
"def",
"_distro_version",
"(",
"version_val",
")",
":",
"version_val",
"=",
"str",
"(",
"version_val",
")",
"# check for no keyword sub",
"if",
"version_val",
"==",
"'$Revision$'",
":",
"return",
"0",
"m",
"=",
"re",
".",
"search",
"(",
"'\\$Revision:\\s*([0-9]*)\\s*\\$'",
",",
"version_val",
")",
"if",
"m",
"is",
"not",
"None",
":",
"version_val",
"=",
"'r'",
"+",
"m",
".",
"group",
"(",
"1",
")",
"# Check that is a valid version string",
"valid",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'.+~'",
"if",
"False",
"in",
"(",
"c",
"in",
"valid",
"for",
"c",
"in",
"version_val",
")",
":",
"raise",
"InvalidDistro",
"(",
"\"Version string %s not valid\"",
"%",
"version_val",
")",
"return",
"version_val"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/rospkg/distro.py#L267-L283 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TextAttr.HasFontUnderlined | (*args, **kwargs) | return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs) | HasFontUnderlined(self) -> bool | HasFontUnderlined(self) -> bool | [
"HasFontUnderlined",
"(",
"self",
")",
"-",
">",
"bool"
] | def HasFontUnderlined(*args, **kwargs):
"""HasFontUnderlined(self) -> bool"""
return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs) | [
"def",
"HasFontUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TextAttr_HasFontUnderlined",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1804-L1806 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/data/benchmarks/from_tensor_slices_benchmark.py | python | SingleThreadedFlatMapDataset.__init__ | (self, input_dataset, map_func) | See `Dataset.flat_map()` for details. | See `Dataset.flat_map()` for details. | [
"See",
"Dataset",
".",
"flat_map",
"()",
"for",
"details",
"."
] | def __init__(self, input_dataset, map_func):
"""See `Dataset.flat_map()` for details."""
self._input_dataset = input_dataset
self._map_func = structured_function.StructuredFunctionWrapper(
map_func,
self._transformation_name(),
dataset=input_dataset,
defun_kwargs={"_executor": "SINGLE_THREADED_EXECUTOR"})
self._structure = self._map_func.output_structure._element_spec # pylint: disable=protected-access
variant_tensor = gen_dataset_ops.flat_map_dataset(
input_dataset._variant_tensor, # pylint: disable=protected-access
self._map_func.function.captured_inputs,
f=self._map_func.function,
**self._flat_structure)
super(SingleThreadedFlatMapDataset, self).__init__(input_dataset,
variant_tensor) | [
"def",
"__init__",
"(",
"self",
",",
"input_dataset",
",",
"map_func",
")",
":",
"self",
".",
"_input_dataset",
"=",
"input_dataset",
"self",
".",
"_map_func",
"=",
"structured_function",
".",
"StructuredFunctionWrapper",
"(",
"map_func",
",",
"self",
".",
"_transformation_name",
"(",
")",
",",
"dataset",
"=",
"input_dataset",
",",
"defun_kwargs",
"=",
"{",
"\"_executor\"",
":",
"\"SINGLE_THREADED_EXECUTOR\"",
"}",
")",
"self",
".",
"_structure",
"=",
"self",
".",
"_map_func",
".",
"output_structure",
".",
"_element_spec",
"# pylint: disable=protected-access",
"variant_tensor",
"=",
"gen_dataset_ops",
".",
"flat_map_dataset",
"(",
"input_dataset",
".",
"_variant_tensor",
",",
"# pylint: disable=protected-access",
"self",
".",
"_map_func",
".",
"function",
".",
"captured_inputs",
",",
"f",
"=",
"self",
".",
"_map_func",
".",
"function",
",",
"*",
"*",
"self",
".",
"_flat_structure",
")",
"super",
"(",
"SingleThreadedFlatMapDataset",
",",
"self",
")",
".",
"__init__",
"(",
"input_dataset",
",",
"variant_tensor",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/benchmarks/from_tensor_slices_benchmark.py#L30-L45 | ||
microsoft/checkedc-clang | a173fefde5d7877b7750e7ce96dd08cf18baebf2 | libcxx/utils/libcxx/sym_check/util.py | python | read_syms_from_file | (filename) | return read_syms_from_list(data.splitlines()) | Read a list of symbols in from a file. | Read a list of symbols in from a file. | [
"Read",
"a",
"list",
"of",
"symbols",
"in",
"from",
"a",
"file",
"."
] | def read_syms_from_file(filename):
"""
Read a list of symbols in from a file.
"""
with open(filename, 'r') as f:
data = f.read()
return read_syms_from_list(data.splitlines()) | [
"def",
"read_syms_from_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"return",
"read_syms_from_list",
"(",
"data",
".",
"splitlines",
"(",
")",
")"
] | https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/libcxx/utils/libcxx/sym_check/util.py#L25-L31 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py | python | PthDistributions.add | (self, dist) | Add `dist` to the distribution map | Add `dist` to the distribution map | [
"Add",
"dist",
"to",
"the",
"distribution",
"map"
] | def add(self, dist):
"""Add `dist` to the distribution map"""
new_path = (
dist.location not in self.paths and (
dist.location not in self.sitedirs or
# account for '.' being in PYTHONPATH
dist.location == os.getcwd()
)
)
if new_path:
self.paths.append(dist.location)
self.dirty = True
Environment.add(self, dist) | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"new_path",
"=",
"(",
"dist",
".",
"location",
"not",
"in",
"self",
".",
"paths",
"and",
"(",
"dist",
".",
"location",
"not",
"in",
"self",
".",
"sitedirs",
"or",
"# account for '.' being in PYTHONPATH",
"dist",
".",
"location",
"==",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"if",
"new_path",
":",
"self",
".",
"paths",
".",
"append",
"(",
"dist",
".",
"location",
")",
"self",
".",
"dirty",
"=",
"True",
"Environment",
".",
"add",
"(",
"self",
",",
"dist",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/easy_install.py#L1644-L1656 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py | python | VersionControlSystem.GetGUID | (self) | Return string to distinguish the repository from others, for example to
query all opened review issues for it | Return string to distinguish the repository from others, for example to
query all opened review issues for it | [
"Return",
"string",
"to",
"distinguish",
"the",
"repository",
"from",
"others",
"for",
"example",
"to",
"query",
"all",
"opened",
"review",
"issues",
"for",
"it"
] | def GetGUID(self):
"""Return string to distinguish the repository from others, for example to
query all opened review issues for it"""
raise NotImplementedError(
"abstract method -- subclass %s must override" % self.__class__) | [
"def",
"GetGUID",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"abstract method -- subclass %s must override\"",
"%",
"self",
".",
"__class__",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L814-L818 | ||
facebookincubator/mvfst | 034a40c797485113d00127852d4df3c5bb44b3ed | build/fbcode_builder/fbcode_builder.py | python | FBCodeBuilder.render | (self, steps) | return res | Converts nested actions to your builder's expected output format.
Typically takes the output of build(). | [] | def render(self, steps):
"""
Converts nested actions to your builder's expected output format.
Typically takes the output of build().
"""
res = self._render_impl(steps) # Implementation-dependent
# Now that the output is rendered, we expect all options to have
# been used.
unused_options = set(self._options_do_not_access)
unused_options -= self.options_used
if unused_options:
raise RuntimeError(
"Unused options: {0} -- please check if you made a typo "
"in any of them. Those that are truly not useful should "
"be not be set so that this typo detection can be useful.".format(
unused_options
)
)
return res | [
"def",
"render",
"(",
"self",
",",
"steps",
")",
":",
"res",
"=",
"self",
".",
"_render_impl",
"(",
"steps",
")",
"# Implementation-dependent",
"# Now that the output is rendered, we expect all options to have",
"# been used.",
"unused_options",
"=",
"set",
"(",
"self",
".",
"_options_do_not_access",
")",
"unused_options",
"-=",
"self",
".",
"options_used",
"if",
"unused_options",
":",
"raise",
"RuntimeError",
"(",
"\"Unused options: {0} -- please check if you made a typo \"",
"\"in any of them. Those that are truly not useful should \"",
"\"be not be set so that this typo detection can be useful.\"",
".",
"format",
"(",
"unused_options",
")",
")",
"return",
"res"
] | https://github.com/facebookincubator/mvfst/blob/034a40c797485113d00127852d4df3c5bb44b3ed/build/fbcode_builder/fbcode_builder.py#L120-L140 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/codecs.py | python | StreamReader.read | (self, size=-1, chars=-1, firstline=False) | return result | Decodes data from the stream self.stream and returns the
resulting object.
chars indicates the number of decoded code points or bytes to
return. read() will never return more data than requested,
but it might return less, if there is not enough available.
size indicates the approximate maximum number of decoded
bytes or code points to read for decoding. The decoder
can modify this setting as appropriate. The default value
-1 indicates to read and decode as much as possible. size
is intended to prevent having to decode huge files in one
step.
If firstline is true, and a UnicodeDecodeError happens
after the first line terminator in the input only the first line
will be returned, the rest of the input will be kept until the
next call to read().
The method should use a greedy read strategy, meaning that
it should read as much data as is allowed within the
definition of the encoding and the given size, e.g. if
optional encoding endings or state markers are available
on the stream, these should be read too. | Decodes data from the stream self.stream and returns the
resulting object. | [
"Decodes",
"data",
"from",
"the",
"stream",
"self",
".",
"stream",
"and",
"returns",
"the",
"resulting",
"object",
"."
] | def read(self, size=-1, chars=-1, firstline=False):
""" Decodes data from the stream self.stream and returns the
resulting object.
chars indicates the number of decoded code points or bytes to
return. read() will never return more data than requested,
but it might return less, if there is not enough available.
size indicates the approximate maximum number of decoded
bytes or code points to read for decoding. The decoder
can modify this setting as appropriate. The default value
-1 indicates to read and decode as much as possible. size
is intended to prevent having to decode huge files in one
step.
If firstline is true, and a UnicodeDecodeError happens
after the first line terminator in the input only the first line
will be returned, the rest of the input will be kept until the
next call to read().
The method should use a greedy read strategy, meaning that
it should read as much data as is allowed within the
definition of the encoding and the given size, e.g. if
optional encoding endings or state markers are available
on the stream, these should be read too.
"""
# If we have lines cached, first merge them back into characters
if self.linebuffer:
self.charbuffer = self._empty_charbuffer.join(self.linebuffer)
self.linebuffer = None
if chars < 0:
# For compatibility with other read() methods that take a
# single argument
chars = size
# read until we get the required number of characters (if available)
while True:
# can the request be satisfied from the character buffer?
if chars >= 0:
if len(self.charbuffer) >= chars:
break
# we need more data
if size < 0:
newdata = self.stream.read()
else:
newdata = self.stream.read(size)
# decode bytes (those remaining from the last call included)
data = self.bytebuffer + newdata
if not data:
break
try:
newchars, decodedbytes = self.decode(data, self.errors)
except UnicodeDecodeError as exc:
if firstline:
newchars, decodedbytes = \
self.decode(data[:exc.start], self.errors)
lines = newchars.splitlines(keepends=True)
if len(lines)<=1:
raise
else:
raise
# keep undecoded bytes until the next call
self.bytebuffer = data[decodedbytes:]
# put new characters in the character buffer
self.charbuffer += newchars
# there was no data available
if not newdata:
break
if chars < 0:
# Return everything we've got
result = self.charbuffer
self.charbuffer = self._empty_charbuffer
else:
# Return the first chars characters
result = self.charbuffer[:chars]
self.charbuffer = self.charbuffer[chars:]
return result | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
",",
"chars",
"=",
"-",
"1",
",",
"firstline",
"=",
"False",
")",
":",
"# If we have lines cached, first merge them back into characters",
"if",
"self",
".",
"linebuffer",
":",
"self",
".",
"charbuffer",
"=",
"self",
".",
"_empty_charbuffer",
".",
"join",
"(",
"self",
".",
"linebuffer",
")",
"self",
".",
"linebuffer",
"=",
"None",
"if",
"chars",
"<",
"0",
":",
"# For compatibility with other read() methods that take a",
"# single argument",
"chars",
"=",
"size",
"# read until we get the required number of characters (if available)",
"while",
"True",
":",
"# can the request be satisfied from the character buffer?",
"if",
"chars",
">=",
"0",
":",
"if",
"len",
"(",
"self",
".",
"charbuffer",
")",
">=",
"chars",
":",
"break",
"# we need more data",
"if",
"size",
"<",
"0",
":",
"newdata",
"=",
"self",
".",
"stream",
".",
"read",
"(",
")",
"else",
":",
"newdata",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"size",
")",
"# decode bytes (those remaining from the last call included)",
"data",
"=",
"self",
".",
"bytebuffer",
"+",
"newdata",
"if",
"not",
"data",
":",
"break",
"try",
":",
"newchars",
",",
"decodedbytes",
"=",
"self",
".",
"decode",
"(",
"data",
",",
"self",
".",
"errors",
")",
"except",
"UnicodeDecodeError",
"as",
"exc",
":",
"if",
"firstline",
":",
"newchars",
",",
"decodedbytes",
"=",
"self",
".",
"decode",
"(",
"data",
"[",
":",
"exc",
".",
"start",
"]",
",",
"self",
".",
"errors",
")",
"lines",
"=",
"newchars",
".",
"splitlines",
"(",
"keepends",
"=",
"True",
")",
"if",
"len",
"(",
"lines",
")",
"<=",
"1",
":",
"raise",
"else",
":",
"raise",
"# keep undecoded bytes until the next call",
"self",
".",
"bytebuffer",
"=",
"data",
"[",
"decodedbytes",
":",
"]",
"# put new characters in the character buffer",
"self",
".",
"charbuffer",
"+=",
"newchars",
"# there was no data available",
"if",
"not",
"newdata",
":",
"break",
"if",
"chars",
"<",
"0",
":",
"# Return everything we've got",
"result",
"=",
"self",
".",
"charbuffer",
"self",
".",
"charbuffer",
"=",
"self",
".",
"_empty_charbuffer",
"else",
":",
"# Return the first chars characters",
"result",
"=",
"self",
".",
"charbuffer",
"[",
":",
"chars",
"]",
"self",
".",
"charbuffer",
"=",
"self",
".",
"charbuffer",
"[",
"chars",
":",
"]",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/codecs.py#L451-L529 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/lib-tk/Tkinter.py | python | NoDefaultRoot | () | Inhibit setting of default root window.
Call this function to inhibit that the first instance of
Tk is used for windows without an explicit parent window. | Inhibit setting of default root window. | [
"Inhibit",
"setting",
"of",
"default",
"root",
"window",
"."
] | def NoDefaultRoot():
"""Inhibit setting of default root window.
Call this function to inhibit that the first instance of
Tk is used for windows without an explicit parent window.
"""
global _support_default_root
_support_default_root = 0
global _default_root
_default_root = None
del _default_root | [
"def",
"NoDefaultRoot",
"(",
")",
":",
"global",
"_support_default_root",
"_support_default_root",
"=",
"0",
"global",
"_default_root",
"_default_root",
"=",
"None",
"del",
"_default_root"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L199-L209 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/dataview.py | python | DataViewVirtualListModel.GetAttrByRow | (*args, **kwargs) | return _dataview.DataViewVirtualListModel_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.DataViewVirtualListModel_GetAttrByRow(*args, **kwargs) | [
"def",
"GetAttrByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewVirtualListModel_GetAttrByRow",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/dataview.py#L974-L982 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/dashboard/dashboard/utils.py | python | ServiceAccountCredentials | () | return client.SignedJwtAssertionCredentials(
service_account_name=account_details['client_email'],
private_key=account_details['private_key'],
scope=EMAIL_SCOPE) | Returns the Credentials of the service account if available. | Returns the Credentials of the service account if available. | [
"Returns",
"the",
"Credentials",
"of",
"the",
"service",
"account",
"if",
"available",
"."
] | def ServiceAccountCredentials():
"""Returns the Credentials of the service account if available."""
account_details = stored_object.Get(SERVICE_ACCOUNT_KEY)
if not account_details:
logging.error('Service account credentials not found.')
return None
return client.SignedJwtAssertionCredentials(
service_account_name=account_details['client_email'],
private_key=account_details['private_key'],
scope=EMAIL_SCOPE) | [
"def",
"ServiceAccountCredentials",
"(",
")",
":",
"account_details",
"=",
"stored_object",
".",
"Get",
"(",
"SERVICE_ACCOUNT_KEY",
")",
"if",
"not",
"account_details",
":",
"logging",
".",
"error",
"(",
"'Service account credentials not found.'",
")",
"return",
"None",
"return",
"client",
".",
"SignedJwtAssertionCredentials",
"(",
"service_account_name",
"=",
"account_details",
"[",
"'client_email'",
"]",
",",
"private_key",
"=",
"account_details",
"[",
"'private_key'",
"]",
",",
"scope",
"=",
"EMAIL_SCOPE",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/utils.py#L335-L344 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py | python | zeros | (shape, dtype=float) | return array(numeric.zeros(shape, dtype)) | zeros(n, dtype=float) =
an array of all zeros of the given length or shape. | zeros(n, dtype=float) =
an array of all zeros of the given length or shape. | [
"zeros",
"(",
"n",
"dtype",
"=",
"float",
")",
"=",
"an",
"array",
"of",
"all",
"zeros",
"of",
"the",
"given",
"length",
"or",
"shape",
"."
] | def zeros (shape, dtype=float):
"""zeros(n, dtype=float) =
an array of all zeros of the given length or shape."""
return array(numeric.zeros(shape, dtype)) | [
"def",
"zeros",
"(",
"shape",
",",
"dtype",
"=",
"float",
")",
":",
"return",
"array",
"(",
"numeric",
".",
"zeros",
"(",
"shape",
",",
"dtype",
")",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1576-L1579 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py | python | MultiIndexUIntEngine._codes_to_ints | (self, codes) | return np.bitwise_or.reduce(codes, axis=1) | Transform combination(s) of uint64 in one uint64 (each), in a strictly
monotonic way (i.e. respecting the lexicographic order of integer
combinations): see BaseMultiIndexCodesEngine documentation.
Parameters
----------
codes : 1- or 2-dimensional array of dtype uint64
Combinations of integers (one per row)
Returns
-------
scalar or 1-dimensional array, of dtype uint64
Integer(s) representing one combination (each). | Transform combination(s) of uint64 in one uint64 (each), in a strictly
monotonic way (i.e. respecting the lexicographic order of integer
combinations): see BaseMultiIndexCodesEngine documentation. | [
"Transform",
"combination",
"(",
"s",
")",
"of",
"uint64",
"in",
"one",
"uint64",
"(",
"each",
")",
"in",
"a",
"strictly",
"monotonic",
"way",
"(",
"i",
".",
"e",
".",
"respecting",
"the",
"lexicographic",
"order",
"of",
"integer",
"combinations",
")",
":",
"see",
"BaseMultiIndexCodesEngine",
"documentation",
"."
] | def _codes_to_ints(self, codes):
"""
Transform combination(s) of uint64 in one uint64 (each), in a strictly
monotonic way (i.e. respecting the lexicographic order of integer
combinations): see BaseMultiIndexCodesEngine documentation.
Parameters
----------
codes : 1- or 2-dimensional array of dtype uint64
Combinations of integers (one per row)
Returns
-------
scalar or 1-dimensional array, of dtype uint64
Integer(s) representing one combination (each).
"""
# Shift the representation of each level by the pre-calculated number
# of bits:
codes <<= self.offsets
# Now sum and OR are in fact interchangeable. This is a simple
# composition of the (disjunct) significant bits of each level (i.e.
# each column in "codes") in a single positive integer:
if codes.ndim == 1:
# Single key
return np.bitwise_or.reduce(codes)
# Multiple keys
return np.bitwise_or.reduce(codes, axis=1) | [
"def",
"_codes_to_ints",
"(",
"self",
",",
"codes",
")",
":",
"# Shift the representation of each level by the pre-calculated number",
"# of bits:",
"codes",
"<<=",
"self",
".",
"offsets",
"# Now sum and OR are in fact interchangeable. This is a simple",
"# composition of the (disjunct) significant bits of each level (i.e.",
"# each column in \"codes\") in a single positive integer:",
"if",
"codes",
".",
"ndim",
"==",
"1",
":",
"# Single key",
"return",
"np",
".",
"bitwise_or",
".",
"reduce",
"(",
"codes",
")",
"# Multiple keys",
"return",
"np",
".",
"bitwise_or",
".",
"reduce",
"(",
"codes",
",",
"axis",
"=",
"1",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexes/multi.py#L73-L101 | |
gnina/gnina | b9ae032f52fc7a8153987bde09c0efa3620d8bb6 | caffe/python/caffe/coord_map.py | python | coord_map | (fn) | Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords. | Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords. | [
"Define",
"the",
"coordinate",
"mapping",
"by",
"its",
"-",
"axis",
"-",
"scale",
":",
"output",
"coord",
"[",
"i",
"*",
"scale",
"]",
"<",
"-",
"input_coord",
"[",
"i",
"]",
"-",
"shift",
":",
"output",
"coord",
"[",
"i",
"]",
"<",
"-",
"output_coord",
"[",
"i",
"+",
"shift",
"]",
"s",
".",
"t",
".",
"the",
"identity",
"mapping",
"as",
"for",
"pointwise",
"layers",
"like",
"ReLu",
"is",
"defined",
"by",
"(",
"None",
"1",
"0",
")",
"since",
"it",
"is",
"independent",
"of",
"axis",
"and",
"does",
"not",
"transform",
"coords",
"."
] | def coord_map(fn):
"""
Define the coordinate mapping by its
- axis
- scale: output coord[i * scale] <- input_coord[i]
- shift: output coord[i] <- output_coord[i + shift]
s.t. the identity mapping, as for pointwise layers like ReLu, is defined by
(None, 1, 0) since it is independent of axis and does not transform coords.
"""
if fn.type_name in ['Convolution', 'Pooling', 'Im2col']:
axis, stride, ks, pad = conv_params(fn)
return axis, 1 / stride, (pad - (ks - 1) / 2) / stride
elif fn.type_name == 'Deconvolution':
axis, stride, ks, pad = conv_params(fn)
return axis, stride, (ks - 1) / 2 - pad
elif fn.type_name in PASS_THROUGH_LAYERS:
return None, 1, 0
elif fn.type_name == 'Crop':
axis, offset = crop_params(fn)
axis -= 1 # -1 for last non-coordinate dim.
return axis, 1, - offset
else:
raise UndefinedMapException | [
"def",
"coord_map",
"(",
"fn",
")",
":",
"if",
"fn",
".",
"type_name",
"in",
"[",
"'Convolution'",
",",
"'Pooling'",
",",
"'Im2col'",
"]",
":",
"axis",
",",
"stride",
",",
"ks",
",",
"pad",
"=",
"conv_params",
"(",
"fn",
")",
"return",
"axis",
",",
"1",
"/",
"stride",
",",
"(",
"pad",
"-",
"(",
"ks",
"-",
"1",
")",
"/",
"2",
")",
"/",
"stride",
"elif",
"fn",
".",
"type_name",
"==",
"'Deconvolution'",
":",
"axis",
",",
"stride",
",",
"ks",
",",
"pad",
"=",
"conv_params",
"(",
"fn",
")",
"return",
"axis",
",",
"stride",
",",
"(",
"ks",
"-",
"1",
")",
"/",
"2",
"-",
"pad",
"elif",
"fn",
".",
"type_name",
"in",
"PASS_THROUGH_LAYERS",
":",
"return",
"None",
",",
"1",
",",
"0",
"elif",
"fn",
".",
"type_name",
"==",
"'Crop'",
":",
"axis",
",",
"offset",
"=",
"crop_params",
"(",
"fn",
")",
"axis",
"-=",
"1",
"# -1 for last non-coordinate dim.",
"return",
"axis",
",",
"1",
",",
"-",
"offset",
"else",
":",
"raise",
"UndefinedMapException"
] | https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/python/caffe/coord_map.py#L57-L79 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/types.py | python | object_to_types | (object,world=None) | Returns a string defining the type of the given Python Klamp't object.
If multiple types could be associated with it, then it returns a list of all
possible valid types. | Returns a string defining the type of the given Python Klamp't object.
If multiple types could be associated with it, then it returns a list of all
possible valid types. | [
"Returns",
"a",
"string",
"defining",
"the",
"type",
"of",
"the",
"given",
"Python",
"Klamp",
"t",
"object",
".",
"If",
"multiple",
"types",
"could",
"be",
"associated",
"with",
"it",
"then",
"it",
"returns",
"a",
"list",
"of",
"all",
"possible",
"valid",
"types",
"."
] | def object_to_types(object,world=None):
"""Returns a string defining the type of the given Python Klamp't object.
If multiple types could be associated with it, then it returns a list of all
possible valid types."""
if isinstance(object,ContactPoint):
return 'ContactPoint'
elif isinstance(object,Hold):
return 'Hold'
elif isinstance(object,IKObjective):
return 'IKGoal'
elif isinstance(object,SE3Trajectory):
return ['SE3Trajectory','Trajectory']
elif isinstance(object,SO3Trajectory):
return ['SO3Trajectory','Trajectory']
elif isinstance(object,Trajectory):
return 'Trajectory'
elif isinstance(object,MultiPath):
return 'MultiPath'
elif isinstance(object,GeometricPrimitive):
return 'GeometricPrimitive'
elif isinstance(object,TriangleMesh):
return 'TriangleMesh'
elif isinstance(object,PointCloud):
return 'PointCloud'
elif isinstance(object,VolumeGrid):
return 'VolumeGrid'
elif isinstance(object,ConvexHull):
return 'ConvexHull'
elif isinstance(object,Geometry3D):
return ['Geometry3D',object.type()]
elif isinstance(object,WorldModel):
return 'WorldModel'
elif isinstance(object,RobotModel):
return 'RobotModel'
elif isinstance(object,RigidObjectModel):
return 'RigidObjectModel'
elif isinstance(object,TerrainModel):
return 'TerrainModel'
#this was here for Geometry3D, but might be mistaken with a SimRobotSensor.
#elif hasattr(object,'type'):
# if callable(object.type):
# return object.type()
# return object.type
elif hasattr(object,'__iter__'):
if len(object)>0 and hasattr(object[0],'__iter__'):
if isinstance(object[0],str):
if not all(isinstance(v,str) for v in object):
raise ValueError("Mixing string and other items in sequence?")
return 'StringArray'
#list of lists or tuples
if len(object)==2:
if len(object[0])==9 and len(object[1])==3:
#se3
return 'RigidTransform'
allequal = True
for entry in object:
if len(entry) != len(object[0]):
allequal = False
break
if allequal:
return 'Configs'
raise ValueError("Sequence of unequal-length types passed to object_to_types")
else:
dtypes = []
if any(isinstance(v,int) for v in object):
dtypes.append('int')
if any(isinstance(v,float) for v in object):
dtypes.append('float')
if any(isinstance(v,str) for v in object):
dtypes.append('str')
vtypes = []
if not str in dtypes:
vtypes.append('Config')
if not 'float' in dtypes:
vtypes.append('IntArray')
if len(object)==2:
#2d point
vtypes.append('Vector2')
elif len(object)==3:
#3d point
vtypes.append('Vector3')
elif len(object)==9:
#so3 or 9d point?
vtypes.append('Matrix3')
if vectorops.distance(so3.mul(so3.inv(object),object),so3.identity())<1e-5:
vtypes.append('Rotation')
else:
vtypes.append("StringArray")
if len(vtypes)==1:
return vtypes[0]
return vtypes
elif isinstance(object,(int,float)):
return 'Value'
else:
raise ValueError("Unknown object of type %s passed to object_to_types"%(object.__class__.__name__,)) | [
"def",
"object_to_types",
"(",
"object",
",",
"world",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"object",
",",
"ContactPoint",
")",
":",
"return",
"'ContactPoint'",
"elif",
"isinstance",
"(",
"object",
",",
"Hold",
")",
":",
"return",
"'Hold'",
"elif",
"isinstance",
"(",
"object",
",",
"IKObjective",
")",
":",
"return",
"'IKGoal'",
"elif",
"isinstance",
"(",
"object",
",",
"SE3Trajectory",
")",
":",
"return",
"[",
"'SE3Trajectory'",
",",
"'Trajectory'",
"]",
"elif",
"isinstance",
"(",
"object",
",",
"SO3Trajectory",
")",
":",
"return",
"[",
"'SO3Trajectory'",
",",
"'Trajectory'",
"]",
"elif",
"isinstance",
"(",
"object",
",",
"Trajectory",
")",
":",
"return",
"'Trajectory'",
"elif",
"isinstance",
"(",
"object",
",",
"MultiPath",
")",
":",
"return",
"'MultiPath'",
"elif",
"isinstance",
"(",
"object",
",",
"GeometricPrimitive",
")",
":",
"return",
"'GeometricPrimitive'",
"elif",
"isinstance",
"(",
"object",
",",
"TriangleMesh",
")",
":",
"return",
"'TriangleMesh'",
"elif",
"isinstance",
"(",
"object",
",",
"PointCloud",
")",
":",
"return",
"'PointCloud'",
"elif",
"isinstance",
"(",
"object",
",",
"VolumeGrid",
")",
":",
"return",
"'VolumeGrid'",
"elif",
"isinstance",
"(",
"object",
",",
"ConvexHull",
")",
":",
"return",
"'ConvexHull'",
"elif",
"isinstance",
"(",
"object",
",",
"Geometry3D",
")",
":",
"return",
"[",
"'Geometry3D'",
",",
"object",
".",
"type",
"(",
")",
"]",
"elif",
"isinstance",
"(",
"object",
",",
"WorldModel",
")",
":",
"return",
"'WorldModel'",
"elif",
"isinstance",
"(",
"object",
",",
"RobotModel",
")",
":",
"return",
"'RobotModel'",
"elif",
"isinstance",
"(",
"object",
",",
"RigidObjectModel",
")",
":",
"return",
"'RigidObjectModel'",
"elif",
"isinstance",
"(",
"object",
",",
"TerrainModel",
")",
":",
"return",
"'TerrainModel'",
"#this was here for Geometry3D, but might be mistaken with a SimRobotSensor.",
"#elif hasattr(object,'type'):",
"# if callable(object.type):",
"# return object.type()",
"# return object.type",
"elif",
"hasattr",
"(",
"object",
",",
"'__iter__'",
")",
":",
"if",
"len",
"(",
"object",
")",
">",
"0",
"and",
"hasattr",
"(",
"object",
"[",
"0",
"]",
",",
"'__iter__'",
")",
":",
"if",
"isinstance",
"(",
"object",
"[",
"0",
"]",
",",
"str",
")",
":",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"v",
",",
"str",
")",
"for",
"v",
"in",
"object",
")",
":",
"raise",
"ValueError",
"(",
"\"Mixing string and other items in sequence?\"",
")",
"return",
"'StringArray'",
"#list of lists or tuples",
"if",
"len",
"(",
"object",
")",
"==",
"2",
":",
"if",
"len",
"(",
"object",
"[",
"0",
"]",
")",
"==",
"9",
"and",
"len",
"(",
"object",
"[",
"1",
"]",
")",
"==",
"3",
":",
"#se3",
"return",
"'RigidTransform'",
"allequal",
"=",
"True",
"for",
"entry",
"in",
"object",
":",
"if",
"len",
"(",
"entry",
")",
"!=",
"len",
"(",
"object",
"[",
"0",
"]",
")",
":",
"allequal",
"=",
"False",
"break",
"if",
"allequal",
":",
"return",
"'Configs'",
"raise",
"ValueError",
"(",
"\"Sequence of unequal-length types passed to object_to_types\"",
")",
"else",
":",
"dtypes",
"=",
"[",
"]",
"if",
"any",
"(",
"isinstance",
"(",
"v",
",",
"int",
")",
"for",
"v",
"in",
"object",
")",
":",
"dtypes",
".",
"append",
"(",
"'int'",
")",
"if",
"any",
"(",
"isinstance",
"(",
"v",
",",
"float",
")",
"for",
"v",
"in",
"object",
")",
":",
"dtypes",
".",
"append",
"(",
"'float'",
")",
"if",
"any",
"(",
"isinstance",
"(",
"v",
",",
"str",
")",
"for",
"v",
"in",
"object",
")",
":",
"dtypes",
".",
"append",
"(",
"'str'",
")",
"vtypes",
"=",
"[",
"]",
"if",
"not",
"str",
"in",
"dtypes",
":",
"vtypes",
".",
"append",
"(",
"'Config'",
")",
"if",
"not",
"'float'",
"in",
"dtypes",
":",
"vtypes",
".",
"append",
"(",
"'IntArray'",
")",
"if",
"len",
"(",
"object",
")",
"==",
"2",
":",
"#2d point",
"vtypes",
".",
"append",
"(",
"'Vector2'",
")",
"elif",
"len",
"(",
"object",
")",
"==",
"3",
":",
"#3d point",
"vtypes",
".",
"append",
"(",
"'Vector3'",
")",
"elif",
"len",
"(",
"object",
")",
"==",
"9",
":",
"#so3 or 9d point?",
"vtypes",
".",
"append",
"(",
"'Matrix3'",
")",
"if",
"vectorops",
".",
"distance",
"(",
"so3",
".",
"mul",
"(",
"so3",
".",
"inv",
"(",
"object",
")",
",",
"object",
")",
",",
"so3",
".",
"identity",
"(",
")",
")",
"<",
"1e-5",
":",
"vtypes",
".",
"append",
"(",
"'Rotation'",
")",
"else",
":",
"vtypes",
".",
"append",
"(",
"\"StringArray\"",
")",
"if",
"len",
"(",
"vtypes",
")",
"==",
"1",
":",
"return",
"vtypes",
"[",
"0",
"]",
"return",
"vtypes",
"elif",
"isinstance",
"(",
"object",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"'Value'",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown object of type %s passed to object_to_types\"",
"%",
"(",
"object",
".",
"__class__",
".",
"__name__",
",",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/types.py#L24-L118 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py | python | Message.set_type | (self, type, header='Content-Type', requote=True) | Set the main type and subtype for the Content-Type header.
type must be a string in the form "maintype/subtype", otherwise a
ValueError is raised.
This method replaces the Content-Type header, keeping all the
parameters in place. If requote is False, this leaves the existing
header's quoting as is. Otherwise, the parameters will be quoted (the
default).
An alternative header can be specified in the header argument. When
the Content-Type header is set, we'll always also add a MIME-Version
header. | Set the main type and subtype for the Content-Type header. | [
"Set",
"the",
"main",
"type",
"and",
"subtype",
"for",
"the",
"Content",
"-",
"Type",
"header",
"."
] | def set_type(self, type, header='Content-Type', requote=True):
"""Set the main type and subtype for the Content-Type header.
type must be a string in the form "maintype/subtype", otherwise a
ValueError is raised.
This method replaces the Content-Type header, keeping all the
parameters in place. If requote is False, this leaves the existing
header's quoting as is. Otherwise, the parameters will be quoted (the
default).
An alternative header can be specified in the header argument. When
the Content-Type header is set, we'll always also add a MIME-Version
header.
"""
# BAW: should we be strict?
if not type.count('/') == 1:
raise ValueError
# Set the Content-Type, you get a MIME-Version
if header.lower() == 'content-type':
del self['mime-version']
self['MIME-Version'] = '1.0'
if header not in self:
self[header] = type
return
params = self.get_params(header=header, unquote=requote)
del self[header]
self[header] = type
# Skip the first param; it's the old type.
for p, v in params[1:]:
self.set_param(p, v, header, requote) | [
"def",
"set_type",
"(",
"self",
",",
"type",
",",
"header",
"=",
"'Content-Type'",
",",
"requote",
"=",
"True",
")",
":",
"# BAW: should we be strict?",
"if",
"not",
"type",
".",
"count",
"(",
"'/'",
")",
"==",
"1",
":",
"raise",
"ValueError",
"# Set the Content-Type, you get a MIME-Version",
"if",
"header",
".",
"lower",
"(",
")",
"==",
"'content-type'",
":",
"del",
"self",
"[",
"'mime-version'",
"]",
"self",
"[",
"'MIME-Version'",
"]",
"=",
"'1.0'",
"if",
"header",
"not",
"in",
"self",
":",
"self",
"[",
"header",
"]",
"=",
"type",
"return",
"params",
"=",
"self",
".",
"get_params",
"(",
"header",
"=",
"header",
",",
"unquote",
"=",
"requote",
")",
"del",
"self",
"[",
"header",
"]",
"self",
"[",
"header",
"]",
"=",
"type",
"# Skip the first param; it's the old type.",
"for",
"p",
",",
"v",
"in",
"params",
"[",
"1",
":",
"]",
":",
"self",
".",
"set_param",
"(",
"p",
",",
"v",
",",
"header",
",",
"requote",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py#L641-L671 | ||
raymondlu/super-animation-samples | 04234269112ff0dc32447f27a761dbbb00b8ba17 | samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py | python | Cursor.extent | (self) | return self._extent | Return the source range (the range of text) occupied by the entity
pointed at by the cursor. | Return the source range (the range of text) occupied by the entity
pointed at by the cursor. | [
"Return",
"the",
"source",
"range",
"(",
"the",
"range",
"of",
"text",
")",
"occupied",
"by",
"the",
"entity",
"pointed",
"at",
"by",
"the",
"cursor",
"."
] | def extent(self):
"""
Return the source range (the range of text) occupied by the entity
pointed at by the cursor.
"""
if not hasattr(self, '_extent'):
self._extent = conf.lib.clang_getCursorExtent(self)
return self._extent | [
"def",
"extent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_extent'",
")",
":",
"self",
".",
"_extent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorExtent",
"(",
"self",
")",
"return",
"self",
".",
"_extent"
] | https://github.com/raymondlu/super-animation-samples/blob/04234269112ff0dc32447f27a761dbbb00b8ba17/samples/cocos2d-x-3.1/CocosLuaGame2/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1288-L1296 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/dateutil/rrule.py | python | _rrulestr._handle_BYWEEKDAY | (self, rrkwargs, name, value, **kwargs) | Two ways to specify this: +1MO or MO(+1) | Two ways to specify this: +1MO or MO(+1) | [
"Two",
"ways",
"to",
"specify",
"this",
":",
"+",
"1MO",
"or",
"MO",
"(",
"+",
"1",
")"
] | def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs):
"""
Two ways to specify this: +1MO or MO(+1)
"""
l = []
for wday in value.split(','):
if '(' in wday:
# If it's of the form TH(+1), etc.
splt = wday.split('(')
w = splt[0]
n = int(splt[1][:-1])
elif len(wday):
# If it's of the form +1MO
for i in range(len(wday)):
if wday[i] not in '+-0123456789':
break
n = wday[:i] or None
w = wday[i:]
if n:
n = int(n)
else:
raise ValueError("Invalid (empty) BYDAY specification.")
l.append(weekdays[self._weekday_map[w]](n))
rrkwargs["byweekday"] = l | [
"def",
"_handle_BYWEEKDAY",
"(",
"self",
",",
"rrkwargs",
",",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"l",
"=",
"[",
"]",
"for",
"wday",
"in",
"value",
".",
"split",
"(",
"','",
")",
":",
"if",
"'('",
"in",
"wday",
":",
"# If it's of the form TH(+1), etc.",
"splt",
"=",
"wday",
".",
"split",
"(",
"'('",
")",
"w",
"=",
"splt",
"[",
"0",
"]",
"n",
"=",
"int",
"(",
"splt",
"[",
"1",
"]",
"[",
":",
"-",
"1",
"]",
")",
"elif",
"len",
"(",
"wday",
")",
":",
"# If it's of the form +1MO",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"wday",
")",
")",
":",
"if",
"wday",
"[",
"i",
"]",
"not",
"in",
"'+-0123456789'",
":",
"break",
"n",
"=",
"wday",
"[",
":",
"i",
"]",
"or",
"None",
"w",
"=",
"wday",
"[",
"i",
":",
"]",
"if",
"n",
":",
"n",
"=",
"int",
"(",
"n",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid (empty) BYDAY specification.\"",
")",
"l",
".",
"append",
"(",
"weekdays",
"[",
"self",
".",
"_weekday_map",
"[",
"w",
"]",
"]",
"(",
"n",
")",
")",
"rrkwargs",
"[",
"\"byweekday\"",
"]",
"=",
"l"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/dateutil/rrule.py#L1438-L1462 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/AWSPythonSDK/1.5.8/concurrent/futures/_base.py | python | Executor.shutdown | (self, wait=True) | Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other
methods can be called after this one.
Args:
wait: If True then shutdown will not return until all running
futures have finished executing and the resources used by the
executor have been reclaimed. | Clean-up the resources associated with the Executor. | [
"Clean",
"-",
"up",
"the",
"resources",
"associated",
"with",
"the",
"Executor",
"."
] | def shutdown(self, wait=True):
"""Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other
methods can be called after this one.
Args:
wait: If True then shutdown will not return until all running
futures have finished executing and the resources used by the
executor have been reclaimed.
"""
pass | [
"def",
"shutdown",
"(",
"self",
",",
"wait",
"=",
"True",
")",
":",
"pass"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/concurrent/futures/_base.py#L613-L624 | ||
snap-stanford/snap-python | d53c51b0a26aa7e3e7400b014cdf728948fde80a | setup/snap.py | python | TStrV.IsInBin | (self, *args) | return _snap.TStrV_IsInBin(self, *args) | IsInBin(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const & | IsInBin(TStrV self, TStr Val) -> bool | [
"IsInBin",
"(",
"TStrV",
"self",
"TStr",
"Val",
")",
"-",
">",
"bool"
] | def IsInBin(self, *args):
"""
IsInBin(TStrV self, TStr Val) -> bool
Parameters:
Val: TStr const &
"""
return _snap.TStrV_IsInBin(self, *args) | [
"def",
"IsInBin",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_snap",
".",
"TStrV_IsInBin",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L19926-L19934 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python/src/Lib/string.py | python | lower | (s) | return s.lower() | lower(s) -> string
Return a copy of the string s converted to lowercase. | lower(s) -> string | [
"lower",
"(",
"s",
")",
"-",
">",
"string"
] | def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower() | [
"def",
"lower",
"(",
"s",
")",
":",
"return",
"s",
".",
"lower",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/string.py#L222-L228 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/plugin.py | python | PluginManager.UpdateConfig | (self) | Updates the in memory config data to recognize
any plugins that may have been added or initialzed
by a call to InitPlugins.
@postcondition: plugins are enabled or disabled based
on the configuration data. | Updates the in memory config data to recognize
any plugins that may have been added or initialzed
by a call to InitPlugins.
@postcondition: plugins are enabled or disabled based
on the configuration data. | [
"Updates",
"the",
"in",
"memory",
"config",
"data",
"to",
"recognize",
"any",
"plugins",
"that",
"may",
"have",
"been",
"added",
"or",
"initialzed",
"by",
"a",
"call",
"to",
"InitPlugins",
".",
"@postcondition",
":",
"plugins",
"are",
"enabled",
"or",
"disabled",
"based",
"on",
"the",
"configuration",
"data",
"."
] | def UpdateConfig(self):
"""Updates the in memory config data to recognize
any plugins that may have been added or initialzed
by a call to InitPlugins.
@postcondition: plugins are enabled or disabled based
on the configuration data.
"""
for pdata in self._pdata.values():
plugin = pdata.GetClass()
if self._config.get(plugin.__module__):
self._enabled[plugin] = True
else:
self._config[plugin.__module__] = False
self._enabled[plugin] = False | [
"def",
"UpdateConfig",
"(",
"self",
")",
":",
"for",
"pdata",
"in",
"self",
".",
"_pdata",
".",
"values",
"(",
")",
":",
"plugin",
"=",
"pdata",
".",
"GetClass",
"(",
")",
"if",
"self",
".",
"_config",
".",
"get",
"(",
"plugin",
".",
"__module__",
")",
":",
"self",
".",
"_enabled",
"[",
"plugin",
"]",
"=",
"True",
"else",
":",
"self",
".",
"_config",
"[",
"plugin",
".",
"__module__",
"]",
"=",
"False",
"self",
".",
"_enabled",
"[",
"plugin",
"]",
"=",
"False"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/plugin.py#L845-L859 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/command/alias.py | python | shquote | (arg) | return arg | Quote an argument for later parsing by shlex.split() | Quote an argument for later parsing by shlex.split() | [
"Quote",
"an",
"argument",
"for",
"later",
"parsing",
"by",
"shlex",
".",
"split",
"()"
] | def shquote(arg):
"""Quote an argument for later parsing by shlex.split()"""
for c in '"', "'", "\\", "#":
if c in arg:
return repr(arg)
if arg.split() != [arg]:
return repr(arg)
return arg | [
"def",
"shquote",
"(",
"arg",
")",
":",
"for",
"c",
"in",
"'\"'",
",",
"\"'\"",
",",
"\"\\\\\"",
",",
"\"#\"",
":",
"if",
"c",
"in",
"arg",
":",
"return",
"repr",
"(",
"arg",
")",
"if",
"arg",
".",
"split",
"(",
")",
"!=",
"[",
"arg",
"]",
":",
"return",
"repr",
"(",
"arg",
")",
"return",
"arg"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/command/alias.py#L8-L15 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py | python | VersionControlSystem.__init__ | (self, options) | Constructor.
Args:
options: Command line options. | Constructor. | [
"Constructor",
"."
] | def __init__(self, options):
"""Constructor.
Args:
options: Command line options.
"""
self.options = options | [
"def",
"__init__",
"(",
"self",
",",
"options",
")",
":",
"self",
".",
"options",
"=",
"options"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L806-L812 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/mantid/plots/mantidaxes.py | python | MantidAxes._remove_workspace_artists | (self, workspace) | return True | Remove the artists reference by this workspace (if any) and return True
if the axes is then empty
:param workspace: A Workspace object
:return: True is an artist was removed False if one was not | Remove the artists reference by this workspace (if any) and return True
if the axes is then empty
:param workspace: A Workspace object
:return: True is an artist was removed False if one was not | [
"Remove",
"the",
"artists",
"reference",
"by",
"this",
"workspace",
"(",
"if",
"any",
")",
"and",
"return",
"True",
"if",
"the",
"axes",
"is",
"then",
"empty",
":",
"param",
"workspace",
":",
"A",
"Workspace",
"object",
":",
"return",
":",
"True",
"is",
"an",
"artist",
"was",
"removed",
"False",
"if",
"one",
"was",
"not"
] | def _remove_workspace_artists(self, workspace):
"""
Remove the artists reference by this workspace (if any) and return True
if the axes is then empty
:param workspace: A Workspace object
:return: True is an artist was removed False if one was not
"""
try:
# pop to ensure we don't hold onto an artist reference
artist_info = self.tracked_workspaces.pop(workspace.name())
except KeyError:
return False
for workspace_artist in artist_info:
workspace_artist.remove(self)
return True | [
"def",
"_remove_workspace_artists",
"(",
"self",
",",
"workspace",
")",
":",
"try",
":",
"# pop to ensure we don't hold onto an artist reference",
"artist_info",
"=",
"self",
".",
"tracked_workspaces",
".",
"pop",
"(",
"workspace",
".",
"name",
"(",
")",
")",
"except",
"KeyError",
":",
"return",
"False",
"for",
"workspace_artist",
"in",
"artist_info",
":",
"workspace_artist",
".",
"remove",
"(",
"self",
")",
"return",
"True"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/plots/mantidaxes.py#L369-L385 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py | python | _CompiledGrammar.match | (self, string: str) | return None | Match the string with the grammar.
Returns a :class:`Match` instance or `None` when the input doesn't match the grammar.
:param string: The input string. | Match the string with the grammar.
Returns a :class:`Match` instance or `None` when the input doesn't match the grammar. | [
"Match",
"the",
"string",
"with",
"the",
"grammar",
".",
"Returns",
"a",
":",
"class",
":",
"Match",
"instance",
"or",
"None",
"when",
"the",
"input",
"doesn",
"t",
"match",
"the",
"grammar",
"."
] | def match(self, string: str) -> Optional["Match"]:
"""
Match the string with the grammar.
Returns a :class:`Match` instance or `None` when the input doesn't match the grammar.
:param string: The input string.
"""
m = self._re.match(string)
if m:
return Match(
string, [(self._re, m)], self._group_names_to_nodes, self.unescape_funcs
)
return None | [
"def",
"match",
"(",
"self",
",",
"string",
":",
"str",
")",
"->",
"Optional",
"[",
"\"Match\"",
"]",
":",
"m",
"=",
"self",
".",
"_re",
".",
"match",
"(",
"string",
")",
"if",
"m",
":",
"return",
"Match",
"(",
"string",
",",
"[",
"(",
"self",
".",
"_re",
",",
"m",
")",
"]",
",",
"self",
".",
"_group_names_to_nodes",
",",
"self",
".",
"unescape_funcs",
")",
"return",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/contrib/regular_languages/compiler.py#L359-L372 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_core.py | python | Rect.GetSize | (*args, **kwargs) | return _core_.Rect_GetSize(*args, **kwargs) | GetSize(self) -> Size | GetSize(self) -> Size | [
"GetSize",
"(",
"self",
")",
"-",
">",
"Size"
] | def GetSize(*args, **kwargs):
"""GetSize(self) -> Size"""
return _core_.Rect_GetSize(*args, **kwargs) | [
"def",
"GetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"Rect_GetSize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L1309-L1311 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py | python | ErrorExit | (msg) | Print an error message to stderr and exit. | Print an error message to stderr and exit. | [
"Print",
"an",
"error",
"message",
"to",
"stderr",
"and",
"exit",
"."
] | def ErrorExit(msg):
"""Print an error message to stderr and exit."""
print >>sys.stderr, msg
sys.exit(1) | [
"def",
"ErrorExit",
"(",
"msg",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"msg",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/httplib2/upload-diffs.py#L156-L159 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/xmlreader.py | python | XMLReader.setEntityResolver | (self, resolver) | Register an object to resolve external entities. | Register an object to resolve external entities. | [
"Register",
"an",
"object",
"to",
"resolve",
"external",
"entities",
"."
] | def setEntityResolver(self, resolver):
"Register an object to resolve external entities."
self._ent_handler = resolver | [
"def",
"setEntityResolver",
"(",
"self",
",",
"resolver",
")",
":",
"self",
".",
"_ent_handler",
"=",
"resolver"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/xml/sax/xmlreader.py#L54-L56 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | Environment.add | (self, dist) | Add `dist` if we ``can_add()`` it and it has not already been added | Add `dist` if we ``can_add()`` it and it has not already been added | [
"Add",
"dist",
"if",
"we",
"can_add",
"()",
"it",
"and",
"it",
"has",
"not",
"already",
"been",
"added"
] | def add(self, dist):
"""Add `dist` if we ``can_add()`` it and it has not already been added
"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True) | [
"def",
"add",
"(",
"self",
",",
"dist",
")",
":",
"if",
"self",
".",
"can_add",
"(",
"dist",
")",
"and",
"dist",
".",
"has_version",
"(",
")",
":",
"dists",
"=",
"self",
".",
"_distmap",
".",
"setdefault",
"(",
"dist",
".",
"key",
",",
"[",
"]",
")",
"if",
"dist",
"not",
"in",
"dists",
":",
"dists",
".",
"append",
"(",
"dist",
")",
"dists",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'hashcmp'",
")",
",",
"reverse",
"=",
"True",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1030-L1037 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py | python | _real_valued_var_len_column | (column_name,
default_value=None,
dtype=dtypes.float32,
normalizer=None,
is_sparse=False) | return _RealValuedVarLenColumn(column_name, default_value, dtype, normalizer,
is_sparse) | Creates a `_RealValuedVarLenColumn` for variable-length numeric data.
Note, this is not integrated with any of the DNNEstimators, except the RNN
ones DynamicRNNEstimator and the StateSavingRNNEstimator.
It can either create a parsing config for a SparseTensor (with is_sparse=True)
or a padded Tensor.
The (dense_)shape of the result will be [batch_size, None], which can be used
with is_sparse=False as input into an RNN (see DynamicRNNEstimator or
StateSavingRNNEstimator) or with is_sparse=True as input into a tree (see
gtflow).
Use real_valued_column if the Feature has a fixed length. Use some
SparseColumn for columns to be embedded / one-hot-encoded.
Args:
column_name: A string defining real valued column name.
default_value: A scalar value compatible with dtype. Needs to be specified
if is_sparse=False.
dtype: Defines the type of values. Default value is tf.float32. Needs to be
convertible to tf.float32.
normalizer: If not None, a function that can be used to normalize the value
of the real valued column after default_value is applied for parsing.
Normalizer function takes the input tensor as its argument, and returns
the output tensor. (e.g. lambda x: (x - 3.0) / 4.2). Note that for
is_sparse=False, the normalizer will be run on the values of the
`SparseTensor`.
is_sparse: A boolean defining whether to create a SparseTensor or a Tensor.
Returns:
A _RealValuedSparseColumn.
Raises:
TypeError: if default_value is not a scalar value compatible with dtype.
TypeError: if dtype is not convertible to tf.float32.
ValueError: if default_value is None and is_sparse is False. | Creates a `_RealValuedVarLenColumn` for variable-length numeric data. | [
"Creates",
"a",
"_RealValuedVarLenColumn",
"for",
"variable",
"-",
"length",
"numeric",
"data",
"."
] | def _real_valued_var_len_column(column_name,
default_value=None,
dtype=dtypes.float32,
normalizer=None,
is_sparse=False):
"""Creates a `_RealValuedVarLenColumn` for variable-length numeric data.
Note, this is not integrated with any of the DNNEstimators, except the RNN
ones DynamicRNNEstimator and the StateSavingRNNEstimator.
It can either create a parsing config for a SparseTensor (with is_sparse=True)
or a padded Tensor.
The (dense_)shape of the result will be [batch_size, None], which can be used
with is_sparse=False as input into an RNN (see DynamicRNNEstimator or
StateSavingRNNEstimator) or with is_sparse=True as input into a tree (see
gtflow).
Use real_valued_column if the Feature has a fixed length. Use some
SparseColumn for columns to be embedded / one-hot-encoded.
Args:
column_name: A string defining real valued column name.
default_value: A scalar value compatible with dtype. Needs to be specified
if is_sparse=False.
dtype: Defines the type of values. Default value is tf.float32. Needs to be
convertible to tf.float32.
normalizer: If not None, a function that can be used to normalize the value
of the real valued column after default_value is applied for parsing.
Normalizer function takes the input tensor as its argument, and returns
the output tensor. (e.g. lambda x: (x - 3.0) / 4.2). Note that for
is_sparse=False, the normalizer will be run on the values of the
`SparseTensor`.
is_sparse: A boolean defining whether to create a SparseTensor or a Tensor.
Returns:
A _RealValuedSparseColumn.
Raises:
TypeError: if default_value is not a scalar value compatible with dtype.
TypeError: if dtype is not convertible to tf.float32.
ValueError: if default_value is None and is_sparse is False.
"""
if not (dtype.is_integer or dtype.is_floating):
raise TypeError("dtype must be convertible to float. "
"dtype: {}, column_name: {}".format(dtype, column_name))
if default_value is None and not is_sparse:
raise ValueError("default_value must be provided when is_sparse=False to "
"parse a padded Tensor. "
"column_name: {}".format(column_name))
if isinstance(default_value, list):
raise ValueError(
"Only scalar default value. default_value: {}, column_name: {}".format(
default_value, column_name))
if default_value is not None:
if dtype.is_integer:
default_value = int(default_value)
elif dtype.is_floating:
default_value = float(default_value)
return _RealValuedVarLenColumn(column_name, default_value, dtype, normalizer,
is_sparse) | [
"def",
"_real_valued_var_len_column",
"(",
"column_name",
",",
"default_value",
"=",
"None",
",",
"dtype",
"=",
"dtypes",
".",
"float32",
",",
"normalizer",
"=",
"None",
",",
"is_sparse",
"=",
"False",
")",
":",
"if",
"not",
"(",
"dtype",
".",
"is_integer",
"or",
"dtype",
".",
"is_floating",
")",
":",
"raise",
"TypeError",
"(",
"\"dtype must be convertible to float. \"",
"\"dtype: {}, column_name: {}\"",
".",
"format",
"(",
"dtype",
",",
"column_name",
")",
")",
"if",
"default_value",
"is",
"None",
"and",
"not",
"is_sparse",
":",
"raise",
"ValueError",
"(",
"\"default_value must be provided when is_sparse=False to \"",
"\"parse a padded Tensor. \"",
"\"column_name: {}\"",
".",
"format",
"(",
"column_name",
")",
")",
"if",
"isinstance",
"(",
"default_value",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"Only scalar default value. default_value: {}, column_name: {}\"",
".",
"format",
"(",
"default_value",
",",
"column_name",
")",
")",
"if",
"default_value",
"is",
"not",
"None",
":",
"if",
"dtype",
".",
"is_integer",
":",
"default_value",
"=",
"int",
"(",
"default_value",
")",
"elif",
"dtype",
".",
"is_floating",
":",
"default_value",
"=",
"float",
"(",
"default_value",
")",
"return",
"_RealValuedVarLenColumn",
"(",
"column_name",
",",
"default_value",
",",
"dtype",
",",
"normalizer",
",",
"is_sparse",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/layers/python/layers/feature_column.py#L1765-L1825 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGrid.OnTLPChanging | (*args, **kwargs) | return _propgrid.PropertyGrid_OnTLPChanging(*args, **kwargs) | OnTLPChanging(self, Window newTLP) | OnTLPChanging(self, Window newTLP) | [
"OnTLPChanging",
"(",
"self",
"Window",
"newTLP",
")"
] | def OnTLPChanging(*args, **kwargs):
"""OnTLPChanging(self, Window newTLP)"""
return _propgrid.PropertyGrid_OnTLPChanging(*args, **kwargs) | [
"def",
"OnTLPChanging",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGrid_OnTLPChanging",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2183-L2185 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.